2014-02-17 43 views
0

我有一個程序,允許用戶從4個選項中選擇: 1 - 年級組百分比 2 - 輸入等級 3 - 獲取平均 4 - 退出如何在一個循環中輸入大於1點的整數

該程序運行平穩,沒有編譯錯誤,我可以選擇每個選項,並讓文本行正確顯示。

我的問題是,當用戶選擇選擇2輸入成績時,他們如何在不執行的情況下輸入超過1個成績?目前,當你輸入一個等級時,按回車鍵,它會讓你回到主菜單,而不允許你輸入多於一個等級。下面是代碼:

import java.util.Scanner; 

public class ExerciseThree 
{ 
public static void main (String[] argsv) 
{ 

    float percent = 0; 
    double grade = 0; 
    double totalAvg = 0; 
    double total = 0; 
    double gradeAvg = 0; 

    int gradeCounter = 0; 
    int quit; 
    int choice = 0; 

    Scanner input = new Scanner (System.in); 


    while (choice != 4) 
    { 

    System.out.println("Please choose one of the following: \n 1 - Set percentage of total for new grades \n 2 - Enter new grades \n 3 - Get average \n 4 - Quit "); 
    choice = input.nextInt(); 



     switch (choice) 

     { 

      case 1:   
       System.out.println("Enter a percentage to multiply by (Format: 10% = .10)"); 
       percent = input.nextFloat(); 


      break; 



      case 2: 
       System.out.println("Enter grades"); 
       grade = input.nextDouble(); 
       total = total + grade; 
       gradeCounter = gradeCounter + 1; 
       gradeAvg = (double) total/gradeCounter; 

      break;  



      case 3: 
       System.out.println("You have chosen to get the average"); 
       totalAvg = totalAvg + percent * grade; 
       totalAvg = input.nextDouble();   
      break; 



      default: 
       System.out.println("You have chosen to quit"); 

      break; 


     } 

    } 


} 

} 
+0

我建議將部分這種邏輯的一種方法......不要試圖把它們都放在'主()'。 – crush

+0

我還沒有真正瞭解多種方法:s – user3304333

+0

所以你想如何工作可以請你解釋一下 –

回答

1

做一個循環,直到他們進入停止字符(例如空白字符)

case 2: 
      System.out.println("Enter grades"); 
      boolean isDone = false; 
      while(isDone == false) { 
       grade = input.nextDouble(); 
       if(grade == '') { 
        isDone = true; 
       } 
      } 
      total = total + grade; 
      gradeCounter = gradeCounter + 1; 
      gradeAvg = (double) total/gradeCounter; 
+0

但是雙打可以和charactars比較。負面評分呢? – TheDoctor

+0

雖然此答案不完整 - 您必須將這些值存儲在列表中。此外,我可能會要求輸入字符串(而不是nextDouble),如果它不是空白字符,則會進行雙倍轉換。 – jrowe08

0

怎麼樣的情況下塊while循環?

while (gradCounter < 4) { 
    System.out.println("Enter grades"); 
    grade = input.nextDouble(); 
    total = total + grade; 
    gradeCounter = gradeCounter + 1; 
    gradeAvg = (double) total/gradeCounter; 
} 
1
  System.out.print("How Many Grades You Enter"); 
      int s=input.nextInt(); 
      while(s>0) 
      {   
      System.out.println("Enter grades"); 
      grade = input.nextDouble(); 
      total = total + grade; 
      gradeCounter = gradeCounter + 1; 
      gradeAvg = (double) total/gradeCounter; 
      s--; 
      } 
相關問題