java - 输入一个负数且为偶数或正数且为奇数的整数

标签 java

我正在创建一个程序,要求用户输入几个整数,其中一个语句要求用户“输入一个负偶数或正奇数的整数”。我将如何设置这样的问题?到目前为止我有这个。我不知道我应该怎么做,因为我的指示很困惑。这就是我的问题的问题:

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/

相关文章:

java - 从缓冲区中排除 HTTP/1.1 header

java - Android 中 java.lang.String 类型的值无法转换为 JSONArray(转发)

java - 访问 Java 中的私有(private)集合字段

java - 如何在 Scriptlet 中编写 JSP 表达式标记

java - 在Eclipse中输入 "System.in.read()"

java - 如何测试PreparedStatement是否会耗尽内存

java - Android 选项卡式 Activity 底部关闭屏幕

java - Spring 启动: remove jsessionid from url

java - 如何使用 Jersey 服务轮询资源

java - Log4j:带有属性的配置回退错误处理程序