[英]print out each character in an input
I've been teaching myself Java with http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html as a reference. 我一直在自学Java,以http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html作为参考。 They have a library called algs4 and it has several classes including StdIn, which I'm trying to implement below.
他们有一个名为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;
}
*/
If i run the code, it does ask for an input, but regardless of what i type in, nothing happens and nothing gets printed out. 如果我运行代码,它确实会要求输入,但是无论我键入什么内容,都不会发生任何事情,也不会输出任何内容。
I see that even StdOut.print(1);
我什
StdOut.print(1);
看到StdOut.print(1);
doesnt get printed out, so for some reason, it just gets stuck on while
犯规得到打印出来,所以出于某种原因,它只是卡住上
while
It looks like the issue is with the condition for your while loop: 看来问题在于您的while循环条件:
!StdIn.hasNextChar()
This says to continue as long as there isn't a next char. 这说只要没有下一个字符就继续。 But you want to continue while there is one, so get rid of that
!
但是,如果有一个,您想继续,所以摆脱它
!
and you should be good. 你应该好。
Here is some alternative code that works similarly. 这是一些类似的替代代码。 Not the best coding but works.
不是最好的编码,但是有效。
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
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.