2013-03-25 112 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. 
}