Java:为什么这段代码不起作用?无限循环?
因此,从我的尝试中,您可能可以看出,我试图找出如何制作一个程序,给用户5秒钟的时间来输入一些文本行,然后扫描仪将计算输入的行数。我刚刚开始学习Java作为我的第二语言,所以请尽量简单地解释一切:) 我有两个理论来解释为什么它不起作用。第一个是nextLine()将返回整行,无论它是否为空,都意味着它实际上等于整行(即“”)。我的第二个理论是,我不知道我在做什么,程序流程到处都是。无论如何,我的代码如下:Java:为什么这段代码不起作用?无限循环?,java,console,infinite-loop,program-flow,Java,Console,Infinite Loop,Program Flow,因此,从我的尝试中,您可能可以看出,我试图找出如何制作一个程序,给用户5秒钟的时间来输入一些文本行,然后扫描仪将计算输入的行数。我刚刚开始学习Java作为我的第二语言,所以请尽量简单地解释一切:) 我有两个理论来解释为什么它不起作用。第一个是nextLine()将返回整行,无论它是否为空,都意味着它实际上等于整行(即“”)。我的第二个理论是,我不知道我在做什么,程序流程到处都是。无论如何,我的代码如下: class OrigClass{ public static void main(S
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
String NL = ScanObj.nextLine();
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (!NL.equals("")){
Count++;
NL = ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}
哦,我忘了提到hasNext()是我最初尝试的:
import java.util.Scanner;
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (ScanObj.hasNext() == true){
Count++;
ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}
从外观上看,这段代码应该可以工作。我唯一的猜测是您正在手动输入,而忘记了用
CTRL+D
发出输入结束的信号。但是,如果不使用ScanObj.hasNext()
,则执行此操作时将得到一个NoTouchElementException
您还可以使用输入重定向来运行代码<代码>java OrigClass
更好的方法是:
import java.util.Scanner;
public class Sc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 0;
String nl; // = scan.nextLine();
//while (!NL.equals(""))
while(scan.hasNext())
{
count++;
nl = scan.nextLine();
}
System.out.println("Done! Count: " + count);
scan.close();
}
}
这里的区别在于我们保存第一个nextLine()
,直到进入while循环。这将给出输入中有多少行的准确计数
只是别忘了用
CTRL+D
发出输入结束的信号。这个解决方案不是很好。但这是有效的
public class FiveSecond {
public static void main(String args[]){
new Thread(new Count(new Reader())).start();
}
}
class Count implements Runnable{
Reader r;Thread t;
Robot ro;
public Count(Reader t){this.r=t;
try {
ro=new Robot();
} catch (AWTException e) {e.printStackTrace();}
}
@Override
public void run() {
t=new Thread(r);
//t.setDaemon(true); //[S2]
t.start();
try{
Thread.sleep(5000);
}catch(Exception e){}
t.interrupt();
//Implicitly press the enter key in order to release the readLine() method :D
//not recommended, and it's not a good idea, but works
ro.keyPress(KeyEvent.VK_ENTER);
ro.keyRelease(KeyEvent.VK_ENTER);
/*
* this is possible to save the strings lines in somewhere in order to access from invoker application
* or send back the strings by socket, etc . . .
*/
System.out.println("number of entered lines "+r.getCount()+"\n");
//you would run this main as a process and get the number of counts
//System.exit(r.getCount()); //[S2]
}
}
class Reader implements Runnable{
private List<String> lines;
private volatile int count;
private BufferedReader br;
public Reader(){
lines=new ArrayList<String>();
br=new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
try{String line;
System.out.println("you have 5 second to detect a 2048 length character, then your system will broken");
while((line=br.readLine())!=null){
if(!Thread.currentThread().isInterrupted()){
count++;lines.add(line);}else{break;}
}
//for showing the lines entered
//System.out.println(lines.toString());
}catch(Exception ex){}
}
public int getCount(){return this.count;}
}
公共类五秒钟{
公共静态void main(字符串参数[]){
新线程(新计数(新读卡器()).start();
}
}
类计数实现可运行{
读卡器r;线程t;
机器人反渗透;
公共计数(读取器t){this.r=t;
试一试{
ro=新机器人();
}catch(awtexe){e.printStackTrace();}
}
@凌驾
公开募捐{
t=新螺纹(r);
//t、 setDaemon(true);//[S2]
t、 start();
试一试{
睡眠(5000);
}捕获(例外e){}
t、 中断();
//隐式地按enter键以释放readLine()方法:D
//不推荐,这不是一个好主意,但很管用
ro.按键(KeyEvent.VK_ENTER);
ro.keyRelease(KeyEvent.VK_输入);
/*
*这可以将字符串行保存在某个地方,以便从调用程序应用程序进行访问
*或者通过套接字等发送回字符串。
*/
System.out.println(“输入的行数”+r.getCount()+“\n”);
//您可以将此main作为进程运行,并获取计数的数量
//System.exit(r.getCount());//[S2]
}
}
类读取器实现可运行{
私有列表行;
私有可变整数计数;
专用缓冲读取程序br;
公众读者(){
行=新的ArrayList();
br=新的BufferedReader(新的InputStreamReader(System.in));
}
@凌驾
公开募捐{
试试{字符串行;
System.out.println(“您有5秒钟的时间检测2048长度的字符,那么您的系统将崩溃”);
而((line=br.readLine())!=null){
如果(!Thread.currentThread().isInterrupted()){
计数++;行。添加(行);}否则{break;}
}
//用于显示输入的行
//System.out.println(lines.toString());
}捕获(例外情况除外){}
}
public int getCount(){返回this.count;}
}
但最好的方法是运行一个单独的进程来计算行数,您只需删除
[S2]
注释即可实现此目的。Java约定要求变量名以小写字符开头。您应该尝试而不是(ScanObj.hasNext())
。。。你是如何从中得到无限循环的?如果输入的末尾没有空行,我会得到一个异常,如果有空行,我会得到完整。您是否忘记用^D
终止输入结束?的API表示它将阻止等待输入。因此,如果您的目的是做一些有趣的事情,如果用户在5秒钟内没有键入任何内容,那么Scanner就不是一个合适的类。我不知道该怎么办。而(NL!=null)我认为更合适