【问题标题】:input for a String variable is skipped when it is preceeded by an integer input [duplicate]当字符串变量前面有一个整数输入时,它的输入被跳过[重复]
【发布时间】:2020-03-19 18:57:22
【问题描述】:

我正在练习扫描仪的使用和语法,下面是我编写的代码,我试图从用户那里获取 4 个输入:

    Scanner s= new Scanner(System.in);
    
    int a = s.nextInt();// taking an integer as input, it works fine.
    String b = s.nextLine();//was supposed to take a string input, but not working
    String c=s.nextLine();//takes a string as input from user
    String d=s.nextLine();//takes another string as input from user

    System.out.println("integer entered: "+a);
    System.out.println("first string entered: "+b);
    System.out.println("second string entered: "+c);
    System.out.println("third string entered: "+d);

但用户只能提供 3 个输入,第一个整数和其他两个字符串输入,并通过打印这 4 个变量的值,很明显第一个字符串 String b 的输入被跳过。然后我尝试重新排列输入的顺序,即,

String b = s.nextLine();//takes a string input
int a = s.nextInt();// taking an integer as input
String c=s.nextLine();//was supposed to take a string as input from user
String d=s.nextLine();//takes another string as input from user

在这种情况下,第二个字符串String c的输入被跳过。 那么,是不是因为整数输入跳过了下一个字符串输入?

【问题讨论】:

  • 您已经读取了带有Scanner.nextInt() 的第一行的整数,但没有读取它所在行的其余部分:.nextInt() 不使用换行符。在.nextInt() 之后添加一个额外的.nextLine() 以消耗并丢弃第一行的(空)其余部分。
  • 或 ParseInt the nextLine()... ;-)

标签: java string integer java.util.scanner


【解决方案1】:

这是一个常见的问题。


固定代码

Scanner s= new Scanner(System.in);
int a = s.nextInt();
s.nextLine();
System.out.print("Enter a string: ");
String b = s.nextLine();
System.out.print("Enter another string: ");
String c=s.nextLine();
System.out.print("Enter one more string: ");
String d=s.nextLine();

System.out.println(a+"\n"+b+d+c);

参考: Scanner is skipping nextLine() after using next() or nextFoo()?

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多