Java 扫描仪不工作
我有以下代码:Java 扫描仪不工作,java,string,terminal,java.util.scanner,Java,String,Terminal,Java.util.scanner,我有以下代码: byte[] nombre = new byte[20]; System.out.print("Cuenta a modificar: "); cuenta = s.nextInt(); boolean existe = estaRepetido(cuenta); if (existe == false){ Sys
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);
}
有什么想法吗?这只是一个非常大的方法的一部分,但这是唯一一个引起麻烦的扫描仪。方法离开\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
s或在其后使用单独的单词。当您想在扫描下一个输入之前等待用户输入键时,需要使用s.nextLine()
。
使用:
我认为这可能是因为您正在使用nextInt()而不是nextLine()来表示“cuenta”。
String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int
try {
cuenta = Integer.parseInt(s.nextLine());
} catch (Exception e){
//Do whatever you want.
}