nextLine()的问题; [英] Issues with nextLine();

查看:107
本文介绍了nextLine()的问题;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在nextInt之后使用nextLine时扫描程序问题

我正在尝试创建一个程序,它允许用户使用扫描仪将值输入到数组中。

I am trying create a program where it lets the user inputs values into an array using scanner.

然而,当程序要求学生的近亲时,它不会让用户输入任何内容并立即结束该程序。

However, when the program asks for the student's next of kin, it doesn't let the user to input anything and straight away ends the program.

以下是我所做的代码:

if(index!=-1)
    {
        Function.print("Enter full name: ");
        stdName = input.nextLine();

        Function.print("Enter student no.: ");
        stdNo = input.nextLine();

        Function.print("Enter age: ");
        stdAge = input.nextInt();

        Function.print("Enter next of kin: ");
        stdKin = input.nextLine();

        Student newStd = new Student(stdName, stdNo, stdAge, stdKin);
        stdDetails[index] = newStd;
    }

我尝试过使用next();但它只会取用户输入的第一个字而不是我想要的。无论如何都有解决这个问题的方法吗?

I have tried using next(); but it will only just take the first word of the user input which is not what I wanted. Is there anyway to solve this problem?

推荐答案

当你按下回车键时出现问题,这是一个换行符 \ n 字符。 nextInt()仅消耗整数,但它会跳过换行符 \ n 。要解决此问题,您可能需要在阅读 int 后添加额外的 input.nextLine(),它可以消耗 \ n

The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.

    Function.print("Enter age: ");
    stdAge = input.nextInt();
    input.nextLine();.

    // rest of the code

这篇关于nextLine()的问题;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆