Java 打印出输入中的每个字符
我一直在自学Java作为参考。他们有一个名为algs4的库,它有几个类,包括StdIn,我将在下面实现它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
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
}
}
}
}