[英]How do I keep java program running (loop) so I can use the scanner to input to the same text file text file?
I am trying to use the java scanner input to read multiple inputs (numbers as a string eg. 12345) from keyboard and send to a text file, I have a scanner reading input.nextLine(), where it will read in each line. 我试图使用Java扫描仪输入从键盘读取多个输入(例如12345等数字)并发送到文本文件,我有一个扫描仪读取input.nextLine(),它将在每一行中读取。 I just would like to run my program and have it stay running so it will populate the text file with each scanner input.
我只是想运行我的程序并使它保持运行状态,因此它将使用每个扫描仪输入来填充文本文件。 I am using the following code:
我正在使用以下代码:
import java.util.*;
import java.io.*;
public class tap1
{
public static void main(String[] args) throws IOException
{
System.out.println("Please enter number:");
File outFile = new File ("CardNumbers.txt");
FileWriter fWriter = new FileWriter (outFile, true);
PrintWriter pWriter = new PrintWriter (fWriter);
Scanner scan = new Scanner(System.in);
String num = scan.nextLine();
pWriter.println (num);
pWriter.close();
}
}
You can wrap it in a loop like 您可以将其包装成一个循环
while(scanner.hasNext){
scanner.nextLine();
//Do some code
}
You'll keep "scanning" for new input until EOF is reached and untill then your program keep running. 您将继续“扫描”新的输入,直到达到EOF为止,然后程序将继续运行。
You can try this 你可以试试这个
import java.util.*;
import java.io.*;
public class tap1
{
public static void main(String[] args) throws IOException
{
System.out.println("Please enter number:");
File outFile = new File ("CardNumbers.txt");
FileWriter fWriter = new FileWriter (outFile, true);
PrintWriter pWriter = new PrintWriter (fWriter);
Scanner scan = new Scanner(System.in);
String num = "";
while(true){
num=scan.nextLine();
if(num.equals("exit")){
break;
}
pWriter.println (num);
}
pWriter.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.