Java Switch语句和Case

Java Switch语句和Case,java,for-loop,int,switch-statement,Java,For Loop,Int,Switch Statement,我正在为我的CPSC类制作代码,我必须打印一个为int设置的箱号。当我输入“2”时,代码会打印“两个土豆”八次,而不是“一个土豆,两个土豆” 以下是我的代码: public class Potato { public Potato() { } public void count(int c) { for (int i = 0; i < 8; i++) { switch (c % 8) { case 1: System

我正在为我的CPSC类制作代码,我必须打印一个为int设置的箱号。当我输入“2”时,代码会打印“两个土豆”八次,而不是“一个土豆,两个土豆”

以下是我的代码:

public class Potato {

public Potato() {
}

public void count(int c) {     


    for (int i = 0; i < 8; i++) {   
        switch (c % 8) {
            case 1:  System.out.println("One potato"); break;
            case 2:  System.out.println("two potato"); break;
            case 3:  System.out.println("three potato"); break;
            case 4:  System.out.println("four..."); break;
            case 5:  System.out.println("five potato"); break;
            case 6:  System.out.println("six potato"); break;
            case 7:  System.out.println("seven potato"); break;
            case 8:  System.out.println("more!"); break;
            default: break; 
        }
    }


}
}
公共类{
公共马铃薯(){
}
公共无效计数(INTC){
对于(int i=0;i<8;i++){
开关(c%8){
案例1:System.out.println(“一个土豆”);中断;
案例2:System.out.println(“两个土豆”);中断;
案例3:System.out.println(“三个土豆”);中断;
案例4:System.out.println(“四…”);中断;
案例5:System.out.println(“五个土豆”);中断;
案例6:System.out.println(“六个土豆”);中断;
案例7:System.out.println(“七个土豆”);中断;
案例8:System.out.println(“更多!”);中断;
默认:中断;
}
}
}
}

我想我的问题是我的for循环,但不太确定,因为我在这里寻求帮助。提前谢谢

这是因为
c%8(2%8=2)
,所以在每个循环中,它将执行
案例2
,并打印
两个土豆。您可以使用
i%8

此代码是。。。特别的:

主要问题是您没有使用在
for
循环中递增的
i
变量。相反,您使用的是
c
变量:

switch (c % 8)
应该是:

switch (i % 8)

您不需要
案例8
,因为
i%8
不可能产生8。而且,看起来您根本不需要
c
变量。

这就可以了。正如其他人所说,您应该使用
i%8
。但是,要使其起作用,您还应该从
i=1
开始,因为
0%8=0
。您的
案例8
应更改为
案例0

for (int i = 1; i <= c; i++) {
    switch (i % 8) {
        case 1: System.out.println("One potato"); break;
        case 2: System.out.println("two potato"); break;
        case 3: System.out.println("three potato"); break;
        case 4: System.out.println("four..."); break;
        case 5: System.out.println("five potato"); break;
        case 6: System.out.println("six potato"); break;
        case 7: System.out.println("seven potato"); break;
        case 0: System.out.println("more!"); break;
        default: break;
    }
}

用于(int i=1;我为什么需要'for'循环?for
循环的意义是什么?你从不使用循环变量
i
。教授说把switch语句放在一个正确计算int计数器的循环中。我认为for循环会起作用,无论如何,让我知道是否有更好的解决方案。你有
i
你的循环,但是你的开关中有
c
。为什么
%8
?我要离开教授给我的一个包含%8的例子