【发布时间】:2019-06-17 21:40:03
【问题描述】:
我正在尝试使用 switch 语句来迭代 for 循环。我想打印该 switch 语句中的特定数据。
我在一个数组中获取数据,比如 5,6,并且我正在通过 switch 语句使用这个数组长度迭代循环。它应该只从 switch 语句中打印第 5 和第 6 个值。但它不起作用。
它在下面输出::::
字符串值的连接 打印 11 字符串值的连接 打印 1
public class String_Concat {
public void concat(int n){
System.out.println("Concatination of String value");
switch (n)
{
case 1 :
System.out.println("Print 1");
break;
case 2 :
System.out.println("Print 2");
break;
case 3 :
System.out.println("Print 3");
break;
case 4 :
System.out.println("Print 4");
break;
case 5 :
System.out.println("Print 5");
break;
case 6 :
System.out.println("Print 6");
break;
case 7 :
System.out.println("Print 7");
break;
case 8 :
System.out.println("Print 8");
break;
case 9 :
System.out.println("Print 9");
break;
case 10 :
System.out.println("Print 10");
break;
default :
System.out.println("Print 11");
}
}
public static void main(String[] rags){
String[] nums={"5","6"};
String_Concat st=new String_Concat();
for(int i=0;i<nums.length;i++){
st.concat(i);
}
}
}
【问题讨论】:
-
当然,为什么不呢,但是您在某种程度上编写了很多过时的代码,并且没有按照注释中的说明进行操作(字符串连接)
-
开关不是迭代,开关只能与一个值比较
-
我想你是想写
st.concat(Integer.parseInt(nums[i])); -
清道夫是对的。您当前正在传递这些元素的索引,即 0 和 1。0 将打印 11,1 将打印 1
标签: java for-loop switch-statement