在这里,我正在尝试使用链接列表实现一个简单的队列。我在这里使用了Bufferreader和readline。我宣布“选择”为字符串。但是我不能将字符串变量传递给switch语句。如果我将其声明为Integer变量,则readline方法将不接受它。谁能帮忙?
import java.lang.*;
import java.util.*;
import java.io.*;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
LinkedList l1=new LinkedList();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the no of elements to be inserted: ");
String str;
str=bf.readLine();
System.out.println("Enter Your Choice: ");
System.out.println("1->Insert 2->Delete 3->Display 4->Exit");
String choice;
choice=bf.readLine();
for(;;){
switch(choice) {
case 1:l1.addLast(bf);
break;
case 2:l1.removeFirst();
break;
case 3:
System.out.println("The contents of Queue are :" +l1);
break;
default:break;
}
}
}
最佳答案
使用int choiceNum = Integer.parseInt(choice);
并打开它。
请注意,在Java 7中,您实际上可以打开字符串,但是您需要case "1":
。
关于java - 如何在switch语句中使用字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8592630/