【问题标题】:Getting accurate int and String input获取准确的 int 和 String 输入
【发布时间】:2011-11-26 20:48:17
【问题描述】:

在读取 int 后,我​​无法读取来自用户的字符串。本质上,我必须从用户那里得到一个 int,然后是几个字符串。我可以成功获取用户的int。但是,当我开始询问字符串(作者、主题等)时,我的扫描仪会“跳过”第一个字符串输入。

例如,我的输出如下所示: 输入您的选择: 2 输入作者: 输入主题: 主题

如您所见,用户永远无法输入作者,并且我的扫描仪将 null 存储到作者字符串中。

这是产生上述输出的代码:

    String author;
    String subject;
    int choice;
    Scanner input = new Scanner(System.in);

    System.out.println("Enter choice:");
    choice = input.nextInt();
    System.out.println("Enter author:");
    author = input.nextLine();
    System.out.println("Enter subject:");
    subject = input.nextLine();

任何帮助将不胜感激。谢谢! -普雷斯顿·多诺万

【问题讨论】:

    标签: java input io user-input java.util.scanner


    【解决方案1】:

    问题在于,当您使用readLine 时,它会从最后一个读取令牌读取到包含该令牌的当前 行的末尾。它不会自动移动到下一行然后读取整行。

    要么始终使用readLine,并在适当的情况下将字符串解析为整数,要么额外调用readLine

    System.out.println("Enter choice:");
    choice = input.nextInt();
    
    input.nextLine(); // Discard the rest of the line.
    
    System.out.println("Enter author:");
    author = input.nextLine();
    

    【讨论】:

      【解决方案2】:

      这非常有效。 虽然在制作像下面这样的以前的程序时,它不是必需的。谁能解释一下?

       import java.util.Scanner;
      
       public class Average Marks {
      
       public static void main(String[] args) {
        Scanner s = new Scanner ( System.in);
        System.out.print("Enter your name: ");
        String name=s.next();
        System.out.print("Enter marks in three subjects: ");
        int marks1=s.nextInt();
        int marks2=s.nextInt();
        int marks3=s.nextInt();
        double average = ( marks1+marks2+marks3)/3.0;
        System.out.println("\nName: "+name);
        System.out.println("Average: "+average);
      

      【讨论】:

        猜你喜欢
        • 2017-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多