1

I run my code then I put in an integer, press enter, then I get an extra input space. In the extra input space I put in a number then I get the input space I want where it says "Write A Line". It only adds the numbers I put in the first input space and the extra input space. Please help. (P.S Sorry for code's format)

My Output: Write An Integer (put my input here) (put my input here) Write An Integer (put my input here)

I don't want that 2nd input option.

public static void main(String eth[]){

System.out.println("Write An Integer");
Scanner input = new Scanner(System.in);


if (input.hasNextInt()){
}
else System.out.println("Play By The Rules");
Scanner input1 = new Scanner(System.in);
int a = input1.nextInt();
{

System.out.println("Write An Integer");
Scanner input2 = new Scanner(System.in);
int b = input2.nextInt();

int answer = (a+b); 
System.out.println(answer);

        }
    }
}   

3 Answers3

1

Well, if you are trying to add two numbers with strings in between, a better way to do it would be,

Scanner sr=new Scanner(System.in);
System.out.println("Play By The Rules")
int a=sr.nextInt();
System.out.println("Write An Integer");
int b = sr.nextInt();
int answer = (a+b); 
working
  • 811
  • 3
  • 11
  • 20
1

The extra space you're getting is from a logical error in first if statement. If input.hasNextInt() is true, then it will skip over else but call the Scanner directly below because it is not grouped with the else statement. Also, this only allows for two attempts for input1 and one for input2. Therefore, I'd switch to a while loop for each and create a method to read in integers instead of duplicating code.

public static void main(String eth[]) {
    int a = readInt();
    int b = readInt();
    int answer = (a + b);
    System.out.println(answer);
}
private static int readInt() {
    System.out.println("Write An Integer");
    Scanner input = null;
    while(!(input = new Scanner(System.in)).hasNextInt()){
        System.out.println("Play By The Rules, Write An Integer");
    }
    return input.nextInt();
}
Ray Hylock
  • 201
  • 1
  • 5
0

Use single instance for Scanner and make sure close the scanner input after operation

Refer code below

public static void main(String eth[]) {

    System.out.println("Write An Integer");
    Scanner input = new Scanner(System.in);

    if (input.hasNextInt()) {
    } else
        System.out.println("Play By The Rules");

    int a = input.nextInt();
    {
        System.out.println("Write An Integer");
        int b = input.nextInt();
        int answer = (a + b);
        System.out.println(answer);
        input.close();
    }
}
sudheer23
  • 1
  • 1