我想使用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