在开关中使用用户输入

时间:2019-04-24 23:46:24

标签: java switch-statement

import java.util.*;

public class assigment4number3
{
public static void main (String [] args)
  {


    int mon, tues, wed, thurs, fri;
    mon=1; tues=2; wed=3;thurs=4;fri=5;

    Scanner day = new Scanner(System.in);
    System.out.println("Enter Day of week: mon, tues, weds, thurs, fri, sat, sun");
   String week= day.next();


    switch (week) {
      case 1:
      System.out.println(" Discrete Math");
        System.out.println("Philosophy");
        System.out.println("Calculus");
       break;
      case 2:
       System.out.println("Modern World");
       System.out.println("Java Programming");
       break;
     case 3: 
        System.out.println(" Discrete Math");
        System.out.println("Philosophy");
        System.out.println("Calculus");
       break;
       case 4:
             System.out.println("Modern World");
       System.out.println("Java Programming");                 
       break;
      case 5:
       System.out.println("Discreet Math");
       System.out.println("Philosophy");
    break;
      default:
       System.out.println("Its the weekend");
    break;


    }
  }
  }

我正在尝试在交换机中使用输入         我正在编写一个代码,可以在一周中的某一天进行插值,并且应该弹出时间表,但是我在开关中使用输入时遇到了困难

1 个答案:

答案 0 :(得分:0)

您所有的case标签均为int类型。将它们更改为String上的switch int。喜欢,

int week = day.nextInt();

switch (week) {
case "1":
    System.out.println(" Discrete Math");
    System.out.println("Philosophy");
    System.out.println("Calculus");
    break;
case "2":
    System.out.println("Modern World");
    System.out.println("Java Programming");
    break;
case "3":
    System.out.println(" Discrete Math");
    System.out.println("Philosophy");
    System.out.println("Calculus");
    break;
case "4":
    System.out.println("Modern World");
    System.out.println("Java Programming");
    break;
case "5":
    System.out.println("Discreet Math");
    System.out.println("Philosophy");
    break;
default:
    System.out.println("Its the weekend");
    break;
}

如果您打算使用值mon-fri代替数字,则可以将其用于case标签。喜欢,

String week = day.next();
switch (week.toLowerCase()) {
case "mon":
    System.out.println(" Discrete Math");
    System.out.println("Philosophy");
    System.out.println("Calculus");
    break;
case "tues":
    System.out.println("Modern World");
    System.out.println("Java Programming");
    break;
case "weds":
    System.out.println(" Discrete Math");
    System.out.println("Philosophy");
    System.out.println("Calculus");
    break;
case "thurs":
    System.out.println("Modern World");
    System.out.println("Java Programming");
    break;
case "fri":
    System.out.println("Discreet Math");
    System.out.println("Philosophy");
    break;
default:
    System.out.println("Its the weekend");
    break;
}