我有这个代码:
byte[] nombre = new byte[20];
System.out.print("Cuenta a modificar: ");
cuenta = s.nextInt();
boolean existe = estaRepetido(cuenta);
if (existe == false){
System.out.println("La cuenta no existe");
}
else {
String nomCliente;
System.out.print("Nombre: ");
nomCliente = s.nextLine();
System.out.print("Cantidad: ");
double cantidad = Double.parseDouble(s.nextLine());
for( int i = 0; i < 20 && i < nomCliente.getBytes().length; i++ ){
nombre[i] = nomCliente.getBytes()[i];
}
String nomModificar = new String (nombre);
modificar(cuenta, nomModificar, cantidad);
}
但是当在终端上运行时,它会以某种方式在海外运行 nomCliente = s.nextLine();以这样的方式结尾:
Cuenta a modificar: 0
Nombre: Cantidad: 0
有什么想法吗?这只是一个非常大的方法的一部分,但这是唯一造成麻烦的扫描仪。
最佳答案
nextInt()
方法留下 \n
(结束行)符号,并立即被 nextLine()
拾取,跳过下一个输入。您想要做的是对所有内容使用 nextLine()
,并稍后解析它:
String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int
这是迄今为止避免问题的最简单方法——不要混合您的“下一个”方法。仅使用 nextLine()
,然后解析 int
或单独的单词。
关于java - 扫描仪不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15626068/