2013-03-25 115 views
0

我有这样的代码:扫描仪无法操作

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 

有什么想法吗?这只是一个非常大的方法的一部分,但这是造成麻烦的唯一扫描仪。

+0

我认为这可能是由于您使用nextInt()而不是nextLine()为“CUENTA”。 – 2013-03-25 22:35:54

回答

1

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或单独的单词。

0

如果您想在扫描下一个输入之前等待用户输入密钥,则需要使用s.nextLine()。 用途:

try { 
    cuenta = Integer.parseInt(s.nextLine()); 
} catch (Exception e){ 
    //Do whatever you want. 
}