2016-11-25 6 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

Другой способ сделать это, что я нашел проще с arraylist, и регулярный цикл 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;} 
    } 
Смежные вопросы