我需要编写一个接受以下条件的程序:
我目前正试图检查它是否有奇数位数。任何帮助,将不胜感激。 更新:感谢所有人的帮助。这真的很有帮助!
pred_score
答案 0 :(得分:0)
这个怎么样?
此伪代码不是解决方案或尝试解决方案。
//this should probably be outside and before your while loop.
int length = Integer.toString(userInput).length();
if (length % 2 == 0) {
return false; //even number of digits
}
...
//this should be inside your while loop
while(userInput != 0) {
remainder = userInput % 10;
userInput = userInput / 10;
if (remainder % 2 != 0) {
return false; //One of the digit is even
}
//if every digit is odd, it has to be an odd number, so checking if origina userInput is an odd number is not necessary.
}
以此伪代码为出发点。
答案 1 :(得分:0)
尝试将userInput的值传递给字符串,并检查其长度是否为奇数。
String total = "";
do{
System.out.println("please enter a positive whole number between"
+ "" + MIN + " and " + MAX + ". Enter " + EXIT + " "
+ "when you are done entering numbers.");
userInput = stdin.nextInt();
total += String.valueOf(userInput);
}
while(userInput != EXIT && userInput >= MIN && userInput <= MAX);
System.out.println(total);
if(total.length() % 2 == 1){
System.out.println("This is an odd number");
}
else{
System.out.println("This is not an odd number");
}
答案 2 :(得分:0)
这段代码将检查每个数字是否为奇数,以及长度是否也为奇数。
int test = 6789;
int a = test;
int length =0;
boolean hasEachDigitOdd = true;
while (a!= 0) {
int remaider = a % 10;
if (remaider % 2 == 0) {
hasEachDigitOdd = false;
}
a = a / 10;
length++;
}
System.out.println(length);
System.out.println(hasEachDigitOdd);
答案 3 :(得分:0)
if (num >= 101 && num <= 1000001 && num % 2 == 0)
%符号为您提供除法运算的剩余部分。
答案 4 :(得分:-1)
请在下面查看 - 满足您所有需求的解决方案。甚至你输入的方式都需要修复。
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int userInput;
final int EXIT = -1;
final int MIN = 101;
final int MAX = 1000001;
do {
System.out.println("please enter a positive whole number between"
+ "" + MIN + " and " + MAX + ". Enter " + EXIT + " "
+ "when you are done entering numbers.");
userInput = stdin.nextInt();
if(userInput==EXIT){
System.out.println("done");
break;
}
if (userInput % 2 == 1) {
System.out.println("This is an odd number");
} else {
System.out.println("This is not an odd number");
}
if(String.valueOf(userInput).length()%2==1){
System.out.println("Has odd number of digits");
} else {
System.out.println("Has even number of digits");
}
boolean[] allOdds = {true};
String.valueOf(userInput).chars().forEach(i -> {
if(Integer.parseInt(String.valueOf((char)i))%2==0){
allOdds[0] = false;
}
});
if(allOdds[0]){
System.out.println("all digits are odds");
}else{
System.out.println("all digits are not odds");
}
} while (userInput >= MIN && userInput <= MAX);
}