2016-11-25 74 views
0

我目前正在研究一個項目,要求我設置數據輸入。在數據輸入模式下,用戶將被要求在循環中輸入科學家數據。如果用戶以'y'迴應,他們將被提示輸入另一位科學家。我認爲可以這樣做的最佳方式是使用do-while循環來填充數組,直到用戶決定結束。我有麻煩Do-While循環來填充陣列

  1. 填充名稱到陣列中,並
  2. 初始循環之後的程序將不會提示輸入一個名稱。

以下是我有:

public class Scientist { 
    private String name; 
    private String field; 
    private String greatIdeas; 

    public static void main(String[] args) { 
     String scientists[] = new String[100]; 
     int scientistCount = 0; 
     Scanner input = new Scanner(System.in);  

     do{ 
      String answer; 
      System.out.println("Enter the name of the Scientist: ");   
      scientists[scientistCount]=input.nextLine(); 

      System.out.println(scientistCount); 
      System.out.println("Would You like to add another Scientist?"); 
      scientistCount++; 
     } 

     while(input.next().equalsIgnoreCase("Y")); 
     input.close(); 
    } 
} 
+0

你確實有什麼樣的麻煩? – Berger

+0

我無法使用do-while循環來填充數組,並且在初始循環之後,我不再提示輸入科學家名稱。 @Berger –

回答

1

始終傾向於使用nextLine()讀取輸入,然後解析字符串。

使用next()只會返回空格前的內容。返回當前行後,nextLine()自動移動掃描儀。

解析來自nextLine()的數據的有用工具是str.split("\\s+")

public class Scientist { 
     private String name; 
     private String field; 
     private String greatIdeas; 

     public static void main(String[] args) { 
      String scientists[] = new String[100]; 
      int scientistCount = 0; 
      Scanner input = new Scanner(System.in);  

      do{ 
       String answer; 
       System.out.println("Enter the name of the Scientist: ");   
       scientists[scientistCount]=input.nextLine(); 

       System.out.println(scientistCount); 
       System.out.println("Would You like to add another Scientist?"); 
       scientistCount++; 
      } 

      while(input.nextLine().equalsIgnoreCase("Y")); 
      input.close(); 
     } 
    } 
0

變化while(input.next().equalsIgnoreCase("Y"));while(input.nextLine().equalsIgnoreCase("Y"));

0

,這就是你的意思是

String scientists[] = new String[100]; 
    int scientistCount = 0; 
    Scanner input = new Scanner(System.in);  
    boolean again = true; 

    while(again){ 
     System.out.println("Enter the name of the Scientist: "); 
     scientists[scientistCount]=input.nextLine(); 
     scientistCount++; 
     System.out.println(scientistCount); 
     System.out.println("Would You like to add another Scientist? y/n"); 
     if(!input.nextLine().equalsIgnoreCase("y")){ 
      again = false; 
     } 
    } 
    input.close(); 
0

另一種方式的解決方案做到這一點,我覺得這更簡單的是使用數組列表,以及在更改布爾值後斷開的常規while循環。請參閱以下示例:

ArrayList<String> scientists = new ArrayList<String>(); 
    Scanner input = new Scanner(System.in); 
    boolean keepGoing = true; 

    while(keepGoing){ 
     System.out.println("Enter the name of the Scientist: "); 
     scientists.add(input.nextLine()); 
     System.out.println("Would You like to add another Scientist? (y/n)"); 

     if(input.nextLine().toLowerCase().equals("y")){continue;} 
     else{keepGoing = false;} 
    }