我对此有点陌生,但是?谁能纠正我的第一个 switch 语句?我不知道用什么表达来开始这个案例a:
我什至不确定起始声明是否正确
import java.io.*;
public class SwitchDemo {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input= br.readLine();
System.out.println("Press Enter");
System.out.println("a.Hello: Asks the name of the user.");
System.out.println("b.Array: Input elements and search for a specified key and prints a message.");
System.out.println("c.MagicSquare: Displays [7][7] magic square.");
System.out.println("d.Bubble Sort: Alphabetically sorts 20 employees using bubble sort.");
System.out.println("e.Selection Sort: Alphabetically sorts 20 employees using selection sort");
System.out.println("f.Insertion Sort: Alphabetically sorts 20 employees using Insertion sort");
System.out.println("g.Factorial: Run the Factorial application");
System.out.println("h.Triangle: Run the Triangle application.");
System.out.println("i.MergeSort: Performs the mergesort of a two class databasse.");
System.out.println("j.Stack_1: Perform reversal of string.");
System.out.println("k.Stack_2: Perform Infix Notation");
System.out.println("l.Postfix: Perform Postfix Notation");
System.out.println("m.Linked List");
System.out.println("n.Queue:");
System.out.println("o.Exit:");
switch (input) {
case a:
String usersName;
String upperCaseName;
TextIO.put("Please enter your name: ");
usersName = TextIO.getln();
upperCaseName = usersName.toUpperCase();
TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
break;
case b:
// Code for b execution here. Run array.
break;
case c:
// Code for c execution here. magicsquare.
break;
case d:
// Code for d execution here. Bubble sort.
break;
case e:
// Code for e execution here. selection sort.
break;
case f:
// Code for f execution here. insertion sort.
break;
case g:
// Code for g execution here. recursion.
break;
case h:
// Code for h execution here. mergesort.
break;
case i:
// Code for b execution here. stack1.
break;
case j:
// Code for b execution here. stack2.
break;
case k:
// Code for b execution here. link list.
break;
default:
System.out.println("Please input selection from a-o");
break;
}
}
}
最佳答案
正如其他人提到的,使用
switch(input) {
case "a":
// do stuff
break;
case "b":
// do more stuff
break;
}
会起作用的。 另一件事,如果您使用的是 java 7(java 版本),您应该能够摆脱
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
并将其替换为
Scanner in = new Scanner(System.in);
String input = in.nextLine();
至少对我来说,这更容易使用。只需导入
import java.util.Scanner;
关于java - Switch 语句 请帮助我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22368944/