0

I am making a code for a project. When I input for example

Harry + John
Harry * James
finish

The output should be

HarryJohn
HarryHarryHarryHarryHarry
End

However, my current output is

HarryJohn
HarryHarryHarryHarryHarry

End

I have to press enter in order for the program to print "End" and finish. Is there any way for me to not press enter in order to finish running my code?

The following is the code I have written so far.

public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    String str1 = in.next();
    while (!str1.equals("finish")) {
        String op = in.next();
        String str2 = in.next();
        if (op.equals("+")){
            System.out.println(str1 + str2);
        }
        else if (op.equals("*")){
            for (int i = 0; i < str2.length(); i++){
                System.out.print(str1);
            }
            System.out.println();
        }
        else {
            System.out.println("wrong");
        }
        String blankStr = in.nextLine();
        str1 = in.next();
    }
    System.out.println("End");
}
Dylan
  • 103
  • 6
  • Debugger/IDE is the tool to resolve problems like this – Alex Shesterov Sep 20 '21 at 17:28
  • Does [How to read a single char from the console in Java (as the user types it)?](https://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) helps you? – J.F. Sep 20 '21 at 17:32
  • Actually I already tried debugging using the Debugger, but I failed to see the problem. I also think this is a different problem from what J.F. has suggested. – Dylan Sep 20 '21 at 17:36
  • Consider adding a space after "finish " in input – Vasanth Subramanian Sep 20 '21 at 17:52

1 Answers1

0

Because while loop is running one more time as the contdition is not checked before the loop begins,so it will run an extra time then check the c