gpt4 book ai didi

java - 如何打印非0的整数?

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

为我的 java 类编写代码,程序按预期运行,我遇到的唯一问题是州际公路是否为 405,当它打印时,它会打印 05 标记问题错误,因为问题只是寻找 5 。有什么帮助吗?

import java.util.Scanner; 

highwayNumber = scnr.nextInt();

if ((highwayNumber > 999) || (highwayNumber < 1)) {
System.out.println(highwayNumber + " is not a valid interstate highway number.");
}
else if ((highwayNumber < 100) && (highwayNumber > 0) && (highwayNumber % 2 == 0)) {
System.out.println("The " + highwayNumber + " is primary, going east/west.");
}
else if ((highwayNumber < 100) && (highwayNumber > 0) && (highwayNumber % 2 != 0)) {
System.out.println("The " + highwayNumber + " is primary, going north/south.");
}
else if ((highwayNumber > 99) && (highwayNumber < 1000) && (highwayNumber % 2 == 0)) {
System.out.println("The " + highwayNumber + " is auxiliary, serving the " + String.valueOf(highwayNumber).substring(1) + ", going east/west.");
}
else if ((highwayNumber > 99) && (highwayNumber < 1000) && (highwayNumber % 2 != 0)) {
System.out.println("The " + highwayNumber + " is auxiliary, serving the " + String.valueOf(highwayNumber).substring(1) + ", going north/south.");
}
}
}

最佳答案

只需将 substring 替换为 % 模运算符:

System.out.println("The " + highwayNumber + " is auxiliary, serving the " + String.valueOf(highwayNumber % 100) + ", going east/west.");

System.out.println("The " + highwayNumber + " is auxiliary, serving the " + String.valueOf(highwayNumber % 100) + ", going north/south.");

关于java - 如何打印非0的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58055500/

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