jl9*_*l90 11 java java.util.scanner
我正在尝试创建一个程序,它允许用户使用扫描仪将值输入到数组中.
但是,当程序要求学生的近亲时,它不会让用户输入任何内容并立即结束该程序.
以下是我所做的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过使用next(); 但它只会取用户输入的第一个字而不是我想要的.反正有没有解决这个问题?
Swa*_*nil 23
当您按Enter键时出现问题,这是一个换行符\n.nextInt()仅消耗整数,但它会跳过换行符\n.要解决这个问题,您可能需要input.nextLine()在阅读之后再添加一个int,这可以消耗\n.
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();.
// rest of the code
Run Code Online (Sandbox Code Playgroud)
问题是input.nextInt()这个函数只读取int值.因此,当您继续阅读时,input.nextLine()您会收到"\n" Enter键.所以要跳过这个你必须添加input.nextLine().
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();
Run Code Online (Sandbox Code Playgroud)
为什么next()不工作..?
next()返回下一个标记,nextLine()返回NextLine.如果我们知道差异就很好.令牌是由空格包围的非空白字符串.
来自Doc
查找并返回此扫描程序中的下一个完整令牌.在完成令牌之前和之后是与分隔符模式匹配的输入.即使之前的hasNext()调用返回true,此方法也可能在等待输入扫描时阻塞.
| 归档时间: |
|
| 查看次数: |
37994 次 |
| 最近记录: |