2015-10-15 88 views
0
import java.util.Scanner; 

public class VerticalWire { 
    public static void main(String[] args) 
    { 
     Scanner in = new Scanner(System.in); 
     System.out.println("how many wires"); 
     String howManyWires = in.next(); 

     switch(howManyWires) { 
      case "3": 
      { 
       System.out.println("true"); 
       break; 
      } 

      case "3 5": 
      { 
       System.out.println("false");break;} 
      } 
    } 
} 

我测试过,如果输入“3 5”,它会返回true,即使我认为它应该返回false! 有什么不对?为什么这个switch语句不起作用?

+2

你觉得呢'in.next() '是吗?你为什么这么认为? –

+0

'in.next()'只读取第一个数字。使用'nextLine()' – TheLostMind

+0

阅读['Scanner#next'](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next--)实际上,然后使用'扫描仪#nextLine'而不是 – MadProgrammer

回答

0

使用in.nextLine()而不是in.next()

scanner.next()文档指出

查找并从该扫描仪返回下一个完整标记。

所以,当你进入3 5作为输入,它会当你调用一个方法只读3,如果你再次调用next方法会读5

+1

他们为什么要这样做? (我知道答案,但你需要告诉OP;)) – MadProgrammer

+0

@MadProgrammer - 你不必说 - *我知道答案*。我们知道你知道:P – TheLostMind

+1

@TheLostMind人们经常误认我为OP;) – MadProgrammer