我正在创建一个程序,要求用户输入几个整数,其中一个语句要求用户“输入一个负偶数或正奇数的整数”。我将如何设置这样的问题?到目前为止我有这个。我不知道我应该怎么做,因为我的指示很困惑。这就是我的问题的问题:
4. 向用户询问一个整数,该整数要么是负数,要么是偶数,要么是正数 和奇怪的。使用 if 语句和复合条件。
import java.util.Scanner;
public class ExerciseFour
{
public static void main ( String[] argsv )
{
int choice;
int choiceTwo;
int choiceThree;
Scanner input = new Scanner(System.in);
System.out.println( "Enter a number between 0 and 10" );
choice = input.nextInt();
if ( choice > 0 && choice < 10 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Invalid number" );
return;
}
System.out.println( "Enter a number divisible by 2 or 3?" );
choiceTwo = input.nextInt();
if ( choiceTwo % 2 == 0 && choiceTwo % 3 == 0 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Number not divisible by 2 or 3" );
return;
}
System.out.println( "Enter an integer that is negative and even or positive and odd (Ex. -2 or 7 )" );
choiceThree = input.nextInt();
if ( choiceThree )
{
}
else
{
}
最佳答案
((choiceThree > 0) && (choiceThree % 2 == 1)) || ((choiceThree < 0) && (choiceThree % 2 == 0))
上面是你要找的复合条件,意思是:
(
(choiceThree > 0) //positive number / greater than zero
&& // AND
(choiceThree % 2 == 1) //odd number: (an odd number divided by two has a remainder of 1)
)
|| // OR
(
(choiceThree < 0) //negative number / less than zero
&&
(choiceThree % 2 == 0) //even number (an even number divided by two has a remainder of 0)
)
编辑 %
是 modulo operator .
a % b
的结果是整数除法 a/b
的余数。
关于java - 输入一个负数且为偶数或正数且为奇数的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21987894/