有没有一种方法只能对多个整数使用一个for循环?目前,我只为int num0编写了代码。但是有没有办法在相同的代码中保留其余的num1,num2,num3?我之所以要求这样做,是因为我没有作为程序员的经验,所以我想知道你们是否知道有解决方案。 (对不起,我的语法不好)
public void exercise1c() {
int num0, num1, num2, num3;
num0 = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
num1 = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
num2 = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
num3 = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
for (int i = 0; i <= num0; i++) {
if (num0 <= 0) {
System.out.println("Number "+ num0 + " is negative.");
break;
}
}
if (num0 >= 0) {
System.out.println(num0 + " is a integer.");
}
if (num0 == 0){
System.out.println(num0 + " is zero.");
}
}
最佳答案
将num0, num1, num2, num3
添加到List
或array
中,然后可以使用单个for
循环
例如:使用int[]
int[] num = new int[4];
num[0] = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
num[1] = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
num[2] = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
num[3] = Integer.parseInt(JOptionPane.showInputDialog("Write a number."));
for (int i = 0; i < num.length; i++) {
if (num[i] < 0) {
System.out.println("Number " + num[i] + " is negative.");
break;
}
if (num[i] > 0) {
System.out.println(num[i] + " is a integer.");
}
if (num[i] == 0) {
System.out.println(num[i] + " is zero.");
}
}
如何使用
List
例如:
List<Integer> numList = new ArrayList<>();
numList.add(Integer.parseInt(JOptionPane.showInputDialog("Write a number.")));
numList.add(Integer.parseInt(JOptionPane.showInputDialog("Write a number.")));
numList.add(Integer.parseInt(JOptionPane.showInputDialog("Write a number.")));
numList.add(Integer.parseInt(JOptionPane.showInputDialog("Write a number.")));
for (Integer i :numList) {
if (i < 0) {
System.out.println("Number " + i + " is negative.");
break;
}
if (i > 0) {
System.out.println(i + " is a integer.");
}
if (i == 0) {
System.out.println(i + " is zero.");
}
}