打印出输入中的每个字符

时间:2016-03-05 22:43:26

标签: java class input while-loop

我一直在用http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html作为参考教自己Java。他们有一个名为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

2 个答案:

答案 0 :(得分:0)

看起来问题在于你的while循环的条件:

!StdIn.hasNextChar()

只要没有下一个字符,这就说继续了。但是你想在有一个的时候继续,所以摆脱那个!你应该是好的。

答案 1 :(得分: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
            }
        }
    }   
}
相关问题