0

I am working on a school project for Intro to CS and I can't post my code because our teacher fails us for getting code checked from StackOverflow. My issue is that in my code with the format :

while (condition){
Do something;

if (new condition){
Do something else;
Wait for input;
Depending on input make while's condition false;
}

This code should wait for input when the if statement is evaluated and it does something else. However, my code does not wait for "Wait for input" step and goes directly to the "Do something" step. Here's a bit of the code. Thank you for your help.

while (inum != 102) {
System.out.println("Enter a number between 1 and 100: ");
inum = input.nextInt();
else if (inum == 101) {
                System.out.println("Are you sure you want to quit?");
                confirm = input.nextLine();
                if (confirm == "yes") {
                    inum = 102;
                }
}

Here the code gives me this when I type in 101: Are you sure you want to quit? Enter a number between 1 and 100:

*The code does not wait for

confirm = input.nextLine();
                if (confirm == "yes") {
                    inum = 102;
                } 

step.

4 Answers4

2

The easiest way to solve your problem is calling

input.nextLine();

just below

inum = input.nextInt();

The reason is: when you type "101" in the console, you really type 101 and NEWLINE. nextInt() takes the 101 from the console buffer, but the NEWLINE character remains. For that reason, the second nextLine() in your code was skipped (the code assumed you entered a new empty line)

1
  1. You should use confirm.equals("yes").
  2. input is already use to input the number and declare another scanner object to input the confirm String.
Myat Min Soe
  • 787
  • 8
  • 32
0

Define an other input Scanner and don't use the same for both String and int Try this code (I put System.exist(0) so the program exit when you enter yes)

import java.util.Scanner;

public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
    int inum = 0;
    Scanner input = new Scanner(System.in);
    Scanner input1 = new Scanner(System.in);
    while (inum != 102) {
        System.out.println("Enter a number between 1 and 100: ");
        inum =  input.nextInt();
        if (inum == 101) {
            System.out.println("Are you sure you want to quit?");
            String confirm = input1.nextLine();
            if (confirm.equalsIgnoreCase("yes")) {
                inum = 102;
                System.exit(0);
            }
        }

    }
}
JHDev
  • 974
  • 2
  • 26
  • 38
0
if( StringUtils.equals(confirm, "yes") ) { ...
deanosaur
  • 621
  • 3
  • 5