简体   繁体   中英

Java Scanner nextInt() make me hit enter twice for the value to be accepted

package ex3.io.excape;

import java.util.Scanner;

public class Prg {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    
    int a;
    System.out.print("a : ");
    a=scan.nextInt();

    System.out.println(a);
}
}

The result is following:

a : 3

3

To get this result, I had to hit enter twice. How can I get the result without the extra line in the middle and only hit enter once?

I tried

a=Integer.parseInt(scan.nextLine());

or

a=scan.nextInt();
scan.nextLine();

But it did not work...

Thanks in advance!

I tried this and it's took only 1 enter. I don't know why this taking 2 enter from you. Therefore, I made some basic changes in the code. Just run this and check this out if it is just a error from your compiler.

Scanner scan = new Scanner(System.in);
    
    int a;
    System.out.print("Enter a value of a: ");
    a=scan.nextInt();

    System.out.println("The value of a is: " +a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM