2015-02-26 2 views
0

Я сделал простую программу, которая имеет выбор добавления, голосования и просмотра голосов на 3 разных кандидата. По какой-то причине строка 18 повторяет себя и линию 72 после нее, например, если вы начинаете, нажмите 1, чтобы создать кандидата, введите имя и нажмите enter, он будет проходить следующим образом:Почему линия повторяется во время цикла?

Add candidate (1) or vote (2) or view number of votes on each candidate (3): Incorrect number, please try again. 

, но затем возвращается в нормальное русло ...

Add candidate (1) or vote (2) or view number of votes on each candidate (3): 

Вот весь код (повторяющиеся строки отмечены):

package array; 

import java.util.Scanner; 

public class Array { 

    public static void main(String[] args) { 
     char[] Vote_Choice = {'A', 'B', 'C'}; 
     String[] candidates = { "none", "none", "none"}; 
     int[] votes = {0, 0, 0}; 


     Scanner input = new Scanner(System.in); 
     boolean done = false; 

     while (!done) { 
      boolean done2 = false; 
       System.out.print("Add candidate (1) or vote (2) or view number of votes on each candidate (3): "); // here (line 18) 

      switch (input.nextLine()) { 
       case "1": System.out.print("Type new candidates name: "); 
        while (!done2) { 
         if (candidates[0].equals("none")) { 
         candidates[0] = input.next(); 
         done2 = true; 
        } 
         else if (!candidates[0].equals("none") && candidates[1].equals("none")) { 
         candidates[1] = input.next(); 
         done2 = true; 

        } 
        else if (!candidates[0].equals("none") && !candidates[1].equals("none") && candidates[2].equals("none")) { 
         candidates[2] = input.next(); 
         done2 = true; 
        } 
        else if (!candidates[0].equals("none") && !candidates[1].equals("none") && !candidates[2].equals("none")) { 
         System.out.println("Sorry, all candidate slots are full."); 
         done2 = true; 
        } 
        } 
         break; 
       case "2": 
        System.out.println("Type letter corresponding to the candidate you wish to vote for: "); 

        System.out.print("Type A for candidate "+ candidates[0] +", type B for candidate "+candidates[1]+", type C for candidate "+candidates[2]+": "); 
        String choice = input.next(); 
        if (choice.equals("A")) { 
         votes[0]++; 
        } 
        if (choice.equals("B")) { 
         votes[1]++; 
        } 
        if (choice.equals("C")) { 
         votes[2]++; 
        } 


        break; 
       case "3": if (!candidates[0].equals("none")) { 
        System.out.println("Candidate "+ candidates[0] +": "+votes[0]); 
       } 
          if (!candidates[1].equals("none")) { 
        System.out.println("Candidate "+ candidates[1] +": "+votes[1]); 
       } 
          if (!candidates[2].equals("none")) { 
        System.out.println("Candidate "+ candidates[2] +": "+votes[2]); 
       } 
          else { 
           System.out.println("Sorry, there are no current candidates."); 
          } 
       break; 
       default: System.out.println("Incorrect number, please try again."); // And here, line 72 
      }  

     } 


    } 
} 
+0

Помните, что мы не можем видеть, какая линия линия 18, или какая линия линия 72. – ThePerson

+0

я отметил, рядом с линиями, которые затронуты, вы просто должны смотреть :) – LuketheWillyman

+0

Любой шанс, что вы тоже можете отступать от кода? Случай 1 становится особенно трудным для чтения, потому что закрывающая фигурная скобка, которая выглядит так, как она принадлежит петле while, фактически принадлежит if. Это может показаться педантичным, но если ваш код трудно читать, люди не захотят его читать :). Если вы используете eclipse, одновременно нажмите Ctrl + Shift + F или Command-Shift-F на mac. – ThePerson

ответ

1

Это потому, что у вас есть input.next() вместо input.nextLine() есть. Конец строки «остается» во входном потоке, и когда вы вызываете его, он возвращает то, что осталось в этом потоке (часто пустая строка).

0

Когда вы звоните:

candidates[1] = input.next(); 

Это вызывает проблему, поскольку она потребляет только часть входного сигнала.

Если рассматривать входной поток с клавиатуры может быть что-то вроде: 1 \ nDavid \ п

Что происходит, вы читаете «1 \ П», когда вы читаете строку, а затем, когда вы читаете «далее» вы читаете «Давид», но не новые символы строки, поэтому в следующий раз, когда вы вызываете nextLine, вы получаете пустую строку, начиная с \ n (\ n - это новый символ строки).

Ваш код должен быть:

import java.util.Scanner; 

public class Array { 

    public static void main(String[] args) { 
     char[] Vote_Choice = { 'A', 'B', 'C' }; 
     String[] candidates = { "none", "none", "none" }; 
     int[] votes = { 0, 0, 0 }; 

     Scanner input = new Scanner(System.in); 
     boolean done = false; 

     while (!done) { 
      boolean done2 = false; 
      System.out 
        .print("Add candidate (1) or vote (2) or view number of votes on each candidate (3): "); // here 
                               // (line 
                               // 18) 

      switch (input.nextLine()) { 
      case "1": 
       System.out.print("Type new candidates name: "); 
       while (!done2) { 
        if (candidates[0].equals("none")) { 
         candidates[0] = input.nextLine(); 
         done2 = true; 
        } else if (!candidates[0].equals("none") 
          && candidates[1].equals("none")) { 
         candidates[1] = input.nextLine(); 
         done2 = true; 

        } else if (!candidates[0].equals("none") 
          && !candidates[1].equals("none") 
          && candidates[2].equals("none")) { 
         candidates[2] = input.nextLine(); 
         done2 = true; 
        } else if (!candidates[0].equals("none") 
          && !candidates[1].equals("none") 
          && !candidates[2].equals("none")) { 
         System.out 
           .println("Sorry, all candidate slots are full."); 
         done2 = true; 
        } 
       } 
       break; 
      case "2": 
       System.out 
         .println("Type letter corresponding to the candidate you wish to vote for: "); 

       System.out.print("Type A for candidate " + candidates[0] 
         + ", type B for candidate " + candidates[1] 
         + ", type C for candidate " + candidates[2] + ": "); 
       String choice = input.nextLine(); 
       if (choice.equals("A")) { 
        votes[0]++; 
       } 
       if (choice.equals("B")) { 
        votes[1]++; 
       } 
       if (choice.equals("C")) { 
        votes[2]++; 
       } 

       break; 
      case "3": 
       if (!candidates[0].equals("none")) { 
        System.out.println("Candidate " + candidates[0] + ": " 
          + votes[0]); 
       } 
       if (!candidates[1].equals("none")) { 
        System.out.println("Candidate " + candidates[1] + ": " 
          + votes[1]); 
       } 
       if (!candidates[2].equals("none")) { 
        System.out.println("Candidate " + candidates[2] + ": " 
          + votes[2]); 
       } else { 
        System.out 
          .println("Sorry, there are no current candidates."); 
       } 
       break; 
      default: 
       System.out.println("Incorrect number, please try again."); // And 
                      // here, 
                      // line 
                      // 72 
      } 

     } 

    } 
} 
Смежные вопросы