public class ConsecutiveChecker
{
public static void main( String[] args )
{
java.util.Scanner keyboardReader = new java.util.Scanner(System.in);
int number = keyboardReader.nextInt();
int w;
int x;
int y;
int z;
// w= fourth digit, x= third digit, y= second digit, z= first digit
w = (number - (number % 1000)) / 1000;
x = ((number - (number % 100)) % 1000) / 10;
y = ((number - (number % 10)) % 100) * 10;
z = (1000)*(number % 10);
boolean isOneDigitConsecutive;
isOneDigitConsecutive = (number <= 9);
boolean isTwoDigitConsecutive;
isTwoDigitConsecutive = (w = 0) && (x = 0) && (y <= 9) && (y - z ==1);
boolean isConsecutive = (isOneDigitConsecutive || isTwoDigitConsecutive || isThreeDigitConsecutive || isFourDigitConsecutive)
System.out.println();
}
}
嗨,
我是 Java 新手,我必须编写一段代码来使用 boolean 变量检测 4 位数字(用户输入的)是否连续。连续如 0543、1234、0009、0034(单个数字算连续)。到目前为止我已经写了这部分代码,问题是我不明白为什么我的行
boolean 是两位数连续;
isTwoDigitConsecutive = (w = 0) && (x = 0) && (y <= 9) && (y - z ==1);
错误的。它说我不能将 && 与 Int 一起使用。
我想澄清一下如何使用 boolean 变量。
提前谢谢您。
*编辑: 感谢您的帮助, 我听取了您的建议并相应地更改了我的代码。
最佳答案
尝试isTwoDigitConsecutive = (w == 0) && (x == 0) && (y <== 9) && (y - z ==1);
当您使用==
时符号,编译器检查是否相等。如果您使用的是单个 =
,它分配 =
的右侧部分在左侧签名。
关于java - 使用 boolean 值检测连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19070839/