在java

时间:2018-04-19 21:27:02

标签: java switch-statement

您好我正在尝试生成一个用于显示字符串的随机案例。 到目前为止,下面的代码只输出案例2.例如,如果randomNum是1,我希望它打印出案例1中的内容,如果randomNum是2,我希望它打印出来的内容案例2.如果可能,请告诉我,并告诉我如果可能的话我如何纠正我的代码。谢谢你的帮助!

  String Aries = "";
  Random number = new Random();
  int i = 0;
  int randomNum = number.nextInt(2) + 1;

  switch(randomNum)
  {
    case 1:
      Aries = "On April 2...";
    case 2:
      Aries = "In 2018...";
  }
  System.out.println(Aries);

5 个答案:

答案 0 :(得分:1)

您需要在每个break语句的末尾添加case。如果您不添加此break并输入一个case,则会执行以下每个案例,如下所示:

int i = 2;

switch(i) {
  case 1 :
    System.out.println("case 1");
    // add "break;" here
  case 2:
    System.out.println("case 2");
    // add "break;" here
  case 3:
    System.out.println("case 3");
    /* Optionally but strongly recommended, 
     * you shall also add a "break;" here
     * so that there is no surprise if you add a case.
     */
}

输出:

case 2
case 3

此外,您可以通过用String数组替换switch / case来简化代码:

String[] strings = new String[]{"case 1", "case 2", "case 3"};
Random random = new Random();
int index = random.nextInt(strings.length);
System.out.println(strings[index]);

答案 1 :(得分:0)

如果你想停止de case,你需要使用一个断句,就像这样...

    Random number = new Random();
    int i = 0;
    int randomNum = number.nextInt(2) + 1;
    String aries;

    switch(randomNum){
        case 1:
            aries = "On April 2...";
            break; //<- stop the switch
        case 2:
            aries = "In 2018...";
            break; //<- stop the switch
    }

    System.out.println(aries);

希望它有所帮助...

答案 2 :(得分:0)

默认情况下,

switch case语句会失效。最小的更改,将break添加到至少case 1(尽管将其添加到case 2也是可取的)。像,

String Aries = "";
Random number = new Random();
int randomNum = number.nextInt(2) + 1;
switch (randomNum) {
case 1:
    Aries = "On April 2...";
    break;
case 2:
    Aries = "In 2018...";
    break;
}
System.out.println(Aries);

但是,您只有两种情况 - 因此booleanif-else会更短(且更具可读性)。此外,除了打印之外,您似乎不需要Aries。所以我会消除它。像,

Random number = new Random();
if (number.nextBoolean()) {
    System.out.println("On April 2...");
} else {
    System.out.println("In 2018...");
}

答案 3 :(得分:0)

只需添加这些中断,它就能正常工作

import java.util.*;
 public class aaaaa {

public static void main(String[] args) {
   String Aries = "";
     Random number = new Random();
     int i = 0;
     int randomNum = number.nextInt(2) + 1;

     switch(randomNum)
     {
       case 1:
         Aries = "On April 2...";
         break;
       case 2:
         Aries = "In 2018...";
         break;
     }
System.out.println(Aries );

}

}

答案 4 :(得分:-3)

我在一个范围之间创建一个随机数     Int ran0 = ThreadLocalRandom.current()。nextInt(1,2 + 1);