2016-06-27 26 views
-1

入力から読み取った文字列は、すべてのスイッチケースをスキップし、デフォルトの場合に直接進みます。私は、文字列sが= in.readLine()を行うと。(トリム)それはすべてのケースに入り、すべてのケースを印刷し例えば「HELLO」の入力がドイツ語、ロシア語、英語を印字などUvaの12250 - 言語検出

import java.io.IOException; 

class Main implements Runnable { 

public static void main(String[] args) { 
    Main main = new Main(); 
    main.run(); 

} 

    @Override 
    public void run() { 

     ExecutorTemplate exe = new ExecutorTemplate(); 
     exe.run(); 

    } 

} 

class ExecutorTemplate implements Runnable { 

@Override 
public void run() { 

    String s = readLine(); 
    int casenr = 1; 
    while(!s.equals("#")){ 
     switch(s){ 
      case "HELLO": 
       System.out.printf("Case %d: %s\n",casenr++,"ENGLISH"); 
      case "HOLA": 
       System.out.printf("Case %d: %s\n",casenr++,"SPANISH"); 
      case "HALLO": 
       System.out.printf("Case %d: %s\n",casenr++,"GERMAN"); 
      case "BONJOUR": 
       System.out.printf("Case %d: %s\n",casenr++,"FRENCH"); 
      case "CIAO": 
       System.out.printf("Case %d: %s\n",casenr++,"ITALIAN"); 
      case "ZDRAVSTVUJTE": 
       System.out.printf("Case %d: %s\n",casenr++,"RUSSIAN"); 
      default: 
       System.out.printf("Case %d: %s\n",casenr++,"UNKNOWN"); 
     } 
     s = readLine(); 
    } 
} 

標準入力から読み込むためのメソッド

private String readLine() { 

    byte line[] = new byte[255]; 
    int length = 0; 
    int input = -1; 
    try { 
     while (length < 255) {// Read until maxlength 
      input = System.in.read(); 
      if ((input < 0) || (input == '\n')) { 
       break; // or until end of line ninput 
      } 
      line[length++] += input; 
     } 

     if ((input < 0) && (length == 0)) { 
      return null; // eof 
     } 
     return new String(line, 0, length); 
    } catch (IOException e) { 
    return null; 
    } 
    } 
} 
+2

case blockの後ろに 'break;'がないと "fallthrough"と呼ばれます。 –

答えて

1

問題は、breakステートメントを忘れてしまったことです。

は休憩とswitch文のために、この例を参照してください:

switch(s){ 
    case "HELLO": 
      // Do something 
      break; 
    case "HOLA": 
      // Do something else 
      break; 
    default: 
      // Default behaviour 
      break; 
} 
// if break; is called, execution continues here 

break;は、switch文の外になります。それがなければ、実行はどこで続けられ、次のステートメントに進みます。