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新手,我必须编写一个代码,用于检测4位数字(用户输入)是否连续使用布尔变量。连续如0543,1234,0009,0034(单个数字连续计数)。我写这部分代码到现在为止,问题是我不明白我的为什么行 boolean isTwoDigitConsecutive; isTwoDigitConsecutive =(w = 0)&amp;&amp; (x = 0)&amp;&amp; (y <= 9)&amp;&amp; (y - z == 1); 错误。它说我不能使用&amp;&amp;与Int。
我想澄清一下如何使用布尔变量。
提前谢谢。
*编辑: 谢谢您的帮助, 我听取了你的建议并相应地更改了我的代码。
答案 0 :(得分:2)
试试isTwoDigitConsecutive = (w == 0) && (x == 0) && (y <== 9) && (y - z ==1);
使用==
符号时,编译器会检查是否相等。如果您使用单个=
,则会将=
符号的右侧部分分配给左侧部分。
答案 1 :(得分:0)
您有两个问题:
1-正如阿米尔所说:
isTwoDigitConsecutive = (w == 0) && (x == 0) && (y <== 9) && (y - z ==1);
2-小修复w,x,y,z
w = (number - (number % 1000)) / 1000;
x = ((number - (number % 100)) % 1000) / 100;
y = ((number - (number % 10)) % 100) / 10;
z = (number % 10);
也不要忘记初始化变量isThreeDigitConsecutive和isFourDigitConsecutive
答案 2 :(得分:0)
我理解你的担忧。 与C语言不同,java只接受带有这些运算符的布尔值。
C非零值中的为真,零为假
(w = 0)将返回0,即整数。而(w == 0)将返回 true / false是布尔值。
尽管您可能通过编写w = 0而不是w == 0来产生逻辑错误,但C编译器在获取值时不会生成编译错误。而java需要布尔值。因此它会显示错误。
答案 3 :(得分:0)
除了这里说的所有内容之外,您的代码可以更清晰,更高效。
public class ConsecutiveChecker {
/**
* return true if number digits are consecutively increasing.
*
* @param num
* @return
*/
private static boolean isConsecutive(int num) {
if(num < 0 || num > 9999) throw new RuntimeException("Input out of range (0-9999)");
// We check if the digits are downward consecutive from right to left
// (which is same as upward consecutive from left to right, but easier
// and more efficient to compute).
while (num > 0) {
int leftDigit = num%10;
int secondFromLeftDigit = (num/10)%10;
if (leftDigit < secondFromLeftDigit) return false;
num = num/10;
}
// if number is now 0, it's consecutive:
return true;
}
public static void main(String[] args) {
try {
java.util.Scanner keyboardReader = new java.util.Scanner(System.in);
int number = keyboardReader.nextInt();
System.out.println(
"Input number is " +
(isConsecutive(number) ? "" : "not ") +
"consecutive"
);
} catch (Exception e) {
System.out.println("Somthing is wrong with the input: ");
e.printStackTrace();
}
}
}