2011-12-21 35 views
0

这里我试图用链表实现一个简单的队列。我在这里使用了Bufferreader和readline。我将“choice”声明为字符串。但是我无法传递一个字符串变量来切换语句。如果我将它声明为Integer变量,那么readline方法将不会接受它。谁能帮忙?如何在switch语句中使用字符串

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; 

    } 

} 

} 
+0

或者改变您切换情况下'“1”','案“2”'等等,因为选择的是String类型 – 2011-12-21 16:00:02

+1

这是否编译呢? – home 2011-12-21 16:00:06

+1

自从几个月前发布的Java 7以来,您可以在'switch'语句中使用'String'。如果您使用Java 6或更早版本,则不能在'switch'语句中使用'String'。 – Jesper 2011-12-22 12:04:08

回答

1

使用int choiceNum = Integer.parseInt(choice);和交换机上。

请注意,在Java 7中,您实际上可以打开字符串,但您需要case "1":

0

付诸TA switch语句之前解析字符串为整数:

int choice; 
choice = Integer.parseInt(bf.readLine()); 
1

好了另一个答案保持字符串:

if (choice.equals("1")) { 
    ... 
} else if (choice.equals("2")) { 
1

如果它始终将是一个一个字符输入,你可以将其转换为char和开关上使用单引号...

0

试此

choice = Integer.parseInt(bf.readLine());

0

我相信要使用LinkedList,您需要在声明时指定数据类型。

LinkedList<String> l1 = new LinkedList<String>(); 

这将创建一个数据类型字符串的链表。然后你可以使用解析函数将String转换为int。

int choice; 
choice = Integer.parseInt(bf.readLine()); 
+0

不一定。虽然不建议这样做,但可以使用原始的LinkedList(或任何其他通用)。您添加的第一项决定了类型。 – corsiKa 2011-12-21 23:49:05

相关问题