有兩個問題。我聽說最好使用switch語句,當你有超過3個'if'語句時。是這樣嗎?Java:對多表達式使用switch語句?
其次,可能有人查看下面的代碼,並給我一個想法就A.如何轉換成switch語句雖然是多表達或B.解釋爲什麼變量「級」總是導致F.
while (!"Y".equalsIgnoreCase(exit))
{
i++;
System.out.print("Please enter name of assignment " + i + ": ");
assignment = user.nextLine().toUpperCase(); //consumes string + \n
System.out.print("Please enter points earned: ");
earned = user.nextDouble();//consumes double
user.nextLine();//consumes \n
System.out.print("Please enter total points possible: ");
total = user.nextDouble();
user.nextLine();
System.out.print("Assignment\t"); System.out.print("Score\t"); System.out.print("Total Points\t"); System.out.print("Percentage\t\n");
System.out.print(assignment + "\t\t"); System.out.print(earned + "\t"); System.out.print(total + "\t\t"); System.out.print(percent.format(earned/total) + "\n\t");
// Putting user data into an array for calculation:
double[] calc; calc = new double[4];
calc[i] = earned; // Array elements coincide with the current iteration loop
double[] totalPoints; totalPoints = new double[4];
totalPoints[i] = total;
for (double e : calc) // adds up all the stored data in the array
sum += e;
for (double f : totalPoints) // adds up all the stored data in the array
tot += f;
char grade = '0';
if (sum/tot >= 90)
{
grade = 'A';
}
else if (sum/tot >= 80 && sum/tot <= 89.99)
{
grade = 'B';
}
else if (sum/tot >= 70 && sum/tot <= 79.99)
{
grade = 'C';
}
else if (sum/tot >= 60 && sum/tot <= 69.99)
{
grade = 'D';
}
else if (sum/tot <= 59.99)
{
grade = 'F';
}
System.out.println("Your total is " + sum + " out of " + tot + ", or " + percent.format(sum/tot) + ", and your grade is an " + grade);
}
如果變量持有這聽起來像他們持有,你需要'100'來劃分所有閾值。 – Keppil
如果不知道'sum'和'tot'的值,任何人都可以發表評論。 –
'switch'正在處理具體的值,而不是範圍 – nikis