我想使用switch語句而不是一系列if/elses,但是當我運行代碼時只有前兩種情況正常運行而其他則被忽略。我用if條件測試過這些方法,它工作正常,但我想使用switch語句。 (一些方法我還沒有得到,因此評論)switch case does not work,instead of methods instead
輸入:A 25
輸出:25被添加到袋。
輸入:F 25
輸出:袋中有(1)25個。
輸入:S
輸出:(無)
預期輸出:Bag中有1個數字。
輸入:M
輸出:(無)
預期輸出:在袋的最小數爲25
import java.util.Scanner;
public class Bag {
int index = 0;
int[] array = new int[50];
public static void main(String[] args) {
int x = 0;
Bag bag = new Bag();
Scanner scan = new Scanner(System.in);
while (x == 0) {
System.out.print("Add(A), Delete(D), Find(F), Size(S), Min(m), Max(M), List(L), Quit(Q) >> ");
char c = scan.next().charAt(0);
int y = scan.nextInt();
switch(c) {
case 'A': bag.Add(y);
break;
//case 'D': bag.Delete(y);
//break;
case 'F': bag.Find(y);
break;
case 'S': bag.Size();
break;
case 'm': bag.Min();
break;
case 'M': bag.Max();
break;
/*case 'L': bag.List();
break;
case 'Q': bag.Quit();*/
}
}
}
public void Add(int y) {
array[index] = y;
index++;
System.out.println(" " + y + " is added to the Bag. ");
}
public void Find(int y)
{
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == y) {
count++;
}
}
System.out.println(" There is (" + count + ") " + y
+ " in the Bag.");
}
public void Size() {
System.out.println(" There are " + index + " numbers in the Bag.");
}
public void Min() {
int min = array[0];
for (int i = 1; i < index; i++) {
if(min > array[i]) {
min = array[i];
}
}
System.out.println(" The minimum number in the Bag is " + min + ".");
}
public void Max() {
int max = array[0];
for (int i = 1; i < index; i++) {
if(max < array[i]) {
max = array[i];
}
}
System.out.println(" The minimum number in the Bag is " + max + ".");
}
}
您的輸入是什麼?爲什麼它不「工作」? –
控制檯中有什麼錯誤? – brso05
當我輸入任何字母(在本例中爲m,M或S)時,請不要回傳任何東西,但是當我輸入A或F以及一個數字時,它可以正常工作。請輸入輸入,輸出和期望輸出 – Rehman