2013-10-27 115 views
-1

嘿,我試圖從用戶一個接一個輸入,但它似乎採取錯誤的輸入......它實際上跳過了從用戶採取的一個輸入.. eg.in下面的代碼我想取的名頭再處理,並在最後一次接觸,但是當我這樣做它跳過輸入名稱...不正確的輸入掃描器

import java.util.ArrayList; 
import java.util.Scanner; 
public class mainClass { 
    public static void main(String args[]){ 

     int value = 0; 
     ArrayList<Data> Contacts = new ArrayList<Data>(); 
     Scanner input = new Scanner(System.in); 
     while(true){ 
      System.out.println("Enter 1 to add a Contact :: Enter 2 to View all Contact"); 
      value = input.nextInt(); 

      switch(value){ 

      case 1: 

       System.out.println("Plz enter Name : "); 
       String name = input.nextLine(); 
       System.out.println("Plz enter Address : "); 
       String address = input.nextLine(); 
       System.out.println("Plz enter ContactNo : "); 
       String contact = input.nextLine(); 

       Data objt1 = new Data(name, address, contact); 
       Contacts.add(objt1); 

       break; 
      case 2: 

       System.out.println("Name\t\tContact\t\tAddress"); 

       for(int i=0; i<Contacts.size(); i++) 
       { 

        System.out.println(Contacts.get(i)); 
       } 

       break; 
      default: 
       System.out.println("Sorry wrong input"); 

      } 



     } 
    } 
} 

數據類是在這裏

public class Data { 

     private String name = ""; 
     private String address = ""; 
     private String cell = ""; 


     public Data(String n, String a, String c){ 

      name = n; 
      address = a; 
      cell = c; 
     } 

     public String toString() 
     { 
      return String.format("%s\t\t%s\t\t%s", name, cell, address); 
     } 
} 

回答

0

嘗試獲得價值後加入input.nextLine();,這將消耗新的行字符

value = input.nextInt(); 
input.nextLine(); 

(或)

int value = Integer.parseInt(input.nextLine()); 
+0

先生,但實際上我想inputfirst因爲交換機有int值 – Johnfranklien

+0

非常感謝先生它的工作原理採用整數... @uopg – Johnfranklien