Java:为什么这段代码不起作用?无限循环



因此,您可以从我的尝试中看出,我正在努力弄清楚如何制作一个程序,让用户有5秒钟的时间输入一些文本行,然后扫描仪会计算输入了多少行。我刚刚开始学习Java作为我的第二语言,所以请尽可能简单地解释一切:)

关于为什么它不起作用,我有两种理论。第一个是nextLine()将返回整行,无论它是否为空。这意味着NL等于",它实际上等于整行(即")。我的第二个理论是,我不知道自己在做什么,程序流程到处都是。不管怎样,这是我的代码:

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(),则会得到一个NoSuchElementException

您也可以使用输入重定向来运行代码。java OrigClass < data

更好的方法是:

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

但最好的方法是运行一个单独的进程来计算行数,只需删除[S2]注释即可实现。

相关内容

最新更新