This question already has answers here:
NoSuchElementException with Java.Util.Scanner
(10 answers)
Closed 9 years ago.
I am trying a program in Java. My code goes as follows
class Main{
static Employee getData() throws IOException {
BufferedReader rdr = new BufferedReader(
new InputStreamReader(
new DataInputStream(System.in)
));
System.out.printf("Enter Employee ID : ");
int tmpid = Integer.parseInt(rdr.readLine());
System.out.printf("Enter Employee Name : ");
String tmpname = rdr.readLine();
System.out.printf("Enter Employee Salary : ");
int tmpsalary = Integer.parseInt(rdr.readLine());
rdr.close();
return new Employee(tmpid, tmpname, tmpsalary);
}
public static void main(String []args){
boolean b = false;
String path = null;
Scanner s = new Scanner(System.in);
File file = null;
try {
System.out.printf("Enter path to save your file : ");
path = s.next();
file = new File(path);
if (!(file.createNewFile()))
System.out.println("Error creating file");
} catch (Exception ie) {
System.err.println("Exception : " + ie);
}
do{
try {
Employee rec = Main.getData();
ObjectOutputStream dos = new ObjectOutputStream(new FileOutputStream(file));
dos.writeObject(rec);
dos.close();
System.out.printf("Add more records [true/false]? ");
s = new Scanner(System.in);
int tmp = s.nextInt();
} catch (Exception ioe) {
System.err.println("Exception : " + ioe);
}
}while(b);
}
}
When I run this program I get NoSuchElementFoundException when second time s.nextInt() is executed. I tried out every possible methods but with no result. What is the problem over here?
Never catch an exception unless you are going to do something useful with it.
I got it to work. It was fairly straight forward.
Enter path to save your file : myfile.bin
Enter Employee ID : 99
Enter Employee Name : Rick Hightower
Enter Employee Salary : 99
Add more records [true/false]? true
Enter Employee ID : 77
Enter Employee Name : Dippy Do
Enter Employee Salary : 88
Add more records [true/false]? false
Here is what I have:
...
public static class Employee implements Serializable {
int id;
String name;
int salary;
public Employee(int id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}
static Employee getData() throws IOException {
BufferedReader rdr = new BufferedReader(
new InputStreamReader(
new DataInputStream(System.in)
));
System.out.printf("Enter Employee ID : ");
int tmpid = Integer.parseInt(rdr.readLine());
System.out.printf("Enter Employee Name : ");
String tmpname = rdr.readLine();
System.out.printf("Enter Employee Salary : ");
int tmpsalary = Integer.parseInt(rdr.readLine());
//rdr.close(); this is why... you broke it :)
return new Employee(tmpid, tmpname, tmpsalary);
}
public static void main(String []args) throws Exception {
boolean moreRecords = true;
String path = null;
Scanner scanner = new Scanner(System.in);
File file = null;
System.out.printf("Enter path to save your file : ");
path = scanner.next();
file = new File(path);
while (moreRecords) {
Employee rec = Main.getData();
ObjectOutputStream dos = new ObjectOutputStream(new FileOutputStream(file));
dos.writeObject(rec);
dos.close();
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
}
It is mostly your code with some parts taken away.
The biggest issue you had was you were closing the input stream.
static Employee getData() throws IOException {
BufferedReader rdr = new BufferedReader(
new InputStreamReader(
new DataInputStream(System.in)
));
System.out.printf("Enter Employee ID : ");
int tmpid = Integer.parseInt(rdr.readLine());
System.out.printf("Enter Employee Name : ");
String tmpname = rdr.readLine();
System.out.printf("Enter Employee Salary : ");
int tmpsalary = Integer.parseInt(rdr.readLine());
//rdr.close(); this is why... you broke it :) <-------------------SEE
return new Employee(tmpid, tmpname, tmpsalary);
}
The Java I/O stream uses the decorator pattern so it just keeps delegating the close call into the inner streams.
That fixes that problem. There are lots of problems with your code.
If you are using JDK 1.7 or later, it will close the file for you.
while (moreRecords) {
Employee rec = Main.getData();
try ( ObjectOutputStream dos =
new ObjectOutputStream(
new FileOutputStream(file) ) ) {
dos.writeObject(rec);
}
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
}
If you are using JDK 1.6 or JDK 1.5:
while (moreRecords) {
Employee rec = Main.getData();
ObjectOutputStream dos = null;
try {
dos = new ObjectOutputStream(
new FileOutputStream(file) );
dos.writeObject(rec);
} finally {
if ( dos!=null ) {
dos.close();
}
}
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
}
Also, your program should do more validation of user input. Scanner can do that as follows:
public static class Employee implements Serializable {
private int id;
private String name;
private BigDecimal salary;
public Employee(int id, String name, BigDecimal salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}
static Employee getData(Scanner scanner) throws IOException {
System.out.printf("Enter Employee ID : ");
while ( !scanner.hasNextInt() ) {
System.out.println("Employee IDs are numbers only");
scanner.next();
}
int employeeId = scanner.nextInt();
System.out.printf("Enter Employee Name : ");
String name = scanner.next();
System.out.printf("Enter Employee Salary : ");
while ( !scanner.hasNextBigDecimal() ) {
System.out.println("Employee salaries are decimals " +
"not random gak");
scanner.next();
}
BigDecimal salary = scanner.nextBigDecimal();
return new Employee(employeeId, name, salary);
}
public static void main(String []args) throws Exception {
boolean moreRecords = true;
String path = null;
Scanner scanner = new Scanner(System.in);
File file = null;
System.out.printf("Enter path to save your file : ");
path = scanner.next();
file = new File(path);
while (moreRecords) {
Employee rec = Main.getData(scanner);
try ( ObjectOutputStream dos =
new ObjectOutputStream(
new FileOutputStream(file) ) ) {
dos.writeObject(rec);
}
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
Now the input/output is more like this:
Enter path to save your file : asdfasdf
Enter Employee ID : 9a
Employee IDs are numbers only
99
Enter Employee Name : Rick
Enter Employee Salary : aa
Employee salaries are decimals not random gak
99.99
Add more records [true/false]? false
The scanner forces the end user to enter in the right types of data.
You can combine it with regex to match patterns for names, etc.
I extended the example and added some discussion of the Scanner.
http://rick-hightower.blogspot.com/2013/10/java-scanner-example.html
In nextInt(), NoSuchElementFoundException occurs when the input is exhausted. So check the input that you give at prompt.
Related
I'm using NetBeans 16 and I'm trying to add the ability to edit a record from a text file I have saved separated by commas.
Ive tried this code here and I don't seem to get any errors (except the one produced as a result of the try catch) but I have no idea why this doesn't seem to work when I try to overwrite a record which I have selected ive tried everything I can think of I'm pretty new to coding so forgive me if there's some obvious error but I have no idea why this doesn't work my text file has 5 entries in a row if that helps but yeah any help is greatly appreciated
public class EditRecords {
private static Scanner x;
public static void main(String[]args)
{
String filepath = "VehicleInforUpd.txt";
System.out.println("Enter Registration of Entry You Wish To Edit");
Scanner scanner = new Scanner(System.in);
String editTerm = scanner.nextLine();
System.out.println("Enter new Registration: ");
String newReg = scanner.nextLine();
System.out.println("Enter new Make: ");
String newMake = scanner.nextLine();
System.out.println("Enter New Model: ");
String newModel = scanner.nextLine();
System.out.println("Enter New Year: ");
String newYear = scanner.nextLine();
System.out.println("Enter New Comments: ");
String newComment = scanner.nextLine();
editRecord(filepath,editTerm,newReg,newMake,newModel,newYear,newComment);
}
public static void editRecord(String filepath,String editTerm,String newReg,String newMake,String newModel, String newYear, String newComment)
{
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String reg = ""; String make = ""; String model = ""; String year = ""; String comment = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
while(x.hasNext())
{
reg = x.next();
make = x.next();
model = x.next();
year = x.next();
comment = x.next();
if(reg.equals(editTerm))
{
pw.println(newReg+","+newMake+","+newModel+","+ newYear+","+newComment);
}
else
{
pw.println(reg+","+make+","+model+","+year+","+comment);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
JOptionPane.showMessageDialog(null, "Changes Succesfully Saved");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The Print stack trace results but im not sure what would cause the NullPointerException im getting
java.lang.NullPointerException
at com.mycompany.anprsystems.EditRecords.editRecord(EditRecords.java:70)
at com.mycompany.anprsystems.EditRecords.main(EditRecords.java:52)
I'm writing JDBC in Java, my thought is to write a method called userInsertCruise, which can make user input the data, and these data will add a new row into my database table.
Here is my code look like:
public class Insert_Cruise {
public void userInsertCruise(Date sailingDate, Date returnDate,String departurePort,
String shipName, String portOfCalls, String cruiseSerialNumber, int passengerID){
while(true){
System.out.println("Input the sailing date:");
Scanner sc1 = new Scanner(System.in);
sailingDate = java.sql.Date.valueOf(sc1.next());
System.out.println("Input the return date :");
Scanner sc2 = new Scanner(System.in);
returnDate = java.sql.Date.valueOf(sc2.next());
System.out.println("Input the departure port:");
Scanner sc3 = new Scanner(System.in);
departurePort = sc3.next();
System.out.println("Input the ship name");
Scanner sc4 = new Scanner(System.in);
shipName = sc4.next();
System.out.println("Input the ports of calls:");
Scanner sc5 = new Scanner(System.in);
portOfCalls = sc5.next();
System.out.println("Input the cruise serial number:");
Scanner sc6 = new Scanner(System.in);
cruiseSerialNumber = sc5.next();
System.out.println("Input the passenger ID:");
Scanner sc7 = new Scanner(System.in);
passengerID = sc7.nextInt();
System.out.println("Are you finish establish your data? Y/N");
Scanner ans = new Scanner(System.in);
String answer = ans.next();
if(answer != "y"){
break;
}else{
continue;
}
public void insertCruise() throws SQLException
{
String url = ("org.apache.derby.jdbc.ClientDriver");
Connection conn = null;
Statement st = conn.createStatement();
try {
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/mydata");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
st.executeUpdate("INSERT INTO CRUISE ("
+ "SAILING_DATE, RETURN_DATE, DEPARTURE_PORT, SHIP_NAME,
PORTS_OF_CALLS, CRUISE_SERIAL_NUMBER, PASSENGER_ID_NUMBER) "
+ "VALUES (?,?,?,?,?,?,?)");
} catch (SQLIntegrityConstraintViolationException e) {
System.out.println("Record Already exists.");
}
}
Then I want to call the method in main:
Insert_Cruise insert = new Insert_Cruise();
insert.userInsertCruise(sailingDate, returnDate, passward, username, passward, username, 0);
insert.insertCruise();
However, it does not work. Because I have no parameter to input in the userInsertCruise method.
The reason that I don't want to use Scanner in the main method is it would make the main method too long. And I have to make user can insert row in different tables in my database, if I write all the scanner in main, it would be very mess.
Is there any method to fix this problem?
So I have this console app with line of Java code intended to modify the Book data inside txt file.
User will prompted to enter the book ID of the book that is going to be modified and then just basically enter all the book details.
public void UpdatingBookData()
{
int bid; String booktitle; String author; String desc; String Alley;
System.out.println("Enter Book ID: ");
bid = sc.nextInt();
System.out.println("Enter Book Title: ");
booktitle = sc.next();
System.out.println("Enter Book Author: ");
author = sc.next();
System.out.println("Enter Book Description: ");
desc = sc.next();
System.out.println("Enter Book Alley: ");
Alley = sc.next();
UpdateBook(bid, booktitle, author, desc, Alley);
}
public static void UpdateBook(int bid, String booktitle, String author, String desc, String Alley)
{
ArrayList<String> TempArr = new ArrayList<>();
try
{
File f = new File("book.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
String[] lineArr;
line = br.readLine();
while(line != null)
{
lineArr = line.split(" ");
if(lineArr[0].equals(bid))
{
TempArr.add(
bid + " " +
booktitle + " " +
author + " " +
desc + " " +
Alley );
}
else
{
TempArr.add(line);
}
}
fr.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
try
{
FileWriter fw = new FileWriter("book.txt");
PrintWriter pw = new PrintWriter(fw);
for(String str : TempArr)
{
pw.println(str);
}
pw.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
}
but when I run it, I keep receiving this error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at lmsconsole.Administrator.UpdateBook(Administrator.java:438)
at lmsconsole.Administrator.UpdatingBookData(Administrator.java:409)
at lmsconsole.Administrator.adminPanel(Administrator.java:52)
at lmsconsole.MainMenu.loginAdmin(MainMenu.java:68)
at lmsconsole.MainMenu.MainPanel(MainMenu.java:45)
at lmsconsole.LMSConsole.main(LMSConsole.java:24)
Is it because of the ArrayList or what? Thanks in advance!
I need help trying to rewrite this program using a linked list. Any help you can give me would help. I have never used linked lists before, and so far looking online has just confused me. Here is my code that is using an arraylist.
public class Main {
public static void main(String[] args) throws Exception {
String stdID, sName, fName, lName, mName;
int testScore1, testScore2, testScore3,totalNoHours;
float cGPA;
Students workobj;
//****************************************External Output*****************************************************
PrintWriter output;
output = new PrintWriter(new File("StudentRecords.txt"));
//****************************************External Input******************************************************
try {
//opening the file for input
FileInputStream istream = new FileInputStream("input.txt");
Scanner input = new Scanner(istream);
//creating an arraylist to store student objects
ArrayList<Students> AllStudents = new ArrayList<Students>();
while (input.hasNextLine()) {
//first I will read the student id
stdID = input.next();
//next I will read the student name
fName = input.next();
lName = input.next();
if (input.hasNextInt()) {
mName = "";
} else {
mName = input.next();
}
sName = fName + " " + lName + " " + mName;
//next read in the test scores
testScore1 = input.nextInt();
testScore2 = input.nextInt();
testScore3 = input.nextInt();
//next read in totalNoHours
totalNoHours = input.nextInt();
//next read in cGPA
cGPA = input.nextFloat();
//creating a student object
Students StudentRecord = new Students(stdID, sName, testScore1, testScore2, testScore3,totalNoHours,cGPA);
//now store this in allstudents
AllStudents.add(StudentRecord);
}//end of while
}//end of main
}//end of program
LinkedList<Student> list = new LinkedList<Student>();
for(Student s: AllStudents)
list.add(s);
public static void main(String[] args)
{
List<Integer> t=new ArrayList<Integer>();
t.add(1);
t.add(2);
t.add(5);
t.add(3);
System.out.println("ArrayList upcating to list");
for(Integer x:t)
{
System.out.println(x);
}
System.out.println(t instanceof ArrayList);
System.out.println(t instanceof LinkedList);
t=new LinkedList<Integer>(t);
System.out.println("After upcasted to linkedList");
for(Integer x:t)
{
System.out.println(x);
}
System.out.println(t instanceof LinkedList);
System.out.println(t instanceof ArrayList);
}
Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.