2015-12-10 56 views
0

我必須編寫一個程序,要求用戶輸入一個整數值。在每個值之後,如果用戶想要繼續該程序,則用戶必須以「y」或「n」作出響應,並且用戶輸入的每個數字被表示爲奇數或偶數,並且找出數字的平均值用戶輸入。我已經完成了這一切,但我很困惑兩點:尋找do-while循環中的最大值和小寫/大寫

  1. 我如何讓這個用戶可以鍵入既是資本和小寫字母y和程序仍會運行?到目前爲止,它僅適用於小寫的y。
  2. 此外,你將如何編程,以便在用戶輸入所有數字後,它會給你用戶輸入的最大號碼?例如:用戶輸入數字10,12,13,程序狀態「輸入的最高值是13」。

這是到目前爲止我的代碼:

import java.util.Scanner; 
class ProgramTest { 
    public static void main(String[] args) { 
     String answer = ""; 
     double sum = 0; 
     int count = 0; 
     do { 

      int num; 
      Scanner scan = new Scanner(System.in); 
      System.out.print("Enter any number : "); 
      num = scan.nextInt(); 

      if ((num % 2) == 0) System.out.println(num + " is an even number."); 
      else System.out.println(num + " is an odd number"); 
      sum += num; 
      System.out.println(("Would you like to enter another value(y/n)?:")); 
      answer = scan.next(); 
      count++; 

     } while (answer.equals("y")); 

     System.out.println("Average: " + (sum/count)); 
    } 
} 

回答

-1

String.equalsIgnoreCase(String anotherString) Java文檔較低和大寫y

至於最高/最低的數字,創建2個變量,如果它們爲空或低於/高於當前數字,請重新分配它們。在課程結束時,您將擁有適當的價值。

這太簡單了,不能提供代碼,所以上面的解釋已經足夠了。

+0

謝謝你低一點d大寫,但我不明白你的意思是什麼變數。我會在哪裏放置變量,如果一個數字大於另一個數字,我如何將它們重新分配給另一個數字? – Aaron

+0

原諒我,如果它看起來對你來說真的很基本,這是我第一年做Java和計算機編程的一般情況,我仍然習慣它。幫助將不勝感激。 – Aaron

-1
import java.util.Scanner; 
class ProgramTest { 
    public static void main(String[] args) { 
    String answer = ""; 
    double sum = 0; 
    int count = 0; 
    **int max = 0;** 
    do { 

     int num; 
     Scanner scan = new Scanner(System.in); 
     System.out.print("Enter any number : "); 

     num = scan.nextInt(); 

     if ((num % 2) == 0) System.out.println(num + " is an even number."); 
     else System.out.println(num + " is an odd number"); 
     sum += num; 
     System.out.println(("Would you like to enter another value(y/n)?:")); 

     **max = (num > max) ? num : max ;** 

     answer = scan.next(); 
     count++; 

    } while (answer.equals("y")); 

     System.out.println("Average: " + (sum/count)); 
     System.out.println("Highest : " + max); 
    } 
0

爲了得到區分大小寫的比較嘗試

while (answer.equalsIgnoreCase ("y")); 

對於最高和最低創建兩個新的變量do循環之前爲

int lowest = Integer.MAX_VALUE; 
int highest = Integer.MIN_VALUE; 

在你的循環做

lowest = Math.min (lowest, num); 
highest = Math.min (higest, num);