-1

With example below do not understand why console reads number but will not read String input

for(int i=0; i < 5; i++) {
    try(Scanner keyboardInput = new Scanner (System.in)){
    System.out.print("Enter five numbers: ");
    int num = keyboardInput.nextInt();
            
    System.out.println("Do you want to add this number to num(yes/no)?");
    String result = keyboardInput.nextLine();
    if(result == "yes") {
    total = num + total;
    System.out.print("The total is: " + total);

}}}

After I enter the value as required, current script does not let me enter String value. I have tried splitting sections of script by moving them to different braces but this just then does not identify variables that have been locally defined and even when I try to re-define variable code does not work.

If code completed in sections, the part that requires user entry of values works just fine. I an expecting to be able to have nextInt & nextLine user inputs to work together in same script.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Bukenke
  • 1
  • 1
  • 1
    In addition to your Scanner issues, don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Aug 06 '23 at 14:49
  • 1
    As an aside, I'd *strongly* advise you to follow normal Java indentation conventions. The code is really hard to read at the moment. What do you mean by "current script does not let me enter String value"? What happens? – Jon Skeet Aug 06 '23 at 14:49

0 Answers0