2016-04-23 11 views
2

私は小文字にフレーズを印刷するには、次のコードを実装しました:java.util.Scannerを使用してユーザー入力を正しくスキャンする方法

import java.util.Scanner; 

public class LowerCase{ 
    public static void main (String[] args) { 
     String input, output = "", inter; 
     Scanner scan, lineScan; 
     scan = new Scanner(System.in); // Scan from the keyboard 
     System.out.println("Enter a line of text: "); 
     input = scan.nextLine(); // Scan the line of text 

     lineScan = new Scanner(input); 
     while (lineScan.hasNext()) { 
      inter = scan.next(); 
      output += inter.toLowerCase() + " "; 
     } 
     System.out.println(output); 
    } 
} 

私は私の実装と間違っているかわかりません!通常はコンパイルされますが、コードを実行して入力フレーズを入力するとフリーズします。

答えて

2

あなたのループは1つのスキャナで行を待っていますが、もう1つのScannerから線を読み込んでいます(無限ループ)。この

while (lineScan.hasNext()) { 
    inter= scan.next(); 

あなたはこれがあなた

scan= new Scanner(System.in); //scan from the keyboard 
System.out.println("Enter a line of text: "); 
input=scan.nextLine(); //scan the line of text 


System.out.println(input.toLowerCase()); 
scan.close(); 
+0

ありがとうございました! – Jane

1

のようなものである必要があり、私は別の方法をお勧めします。

import java.util.*; 
public class something 
    { 
     static Scanner reader=new Scanner(System.in); 
     public static void main(String[] args) 
     { 
      System.out.println("type something (string)"); 
      String text = reader.next(); // whatever the user typed is stored as a string here 
      System.out.println(text); 

      System.out.println("type something (int)"); 
      int num = reader.nextInt(); // whatever the user typed is stored as an int here 
      System.out.println(num); 

      System.out.println("type something (double)"); 
      double doub = reader.nextDouble(); // whatever the user typed is stored as double here 
      System.out.println(doub); 
     } 
    } 

これはユーザー入力を取得するためのコード例です。

1

のために働くものの出力を達成するためにスキャナオブジェクトを必要としない

while (lineScan.hasNext()) { 
    inter= lineScan.next(); 
関連する問題