gpt4 book ai didi

java - 如何测试多个输入以检测负数,同时记录哪些输入为负数?

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

我正在编写一个简短的程序来提示用户输入数字,然后我将测试它们是否为负并报告哪些通过了此测试。我正在寻找一种避免为每个预期输入重复逻辑的方法。

这是我到目前为止所拥有的:

import java.util.Scanner;

public class Negative
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
if (x < 0 || y < 0 || z < 0)
{
System.out.println("A number is negative.");
}
}
}

我知道我可以单独完成这些操作,但我想以某种方式压缩代码。

最佳答案

您始终可以创建一个接受变量名称的方法,然后打印它。比如,

private static void display(String name, int val) {
if (val >= 0) {
System.out.printf("%s (%d) is NOT negative%n", name, val);
} else {
System.out.printf("%s (%d) is negative%n", name, val);
}
}

然后就可以调用display(),

public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
display("x", scan.nextInt());
display("y", scan.nextInt());
display("z", scan.nextInt());
}

现在它实际上并不存储xyz。如果您稍后需要它们,那么您确实需要

public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
display("x", x);
display("y", y);
display("z", z);
// do something else with x,y or z
}

关于java - 如何测试多个输入以检测负数,同时记录哪些输入为负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25630802/

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