2016-03-05 46 views
1

我一直在用自己的Java教學模塊http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html作爲參考。他們有一個名爲algs4的庫,它有幾個類,包括StdIn,我正在試圖在下面實現。在輸入中打印出每個字符

import edu.princeton.cs.algs4.StdIn; 
import edu.princeton.cs.algs4.StdOut; 

public class Tired 
{ 
    public static void main(String[] args) 
    { 
     //I thought this while statement will ask for an input 
     //and if an input is provided, it would spell out each character 
     while (!StdIn.hasNextChar()) { 

      StdOut.print(1); //seeing if it gets past the while conditional 
      char c = StdIn.readChar(); 
      StdOut.print(c); 
     }  
    }  
} 


//This is from StdIn class. It has a method called hasNextChar() as shown below. 
/* 
    public static boolean hasNextChar() { 
     scanner.useDelimiter(EMPTY_PATTERN); 
     boolean result = scanner.hasNext(); 
     scanner.useDelimiter(WHITESPACE_PATTERN); 
     return result; 
    } 
*/ 

如果我運行的代碼,它不要求輸入,但不管是什麼我輸入,什麼都不會發生,沒有什麼被打印出來。

我看到,即使StdOut.print(1);犯規得到打印出來,所以出於某種原因,它只是卡住上while

回答

0

它看起來像問題是與你的while循環的條件:

!StdIn.hasNextChar() 

這說,只要沒有下一個字符就繼續。但是,如果有一個,你想繼續,所以擺脫那!,你應該很好。

0

下面是一些類似的替代代碼。不是最好的編碼,但工作。

import java.util.Scanner; 

public class test{ 

    static Scanner StdIn = new Scanner(System.in); 
    static String input; 

    public static void main(String[] args){ 

     while(true){ 
      if(input.charAt(0) == '!'){ // use ! to break the loop 
       break; 
      }else{ 
       input = StdIn.next(); // store your input 
       System.out.println(input); // look at your input 
      } 
     } 
    } 
}