Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 打印出输入中的每个字符_Java_Class_Input_While Loop - Fatal编程技术网

Java 打印出输入中的每个字符

Java 打印出输入中的每个字符,java,class,input,while-loop,Java,Class,Input,While Loop,我一直在自学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

我一直在自学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循环的条件:

!StdIn.hasNextChar()

这表示只要没有下一个字符,就继续。但是你想在有代码的时候继续,所以把它去掉你应该很好

问题似乎在于while循环的条件:

!StdIn.hasNextChar()

这表示只要没有下一个字符,就继续。但是你想在有代码的时候继续,所以把它去掉你应该很好

这里有一些类似的替代代码。虽然不是最好的编码,但很有效

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
            }
        }
    }   
}

下面是一些类似的替代代码。虽然不是最好的编码,但很有效

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
            }
        }
    }   
}