2016-03-05 42 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 
      } 
     } 
    } 
}