0

好的,这就是我被告知要做的 1.让用户输入两个整数以用于以下任务。2.编写一个简单的 if then 结构来检查用户输入的数字的值,并显示它是否大于 0、大于 10 或负数。3.编写一个决策结构,使用布尔表达式来确定并显示第一和第二是否为正数。4.使用switch语句检查数字2从1到5的值并显示适当的值。找到值后结构应该退出。如果未找到值,请包含一个操作以显示未找到的值。

我自己已经到了 4,但如果第二个数字不是 1-5,我不知道如何让 switch 语句退出。我知道如何显示“未找到值”,但知道如何告诉它显示它是 1-5 未输入。让我知道一个简单的方法,谢谢!这是我到目前为止所拥有的:

package ICS4UIReviewTest;
import java.util.Scanner;
import java.lang.Math;

public class PartOneDecisionStructuresAndMathObject {

    public static void main (String [] args) {
        int int1, int2;

        Scanner input = new Scanner (System.in);

        System.out.print("Enter the first integer: ");
        int1 = input.nextInt();

        System.out.print("Enter the second integer: ");
        int2 = input.nextInt();

        if (int1 > 0 && int1 < 10){
            System.out.println("The first number is > 0.");
            } else {
                 if (int1 > 10){
                     System.out.println("The first number is > 10.");
                } else {
                  System.out.println("The first number is negative.");
                    }
                }
            if (int1 > 0 && int2 > 0) {
             System.out.println("The 1st & 2nd number are postiive.");
                }
        switch (int2) {
            case 1: System.out.println("The second number entered is 1."); break;
            case 2: System.out.println("The second number entered is 2."); break;
            case 3: System.out.println("The second number entered is 3."); break;
            case 4: System.out.println("The second number entered is 4."); break; 
            case 5: System.out.println("The second number entered is 5."); break;
                }

         }
    }
4

2 回答 2

3

利用中的失败switch(并添加default案例):

switch (int2) {
    case 1: 
    case 2: 
    case 3: 
    case 4: 
    case 5: System.out.println("The second number entered is " + int2 + ".");
            break;
    default: System.out.println("Number entered not between 1 and 5");
}
于 2013-02-19T16:15:54.560 回答
1

您可以使用default. 如果没有匹配的情况,则执行默认子句。

   switch (int2) {
        case 1: 
            System.out.println("The second number entered is 1.");
            break;
        case 2: 
            System.out.println("The second number entered is 2."); 
            break;
        case 3: 
            System.out.println("The second number entered is 3."); 
            break;
        case 4: 
            System.out.println("The second number entered is 4."); 
            break; 
        case 5: 
            System.out.println("The second number entered is 5."); 
            break;
        default: 
            System.out.println("Number not in range"); 
   }
于 2013-02-19T16:13:42.217 回答