gpt4 book ai didi

java - 如何为多个整数创建 1 个 for 循环?

转载 作者:行者123 更新时间:2023-12-01 18:26:09 24 4
gpt4 key购买 nike

有没有一种方法可以只使用一个 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数组中,然后您可以使用单个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<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.");
}
}

关于java - 如何为多个整数创建 1 个 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26119362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com