gpt4 book ai didi

java - 有没有办法让整个代码更短?

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

我目前正在为这项任务的一件事而苦苦挣扎。我只是想要一种使整个代码更短的方法,甚至只是一点点(特别是 if 语句)。

package Integers;

import java.util.Scanner;

public class SumOfInt {
public static void main(String[] args) {
int positive = 0;

System.out.println ("-Input ten non-zero integers to calculate their sum. " + "\n" + "-Input the integers at the console and press <Enter>" + "\n");

System.out.println ("Input the 1st integer:");
Scanner input = new Scanner (System.in);
int num1 = input.nextInt ();

System.out.println ("Input the 2nd integer:");
int num2 = input.nextInt ();

System.out.println ("Input the 3rd integer:");
int num3 = input.nextInt ();

System.out.println ("Input the 4th integer:");
int num4 = input.nextInt ();

System.out.println ("Input the 5th integer:");
int num5 = input.nextInt ();

{ if (num1 > 0)
positive++;
}
{ if (num2 > 0)
positive++;
}
{ if (num3 > 0)
positive++;
}
{ if (num4 > 0)
positive++;
}
{ if (num5 > 0)
positive++;
}

System.out.println ("The number of positive integers are: " + positive);
}
}

最佳答案

如果您发现自己一遍又一遍地编写非常相似的代码(甚至是复制粘贴的内容),那么总有一种方法可以概括代码并将其放入 for 循环或额外的方法中。这就是要走的路。在您的情况下,您可以简单地使用 for 循环。

public static void main(String[] args) {
int positive = 0;
System.out.println("Input the integers at the console and press <Enter>");

Scanner input = new Scanner (System.in);
for (int i = 1; i <= 5; i++) {
System.out.println("Input the " + i + "st integer:");
int x = input.nextInt();
if (x > 0) positive++;
}
input.close();
System.out.println ("The number of positive integers are: " + positive );
}

关于java - 有没有办法让整个代码更短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017254/

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