The problem I seek to solve is a game of cups. The user enters a string with no spaces of a series of connected A's, B's, and C's. An example is "AB" or "ABBBCABA". The game is that the player moves the cup of the letter selected. The prize begins in position 1, or the leftmost cup. Here is a picture that helps visualize the movements.
An example move entered "AB" should output 3. An example move of "BC" should output 3.
My code is giving incorrect numbers but I can't figure out where I went wrong logically.
import java.io.*; public class trik { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine(); int position = 1; if (s.length() == 1) { // A if (s.contains("A")) { System.out.println(2); } if (s.contains("B")) { System.out.println(1); } if (s.contains("C")) { System.out.println(3); } } else { String[] parts = s.split(""); int i = 0; while (i < parts.length) { if (parts[i].equals("A")) { if (position != 3) { if (position == 1) { position = 2; } if (position == 2) { position = 1; } } } if (parts[i].equals("B")) { if (position != 1) { if (position == 2) { position = 3; } if (position == 3) { position = 2; } } } if (parts[i].equals("C")) { if (position != 2) { if (position == 1) { position = 3; } if (position == 3) { position = 1; } } } i++; } System.out.println(position); } } }
https://stackoverflow.com/questions/65894569/how-can-i-fix-this-if-then-structure-to-break-out-of-the-loop-as-needed January 26, 2021 at 09:08AM
没有评论:
发表评论