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. 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.
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.