I would like to fix the java.util.NoSuchElementException bug.
I keep getting the error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Main.newUser(Main.java:28)
at Main.main(Main.java:18)
with this code
import java.util.Scanner;
import java.io.*;
class Main2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
input.close();
newUser();
}
private static void newUser()
{
try
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the name for the new user.");
String userNameNew = input.nextLine();
System.out.println("Please enter the password for the new user.");
String userPassWordNew = input.nextLine();
System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
PrintWriter out = new PrintWriter("users.txt");
out.print(userNameNew + "\r\n" + userPassWordNew);
out.close();
input.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
Can you please help me? Thank you.
I found the reason why you are getting this exception.
So in your main method, you initialized your Scanner class object and immediately close it.
Here is the problem. Because when scanner calls the close() method, it will close its input source if the source implements the Closeable interface.
When a Scanner is closed, it will close its input source if the
source implements the Closeable interface.
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
And InputStream class which is the input source in your case implements the Closeable interface.
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
And further you initialized the Scanner class object into your newUser() method. Here scanner class object initialized successfully but your input source is still close.
So my suggestion is that close scanner class object only once.
Please find the updated code of yours.
class Main2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
newUser(input);
//input.close()
}
private static void newUser(Scanner input)
{
try {
System.out.print("Please enter the name for the new user.");
String userNameNew = input.nextLine();
System.out.println("Please enter the password for the new user.");
String userPassWordNew = input.nextLine();
System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
PrintWriter out = new PrintWriter("users.txt");
out.print(userNameNew + "\r\n" + userPassWordNew);
out.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
Related
I'm trying to catch an exception when the user enters any integer in the Scanner. I understand that using a String item = scan.nextLine() will allow for any input to be made including integers. I created a custom exception to catch the number 1. But what happens if the user inputs 999 or any other integer. How can I catch those other integers as part of the exception?
import java.util.Scanner;
import java.lang.Exception;
public class ExampleOne {
public static void main(String[] args) throws TestCustomException {
System.out.println("Please enter any word:");
try {
Scanner scan = new Scanner(System.in);
String item = scan.nextLine();
if (item.contains("1")) {
throw new TestCustomException();
}
}catch (TestCustomException e) {
System.out.println("A problem occured: " + e);
}
System.out.println("Thank you for using my application.");
}
}
public class TestCustomException extends Exception {
TestCustomException (){
super("You can't enter any number value here");
}
}
Regular expression
public static void main(String[] args) {
System.out.println("Please enter any word:");
try {
Scanner scan = new Scanner(System.in);
String item = scan.nextLine();
Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
Matcher isNum = pattern.matcher(item);
if (isNum.matches()) {
throw new RuntimeException();
}
}catch (RuntimeException e) {
System.out.println("A problem occured: " + e);
}
System.out.println("Thank you for using my application.");
}
I'm getting the error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.raghuvamsha.Main.main(Main.java:24)
in my program:
1. Main Class.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
// Using Scanner for Getting Input from User
System.out.println("\tMAIN MENU:\n" +
"\t\t1) Add new member record\n" +
"\t\t2) Modify existing member record\n" +
"\t\t3) Delete member record\n" +
"\t\t4) Display all member records\n" +
"\t\t5) Search for a particular member record\n" +
"\t\t6) Exit");
int a = 0;
while(a!=6) {
Scanner reader = new Scanner(System.in);
a = reader.nextInt();
System.out.println("You entered integer " + a);
if(a==1){
AddNewMember anm = new AddNewMember();
anm.openFile();
anm.addRecords();
anm.closeFile();
}
}
}
}
AddNewMember Class.
public class AddNewMember {
private FileWriter x;
private Formatter form;
public void openFile(){
try{
x = new FileWriter("/Users/askeladd/Downloads/animals.dat", true);
form = new Formatter(x);
}
catch (Exception e){
System.out.println("You have an error");
}
}
public void addRecords(){
//Adding Animal Name.
System.out.println("Please input animal name: ");
Scanner reader_an = new Scanner(System.in);
String animal_name = reader_an.next();
//Adding Animal's Owner.
System.out.println("Please input animal's owner Name: \n");
System.out.println("First Name: ");
Scanner reader_aofn = new Scanner(System.in);
String animal_ofn = reader_aofn.next();
System.out.println("Last Name: ");
Scanner reader_aoln = new Scanner(System.in);
String animal_oln = reader_aoln.next();
//Adding species.
System.out.println("Please input animal species: ");
Scanner reader_s = new Scanner(System.in);
String animal_s = reader_s.next();
//Adding Date of Birth.
System.out.println("Please input animal Date of Birth: ");
Scanner reader_dob = new Scanner(System.in);
String animal_dob = reader_dob.next();
//Adding Treatments
List<String> animal_treatments = new ArrayList<String>();
System.out.println("Please input treatments: ");
int i = 0;
Scanner reader_treatments = new Scanner(System.in);
while (i<10) {
String s = reader_treatments.next();
if (s.equals("q")|| s.equals("Q")) {
break;
}
animal_treatments.add(s);
i += 1;
}
System.out.println(animal_treatments);
}
public void closeFile(){
form.close();
}
}
I have read some posts in StackOverflow regarding the issue, it was mentioned to use next() instead of nextLine() in my code, but still it was not working. Please help me.
Thank you.
The Upshot
First, you shouldn't be creating multiple instances of Scanner. But your main problem is that you aren't doing error checking on the input that the user is giving you. The InputMismatchException was probably thrown beacause you entered something other than an integer on the menu. Try this code to fix it:
Main.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
// Using Scanner for Getting Input from User
int a = 0;
Scanner reader = new Scanner(System.in);
while (a != 6) {
System.out.println("\tMAIN MENU:\n" +
"\t\t1) Add new member record\n" +
"\t\t2) Modify existing member record\n" +
"\t\t3) Delete member record\n" +
"\t\t4) Display all member records\n" +
"\t\t5) Search for a particular member record\n" +
"\t\t6) Exit");
boolean intValid = false;
while(!intValid) {
System.out.println("Please enter a valid option (1 - 6).");
String input = reader.next();
if (isInteger(input)) {
a = Integer.parseInt(input);
if (a >= 1 && a <= 6) {
intValid = true;
}
}
}
System.out.println("You entered integer " + a);
if (a == 1) {
AddNewMember anm = new AddNewMember(reader);
anm.openFile();
anm.addRecords();
anm.closeFile();
}
}
}
private static boolean isInteger(String str) {
return str.matches("-?\\d+");
}
}
AddNewMember.java
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Scanner;
import java.util.List;
public class AddNewMember {
private FileWriter x;
private Formatter form;
private Scanner reader;
public AddNewMember(Scanner reader) {
this.reader = reader;
}
public void openFile() {
try {
x = new FileWriter("/Users/askeladd/Downloads/animals.dat", true);
form = new Formatter(x);
} catch (Exception e) {
System.out.println("You have an error");
}
}
public void addRecords() {
//Adding Animal Name.
System.out.println("Please input animal name: ");
String animal_name = reader.next();
//Adding Animal's Owner.
System.out.println("Please input animal's owner Name: \n");
System.out.println("First Name: ");
String animal_ofn = reader.next();
System.out.println("Last Name: ");
String animal_oln = reader.next();
//Adding species.
System.out.println("Please input animal species: ");
String animal_s = reader.next();
//Adding Date of Birth.
System.out.println("Please input animal Date of Birth: ");
String animal_dob = reader.next();
//Adding Treatments
List <String> animal_treatments = new ArrayList <String>();
System.out.println("Please input treatments: ");
int i = 0;
while (i < 10) {
String s = reader.next();
if (s.equals("q") || s.equals("Q")) {
break;
}
animal_treatments.add(s);
i += 1;
}
System.out.println(animal_treatments);
reader.close();
}
public void closeFile() {
form.close();
}
}
A Side Note
I don't know if this is for a school project of something you are making on your own, but if you really want to handle user input with a nice interface, take a look at Java Swing.
Also, you will have to do a lot more error checking on the input fields for the input in AddNewMember if you don't want similar errors in the future.
Happy Coding!
So my program is supposed to say what type of a token it is from my input file. My second method is supposed to write whatever input from the keyboard to an output file until the user types stop. The problem is my first method won't output the integers to their right type. My second method will only put stop in the output file. Here is my code. Any help would be much appriciated.
public class R16 {
public void readFile(String inputFile) {
try {
File in = new File(inputFile);
Scanner scan = new Scanner(in);
while (scan.hasNext()) {
if (scan.hasNextInt()) {
System.out.println("Integer: " + scan.nextInt());
}
if (scan.hasNext()) {
System.out.println("String: " + scan.next());
}
if (scan.hasNextDouble()) {
System.out.println("Double: " + scan.nextDouble());
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error, not good");
}
}
public void writeFile(String outputFile) {
try {
File out = new File(outputFile);
PrintWriter w = new PrintWriter(out);
Scanner scan= new Scanner(System.in);
System.out.print("Enter Text: ");
while(!scan.next().equals("stop")){
w.print(scan.next());
}
w.close();
scan.close();
} catch (IOException e) {
System.out.println("Error, it just got real");
}
}
public static void main(String[] args) {
R16 test = new R16();
test.readFile(args[0]);
test.writeFile(args[1]);
}
}
In your loop, you check for stop then throw away all input.
while(!scan.next().equals("stop")){
Try using something like
String input;
while (!(input = scan.next()).equals("stop")) {
w.print(input);
Now within the loop, you have access to the input variable which contains the input string.
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Workshop5
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in); // Prompting Scanner -> keyboard
System.out.println("Hello, this program will be used to help determine miles per gallon used.");
System.out.print("Please input file name here: ");
keyboard.nextLine();
Scanner fileIn = null ; // initializes fileIn to empty
try
{
// Attempting to open your file.
fileIn = new Scanner( new FileInputStream("MilesPerGallon.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
String name;
double gasUsed;
int milesDriven;
name = fileIn.nextLine();
gasUsed = fileIn.nextDouble();
milesDriven = fileIn.nextInt();
double milesPerGallon = (milesDriven/gasUsed);
System.out.println(name + " drove " + milesDriven + " miles the other day, using a total of " + gasUsed + " gallons of gas.");
fileIn.close();
System.out.printf("Total number of Miles per Gallon: " + "%2.2f", milesPerGallon);
}
}
This is what i have. I have a file, names MilesPerGallon.txt. If i type in kashdkjashgkhjfgk it still opens the file MilesPerGallon.txt. Anyone know how I can create an if statement or something to make it to where the keyboard entered text for the file name MUST = MilesPerGallon.txt? Please help!
System.out.println("Hello, this program will be used to help determine miles per gallon used.");
System.out.print("Please input file name here: ");
Scanner keyboard = new Scanner(System.in); // Prompting Scanner -> keyboard
String fileName = keyboard.nextLine();
Scanner fileIn = null ; // initializes fileIn to empty
try
{
// Attempting to open your file.
fileIn = new Scanner( new FileInputStream(fileName));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.. Please enter correct filename");
e.printStackTrace();
System.exit(0);
}
Having an issue here, I need this loop to print new lines of code to a file until but what it does is print 1 line then fails on the second time round,
Can never get it to print to another line, below is code
public class study {
public static void main(String[] args) throws IOException{
BufferedWriter post = null;
File file = new File("text.txt");
if(!file.exists()){
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
post = new BufferedWriter(fileWriter);
try {
while(promptUser){
System.out.println("enter age "); //get age
Scanner getage = new Scanner(System.in);
int age= getage.nextInt();
if(age <20 || age>50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); //get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
post.write(age + "\t"); <===== fails here on second run
post.write(name + "\t");
post.write(email + "\t");
post.newLine();
post.close();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if(option.equalsIgnoreCase("quit")){
System.out.println("goodbye!");
System.exit(0);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
post.write(age + "\t");
post.newLine();
post.write(name + "\t");
post.newLine();
post.write(email + "\t");
post.newLine();
//remove post.close(); from here
Now it may solve Your problem
Replace post.close(); with post.flush(); and you should be fine.
Close the stream when the exit condition is entered.
FIXED IT GUYS
I needed to move the FileWriter line out of the TRY
import java.io.*;
import java.util.*;
public class study {
public static void main(String[] args) throws IOException {
BufferedWriter post = null;
File file = new File("text.txt"); //create file
if (!file.exists())
{
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
try {
while (promptUser) {
post = new BufferedWriter(fileWriter);
System.out.println("enter age "); // get age
Scanner getage = new Scanner(System.in);
int age = getage.nextInt();
if (age < 20 || age > 50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); // get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
//send data to file
post.write(age + ";");
post.write(name + ";");
post.write(email + ";");
post.newLine();
post.flush();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if (option.equalsIgnoreCase("quit")) {
System.out.println("goodbye!");
post.close(); // close file upon quitting
System.exit(0);
}
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}