Scanner ignoring the String "name" - java

I am trying to take user input for name, last name, phone number and age.
For some odd reason the scanner is skipping name but none of the other variables.
Can someone point out my mistake please? I can't figure it out.
import java.util.Scanner;
public class Lab2{
String [][] info = new String [10][4];
public static void main(String [] args){
new Lab2();
}
public Lab2(){
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Student contact Interface");
System.out.println("Please select a number from the options below:");
while(true){
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("3: Display the contact list.");
System.out.println("0: Exit the contact list.");
int options = input.nextInt();
String name, lastName, number, age;
switch(options){
case 1:
System.out.println("Please enter the name: ");
name = input.nextLine(); // This is the String var that is not accepting input from...
System.out.println("Please enter the last name: ");
lastName = input.nextLine();
System.out.println("Please enter the phone number: ");
number = input.nextLine();
System.out.println("Please enter the age (eg. 25): ");
age = input.nextLine();
addStudent(name, lastName, number, age);
break;
case 2:
System.out.println("\nEnter the name to remove: ");
String delName = input.nextLine();
System.out.println("\nEnter the last name to remove: ");
String delLastName = input.nextLine();
remove(delName, delLastName);
break;
case 3:
display();
break;
case 0:
System.out.println("Thank you for using the contact Database.");
System.exit(0);
}
}
}
public void addStudent (String name, String lastName, String number, String age){
boolean infoInserted = false;
for(int i = 0; i < 10; i++){
if(info[i][0] == null || info[i][0].equals(null)){
info[i][0] = name;
info[i][1] = lastName;
info[i][2] = number;
info[i][3] = age;
infoInserted = true;
break;
}
}
if(infoInserted){
System.out.println("\nContact saved.\n");
}
else{
System.out.println("\nYour database is full.\n");
}
}
public void remove(String delName, String delLastName){
boolean removed = false;
int i = 0;
for (i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
if (info[i][0].equals(delName) && info[i][1].equals(delLastName)) {
while (i < 9) {
info[i][0] = info[i + 1][0];
info[i][1] = info[i + 1][1];
info[i][2] = info[i + 1][2];
info[i][3] = info[i + 1][3];
i++;
}
info[9][0] = null;
info[9][1] = null;
info[9][2] = null;
info[9][3] = null;
removed = true;
break;
}
}
}
if (removed) {
System.out.println("Contact removed.");
}
else {
System.out.println("Contact was not found.");
}
}
public void display (){
for (int i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
System.out.println("Contact " + (i + 1)+ ":");
System.out.println("\t" + info[i][0]);
System.out.println("\t" + info[i][1]);
System.out.println("\tPhone Number:" + info[i][2]);
System.out.println("\tAge:" + info[i][3]);
}
}
}
}

Add a
input.nextLine();
after your
int options = input.nextInt();
This is because:
nextInt method does not read the last newline character (of your integer input)
that newline is consumed in the next call to nextLine
causing name 'to be skipped'
so you need to 'flush away' the newline character after getting the integer input
Another option:
Take in the entire line, using input.nextLine()
Get the integer value using Integer.parseInt() to extract the integer value

It is skipping name because , input.nextInt() wont go to next input line.
You can use
int option=Integer.parseInt(input.nextLine());
then it wont skip name.

Related

Prevent duplicate Integer ID numbers in an Array using While vs If

I created a program that will add, view, update and delete student arrays. To prevent user from entering duplicate ID number, I used the following code:
public static void addStud() {
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) {
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = 0;
}
}
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[count] = new Student(numID, year, userName, course);
++count;
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
However, by inputting ID numbers 1-5 (again and again) for some reason the program accepts the duplicate ID [1]. What I, did is i change the if(numID == stud[x].getNumID()) to while(numID == stud[x].getNumID()) and it fix my problem.
I'm not good with debugging, I just want to know what went wrong? Why it works with while and not with if?
Bellow is my full program. Try to input ID numbers 1 - 5 and repeat it will accept the duplicate if used the IF statement.
import java.util.Scanner;
public class StudentArray {
static Scanner sc = new Scanner(System.in);
static Student[] stud = new Student[100];
static int count = 0;
public static void main(String[] args) {
while (true) {
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select) {
case 1:
addStud();
break;
case 2:
viewStud();
break;
case 3:
updateStud();
break;
case 4:
deleteStud();
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud() {
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) { // change if to while prevents duplicate
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = 0;
}
}
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[count] = new Student(numID, year, userName, course);
++count;
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
public static void viewStud() {
while(true) {
int select;
System.out.println("1. View Record by ID number ");
System.out.println("2. View Record by Course ");
System.out.println("3. View Record by Course and Year ");
System.out.println("4. View All ");
System.out.println("0. Return Main Menu ");
select = sc.nextInt();
sc.nextLine();
switch (select) {
case 1:
int view1;
System.out.println("Please enter Student ID Number: ");
view1 = sc.nextInt();
viewArray(view1);
break;
case 2:
String view2;
System.out.println("Please enter Student Course: ");
view2 = sc.nextLine();
viewArray(view2);
break;
case 3:
String view3;
int view4;
System.out.println("Please enter Student Course: ");
view3 = sc.nextLine();
System.out.println("Please enter Student Year: ");
view4 = sc.nextInt();
viewArray(view3, view4);
break;
case 4:
viewArray();
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void viewArray(){
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
}
public static void viewArray(int key){
boolean isExist = false;
int temp = 0;
for(int x = 0; x < count; ++x){
if(key == stud[x].getNumID()){
temp = x;
isExist = true;
break;
}
}
if(isExist){
System.out.println("1. Student ID: " + stud[temp].getNumID());
System.out.println("2. Student Name: " + stud[temp].getUserName());
System.out.println("3. Student Course: " + stud[temp].getCourse());
System.out.println("4. Student Year: " + stud[temp].getYear() +"\n");
}
else
System.out.println("The Student ID: " +key+ " is invalid");
}
public static void viewArray(String key){
boolean isExist = false;
for(int x = 0; x < count; ++x){
if(key.equalsIgnoreCase(stud[x].getCourse())){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() +"\n");
isExist = true;
}
}
if(isExist == false){
System.out.println("The Student Course: " +key+ " is invalid");
}
}
public static void viewArray(String course, int year){
boolean isExist = false;
for(int x = 0; x < count; ++x){
if(course.equalsIgnoreCase(stud[x].getCourse()) && year == stud[x].getYear()){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() +"\n");
isExist = true;
}
}
if(isExist == false){
System.out.println("The Student Course: " +course+ " and Year: "+year+" is invalid");
}
}
public static void updateStud(){
int numID, temp = 0;
boolean flag = false;
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
System.out.println("Enter Student ID to update: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count && flag == false; x++){
if (numID == stud[x].getNumID()){
temp = x;
flag = true;
}
}
if(flag) {
System.out.println("Enter Student Name: ");
stud[temp].setUserName(sc.nextLine());
System.out.println("Enter Student Course");
stud[temp].setCourse(sc.nextLine());
System.out.println("Enter Student Year");
stud[temp].setYear(sc.nextInt());
System.out.println("The Student ID: " + numID + " record has been updated");
}
else
System.out.println("The Student ID: " +numID+ " is invalid");
}
public static void deleteStud() {
int numID, temp = 0;
boolean flag = false;
if (count > 0){ // check if array is empty
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
System.out.println("Enter Student ID to delete: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count && flag == false; x++){
if (numID == stud[x].getNumID()){
temp = x; // get the index
flag = true; // stops the loop if id is found
}
}
for( ; temp < count -1; temp++){
stud[temp]=stud[temp+1];
}
stud[count-1] = null;
--count;
}
else {
System.out.println("Cannot delete [Array is Empty]");
}
}
}
My Student class:
public class Student {
private int numID, year;
private String userName, course;
public Student(int numID, int year, String userName, String course) {
this.numID = numID;
this.year = year;
this.userName = userName;
this.course = course;
}
public int getNumID() {
return numID;
}
public void setNumID(int numID) {
this.numID = numID;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
You don't need the while loop, if you fix the issue with your for loop. Suppose you entered user IDs 1 to 5, and then entered 1 again. The first iteration of the for loop will find that 1 == stud[0].getNumID(), so you will ask for new student ID. Then you'll get a new input and reset x to 0.
Now, x will be incremented to 1 by the x++ part of the loop, so if you entered 1 again, the loop will never compare 1 to stud[0].getNumID(), since x==1. Therefore the duplicate input will be accepted.
This can be fixed by resetting x to -1:
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) {
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = -1;
}
}
Of course there are much better ways to check for duplicate IDs (that would be more readable and more efficient). Use a HashSet<Integer> to store all the used IDs, and use the Set to check if a new ID has already been used.
For example:
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
Set<Integer> ids = new HashSet<>();
while (!ids.add(numID)) { // add returns false if numID is already in the Set
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
}
...

Professor gets a java.io.FileNotFoundException but I don't?

I had a project for my Java class where the user enters patients for a hospital then the program reads a file and the user can choose to amend their added patients to the file, print it out to the screen, or both. The program works perfectly in NetBeans for me but in the professor's comments, he says his compiler got a FileNotFoundException(Edit: It is actually a runtime error), even though I included the file in the package. When I emailed him, he only repeated that he received a FileNotFoundException.
Here is the code:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class xyzHospital {
static int numOfPat;
static Scanner input = new Scanner(System.in);
static String inp;
static ArrayList<Patient> p = new ArrayList<>();
public static void main(String[] args) throws IOException {
boolean done = false;
importPatients();
System.out.print("Add new patients to the report:\n");
while (done == false){
addPatient();
System.out.print("Are you done adding patients? (Y or N)\n");
inp = input.nextLine();
switch (inp.toLowerCase()){
case "y": done = true;
break;
case "n": done = false;
break;
default: System.out.print("You did not enter a valid character. The program will print results then exit.\n\n");
done = true;
break;
}
}
printAll();
}
static public void addPatient(){
numOfPat++;
Patient pat = new Patient();
p.add(pat);
pat.addInfo(numOfPat);
}
static public void printAll() throws IOException{
System.out.print("Do you want to output the report to the screen ('S'), to a file ('F'), or both('B')?\n");
inp = input.next();
PrintWriter writer = new PrintWriter("XYZHospitalExampleData-1.txt");
switch (inp.toLowerCase()){
case "s":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
for(int i = 0; i<numOfPat;i++){
p.get(i).print();
}
break;
case "f":
writer.print(""); //writes over file so there is no duplicate patients
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
}
break;
case "b":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
writer.print("");
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
p.get(i).print();
}
break;
}
}
//each patient from the file is added as a patient object
static public void importPatients() throws IOException{
try(Scanner read = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
while(read.hasNextLine()){ //one more line means that there is another patient to add
numOfPat++;
read.nextLine();
}
read.close();
try(Scanner r = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
for (int j=0; j < numOfPat; j++){
String line = r.nextLine();
Patient pat = new Patient();
p.add(pat);
String[] str = line.split("\\^"); //the delimiter ^ is used to separate information in the file
for (int i = 0; i < str.length; i++){
if(str[i].isEmpty()||str[i].matches("0")||str[i] == null){ //if str[i] is empty, that means that it will be skipped over
i++;
}
switch (i){
case 0: p.get(j).ID = Integer.parseInt(str[i]);
break;
case 1: p.get(j).nameLast = str[i];
break;
case 2: p.get(j).nameFirst = str[i];
break;
case 3: p.get(j).address = str[i];
break;
case 4: p.get(j).opAddr = str[i];
break;
case 5: p.get(j).city = str[i];
break;
case 6: p.get(j).state = str[i];
break;
case 7: p.get(j).zip = Integer.parseInt(str[i]);
break;
case 8: p.get(j).optZip = Integer.parseInt(str[i]);
break;
case 9: p.get(j).payDate = str[i];
break;
case 10: p.get(j).payment = Double.parseDouble(str[i]);
break;
case 11: p.get(j).owed = Double.parseDouble(str[i]);
break;
default: System.out.print("Error.\n");
break;
}
}
}
r.close();
}
}
}
}
Here is the patient class:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class Patient {
Scanner input = new Scanner(System.in);
String nameFirst, nameLast, address, opAddr,city, state, payDate;
int zip, optZip, ID;
double owed, payment;
public void print() {
System.out.printf("%-8s%-9s%-20s%-10s%-8s%-7s%-15s%-11.2f%-10.2f%n", nameLast, nameFirst, address, city, state, zip, payDate, owed, payment);
}
public void printToFile()throws IOException{
try (PrintWriter writer = new PrintWriter(new FileWriter("XYZHospitalExampleData-1.txt", true))) {
writer.write(ID + "^" + nameLast+ "^" + nameFirst + "^" + address + "^" + opAddr + "^" + city + "^" + state + "^" + zip + "^" + optZip + "^"+ payDate + "^" + payment + "^" + owed +"\n");
writer.close();
}
}
private void setName(){
System.out.print("Enter patient's first name.\n"); //user is asked for all information
nameFirst = input.nextLine(); //first three inputs use nextLine so it consumes the end of line character, so the address will be put in the string correctly.
System.out.print("Enter patient's last name.\n"); //if next() is used, the address is cut off at the first whitespace and the other elements of the address
nameLast = input.nextLine(); //are stored in the upcoming inputs.
if (nameFirst.isEmpty()||nameLast.isEmpty()){
System.out.print("You must enter the first and last name.\n");
setName();
}
}
public String getName(){
return nameFirst + " " + nameLast;
}
private void setAddr(){
System.out.print("Enter patient's address.\n");
address = input.nextLine();
if (address.isEmpty()){
System.out.print("You must enter the patients address.\n");
setAddr();
}
}
public String getAddr(){
return address;
}
private void setCity(){
System.out.print("Enter patient's home city.\n");
city = input.nextLine();
if(city.isEmpty()){
System.out.print("You must enter the patients city.\n");
setCity();
}
}
public String getCity(){
return city;
}
private void setState(){
System.out.print("Enter patient's state.\n");
state = input.nextLine();
if(state.isEmpty()){
System.out.print("You must enter the patients state.\n");
setState();
}
}
public String getState(){
return state;
}
private void setDate(){
System.out.print("Enter the payment date.\n");
payDate = input.next();
if(payDate.isEmpty()){
System.out.print("You must enter a payment date.\n");
setDate();
}
}
public String getDate(){
return payDate;
}
private void setZip(){
System.out.print("Enter patient's zipcode.\n");
try{
zip = input.nextInt();
}
catch(Exception e){
System.out.print("You must enter a valid 5-digit zipcode.\n");
input.next();
setZip(); //if it says that the setZip call will make the function loop infinitely, it is just a warning, it will not loop infinitely.
}
int length = String.valueOf(zip).length();
if(length != 5 && zip > 0){
System.out.print("You must enter a valid 5-digit zipcode.\n");
setZip();
}
}
public int getZip(){
return zip;
}
private void setOwed(){
System.out.print("Enter patient's due balance.\n");
try{
owed = input.nextDouble();
}
catch(Exception e){
System.out.print("Amount has to be a non-negative number.\n");
input.next();
setOwed();
}
int length = String.valueOf(owed).length();
if (owed <0 || length == 0){
System.out.print("Amount has to be a non-negative number.\n");
setOwed();
}
}
public double getOwed(){
return owed;
}
private void setPayment(){
System.out.print("Enter patient's payment amount.\n");
try{
payment = input.nextDouble();
}
catch(Exception e){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
input.next();
setPayment();
}
int length = String.valueOf(payment).length();
if(payment < 0 || length ==0 || payment > owed){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
setPayment();
}
}
public double getPayment(){
return payment;
}
private void setID(int Id){
ID = Id;
}
public int getID(){
return ID;
}
public void addInfo(int ID){
setID(ID);
setName();
setAddr();
setCity();
setState();
setZip();
setOwed();
setPayment();
setDate();
}
}
And here is the file XYZHospitalExampleData-1.txt:
12345^Jones^John^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/05/2015^250.0^25000.0
12346^Jones^Sara^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/20/2017^50.0^50000.0
12347^Doe^John^1235 XYZ Drive^null^Test City^IN^11234^0^01/05/2016^350.0^56799.0
12348^Doe^Sara^1235 XYZ Drive^null^Test City^IN^11234^0^11/09/2017^100.0^5020.52
12349^Lawson^Lonnie^12 South Drive^null^Test City^IN^11236^0^03/15/2013^253.51^25065.52
12349^Anderson^Sara^156 North Avenue^null^Test City^IN^11246^0^05/05/2013^21.33^251.56
12350^Smith^Andy^2455 East Street^null^Test City^IN^11246^0^12/05/2017^365.21^2543.33
It starts with their ID and ends with the amount that they owe. Any help to understand why my professor's compiler is giving him an error would be appreciated, and what I can do to be sure that it will be able to find the file so I do not have this problem again.
In the beginning of your main method you call importPatients which reads data from the XYZHospitalExampleData-1.txt file. If this file is not present, you'll get an exception (in the runtime, not a compiler error).
Most probably something went wrong when your package was unpackaged. Maybe the file was not copied to the expected location, something like that. One of the ways to address this would be to catch the FileNotFoundException and to display a message describing what went wrong and what is expected.

Making the first input save in a folder first and then reference it

I need my program to detect previous entries in it's contact list and negate the user from inputting two identical entries. I keep trying, but I either allow every entry, or the entry that's invalid is still saved to my list.
What I want is to make it so my program will be a phone book, and no two people in real life should have the same number. This is why I want there to be only one contact with any given number.
Here's my code for checking the entry:
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
}
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
return;
}else{
break;
}
}
contactList[num_entries].number = number;
Here's my full code for reference:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
class Entry {
public String fname, lname, number, note;
}
class PBN {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception{
Scanner s = new Scanner(System.in);
int i;
char C;
String code, Command;
contactList = new Entry[999];
num_entries = 0;
try {
readPhoneBook("PhoneBook.txt");
} catch (FileNotFoundException e) {}
System.out.println("Codes are entered as 1 to 8 characters.\n" +
"Use Commands:\n" +
" \"e\" for enter a new contact,\n" +
" \"f\" for find contact by fist name,\n" +
" \"r\" for find contact by last name,\n" +
" \"y\" for find contact by phone number,\n" +
" \"l\" for listing all the existing contacts,\n" +
" \"d\" for removing contacts by phone number,\n" +
" \"a\" for sort alphabetically by first name,\n" +
" \"n\" for sort alphabetically by last name,\n" +
" \"p\" for sort by number,\n" +
" \"q\" to quit.");
Command = null;
C = ' ';
while(true) { // loop infinitely
System.out.print("Command: ");
Command = stdin.nextLine();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
System.out.print("Search for contact by first name: ");
code = stdin.next();
stdin.nextLine();
index(code); break;
case 'r':
System.out.print("Search for contact by last name: ");
code = stdin.next();
stdin.nextLine();
index1(code); break;
case 'y':
System.out.print("Search for contact by phone number: ");
code = stdin.next();
stdin.nextLine();
index2(code); break;
case 'l':
listAllContacts(); break;
case 'q': // when user wants to quit
CopyPhoneBookToFile("PhoneBook.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt");
System.exit(0); // simply terminate the execution
case 'a':
sortList1();
break;
case 'n':
sortList2();
break;
case 'p':
sortListByPhoneNumber();
break;
case 'd': // m for deleting a contact; delete by phone number
System.out.print("Enter the phone number of a contact you wish to delete : ");
String number = stdin.nextLine();// read the contact number
removeEntry1(number); // remove the number from the entries
break;
default:
System.out.println("Invalid command Please enter the command again!!!");
}
}
}
public static void readPhoneBook(String FileName) throws Exception {
File F;
F = new File(FileName);
Scanner S = new Scanner(F);
while (S.hasNextLine()) {
contactList[num_entries]= new Entry();
contactList[num_entries].fname = S.next();
contactList[num_entries].lname = S.next();
contactList[num_entries].number = S.next();
contactList[num_entries].note = S.nextLine();
num_entries++;
}
S.close();
}
public static void addContact() {
System.out.print("Enter first name: ");
String fname = stdin.nextLine();
String lname;
String number;
String pattern = "^\\(?(\\d{3})?\\)?[- ]?(\\d{3})[- ](\\d{4})$";
while (fname.length() > 8 || fname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
fname = stdin.nextLine();
}
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname;
System.out.print("Enter last name: ");
lname = stdin.nextLine();
while (lname.length() > 8 || lname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
lname = stdin.nextLine();
}
contactList[num_entries].lname = lname;
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
break;
} else {
return;
}
}
}
contactList[num_entries].number = number;
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine();
num_entries++;
System.out.println();
}
public static void listAllContacts() {
for(Entry e : contactList) {
if(e != null)
displayContact(e);
else
break;
}
}
public static int index(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].fname.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index1(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].lname.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index2(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].number.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t");
System.out.println("--"+ contact.lname+"\t");
System.out.println("--"+ contact.number+"\t");
System.out.println("--"+ contact.note);
System.out.println("");
}
public static void sortList1() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].fname.compareToIgnoreCase(contactList[i].fname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
public static void sortList2() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].lname.compareToIgnoreCase(contactList[i].lname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
public static void CopyPhoneBookToFile(String FileName) throws Exception{
FileOutputStream out = new FileOutputStream(FileName);
PrintStream P = new PrintStream( out );
for (int i=0; i < num_entries; i++) {
P.println(
contactList[i].fname + "\t" +
contactList[i].lname + "\t" +
contactList[i].number + "\t" +
contactList[i].note);
}
}
public static void removeEntry1(String number) {
Entry[] newcontactList = new Entry[contactList.length];
int i = 0;
for(Entry e : contactList) {
if(e == null) break; // if an entry is null then break the loop
if(e.number.equals(number)) // if the given number matches the current number
continue; // then skip
newcontactList[i++] = e;
}
num_entries--; // decrease the number of entries by 1;
contactList = newcontactList;
}
public static void sortListByPhoneNumber() {
int i;
Entry temp;
for (int j = 0; j < num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].number.compareToIgnoreCase(contactList[i].number) > 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}
listAllContacts();
}
}
The problem is that while you are looping through your contactList in for (Entry e : contactList) you are not checking the whole list!
E.g. if in the first cycle e.number doesn't equal the new number it goes to else statement and breaks the loop, then it goes and calls contactList[num_entries].number = number; saving potentially the already existing number;
To fix your code with minimum changes - just remove the else{ break;}
If you want a safer and more performant solution, use HashSet data structure for your contactList or TreeSet if you want it to be sorted - it will make sure that you will never have a duplicate entry, you can use Set.contains(number) to check if the entry already exists, and additionally HashSet will improve the complexity of entry lookups to O(1), TreeSet slightly worse O(logn) - either better then looping through the whole array which is O(n).
One way you can do that by using a boolean
boolean isPresent = false;
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
isPresent = true;
break;
}
}
Now check if the variable changed or not and do the entry
if (!isPresent) {
contactList[num_entries].number = number;
//rest of code
}
In Java 8 you could use optional
Optional<String> presentPh = Arrays.stream(contactList).filter(e -> e.number.equals(number)).findAny();
Now check if you find anything in filter
if (!presentPh.isPresent()) {
contactList[num_entries].number = number;
//rest of code
}

Beginner Java: Understanding error message: Exception in thread "main" java.util.NoSuchElementException

I am very new to Java and I'm having trouble understanding the errors I get from these classes. Even though I have searched it up throughout stackoverflow and various other sites, I am not able to grasp the meaning of them. Any help would be great in understanding these errors messages.
Main Class
import java.io.IOException;
import java.util.Scanner;
public class Assignment4 {
public static void main (String[] args) throws IOException{
int command = 0;
Scanner kb=new Scanner(System.in);
System.out.print("Enter the name of the input file:Enter data.txt: ");
String fileName=kb.next();
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
prompt();
System.out.print("Enter a command: ");
String ans=kb.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("a") ||ans.equalsIgnoreCase("add") ||
ans.equalsIgnoreCase("sa") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("sn") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("s") || ans.equalsIgnoreCase("save") ||
ans.equalsIgnoreCase("c1") || ans.equalsIgnoreCase("change1") ||
ans.equalsIgnoreCase("c2") || ans.equalsIgnoreCase("change2") ||
ans.equalsIgnoreCase("c3") || ans.equalsIgnoreCase("change3") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (command)
{
case 1: cr.add();
break;
case 2: cr.sortAverage();
cr.display();
break;
case 3: cr.sortNames();
cr.display();
break;
case 4: cr.remove();
cr.display();
break;
case 5: cr.save();
cr.display();
break;
case 6: ClassRoll.changeScore1();
cr.display();
break;
case 7: ClassRoll.changeScore2();
cr.display();
break;
case 8: ClassRoll.changeScore3();
cr.display();
break;
case 9: Student s=cr.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 10: cr.display();
break;
case 11 : System.out.println("Are you sure you want to quit? "
+ "Yes or No");
String quit = kb.next();
if (quit.equalsIgnoreCase("y") ||
quit.equalsIgnoreCase("yes")){
System.exit(0);
}
else
{
prompt();
System.out.print("Enter a command --> ");
ans=kb.next();
}
cr.save();
System.out.println("Thank you for using this program");
}
}
}
public static void prompt(){
System.out.println("Enter one of the following commands: ");
System.out.println("a or add to add a student in the class roll");
System.out.println("sa or average to sort the students based "
+ "on their average");
System.out.println("sn or names to sort the students "
+ "based on their last names");
System.out.println("r or remove to remove a student from the class roll");
System.out.println("s or save to save the list of students back to the input"
+ "datafile");
System.out.println("d or display to display the class roll");
System.out.println("c1 or change1 to change score 1 of a student");
System.out.println("c2 or change2 to change score 2 of a student");
System.out.println("c3 or change3 to change score 3 of a student");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");}
Class Roll
public class ClassRoll {
ArrayList students = new ArrayList();
private String title;
private String fileName;
public ClassRoll(String f) throws IOException{
//acquires title of file
Scanner fileScan;
Scanner lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Course Title: " + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student name = new Student(firstName, lastName);
name.setScore1(lineScan.nextInt());
name.setScore2(lineScan.nextInt());
name.setScore3(lineScan.nextInt());
students.add(name);
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
}
}
void display(){
double classAverage = 0.0;
DecimalFormat f = new DecimalFormat("0.00");
System.out.println("\t" + title );
for (int i = 0; i < students.size(); i++){
//fix this part of the code, get average
Student name = (Student) students.get(i);
System.out.println(name.toString());
System.out.println("\n" + f.format(name.getAverage()));
classAverage = classAverage + name.getAverage();
}
System.out.println("\t\t\t" + f.format(classAverage / students.size()));
}
void add(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
System.out.print("Score 1: ");
int score1 = input.nextInt();
System.out.print("Score 2: ");
int score2 = input.nextInt();
System.out.print("Score 3: ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
static void changeScore1(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's first Exam score: ");
Integer score1 = kb.nextInt();
System.out.println("New score of Exam 1: ");
Integer newScore1 = kb.nextInt();
score1 = newScore1;
}
static void changeScore2(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's second Exam score: ");
Integer score2 = kb.nextInt();
System.out.println("New score of Exam 2: ");
Integer newScore2 = kb.nextInt();
score2 = newScore2;
}
static void changeScore3(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's third Exam score: ");
Integer score3 = kb.nextInt();
System.out.println("New score of Exam 3: ");
Integer newScore3 = kb.nextInt();
score3 = newScore3;
}
private int search(String fn, String ln) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(fn, ln)) {
return i;
} else {
i++;
}}
return -1;
}
Student find(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}
}
void remove(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student was not found within the list");
}
}
void sortAverage(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}
}
void sortNames(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}}}
void save() throws IOException{
OutputStream file = new FileOutputStream("data.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
output.close();
}}
}
Error Messages
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ClassRoll.<init>(ClassRoll.java:38)
at Assignment4.main(Assignment4.java:16)
hasNext() is a precondition for next(), or else you will get those exceptions. So hasNext() must match the corresponding next()

Scanner carriage return Overflow

If anyone can see where I've gone made a mistake in my code I would be eternally grateful. I recognize that it's an obscene amount of code, but I've been pulling my hair out with it over the last few days and simply cannot fathom what to do with it. I've asked others for help in my class but they cannot see where I have gone wrong. It's to do with carriage return scanner problem.
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at PropertyMenu.runMenu(PropertyMenu.java:109)
at PropertyMenu.main(PropertyMenu.java:7)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Any thoughts would be much appreciated.
Joe.
//ROOM CLASS
import java.util.Scanner;
public class Room{
private String description;
private double length;
private double width;
public Room (String description, double length, double width) {
this.description = description;
this.length = length;
this.width = width;
}
public Room(){
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter description of room:");
description = scan.next();
System.out.println("Enter length of room:");
length = scan.nextDouble();
System.out.println("Enter width of room:");
width = scan.nextDouble();
}
public double getArea () {
return length*width;
}
#Override
public String toString() {
String result = ("***********************************\n");
result +=(" Room Viewing \n");
result +=("************************************\n");
result +=("The width of the room is " + width + "m.\n");
result +=("the length of the room is " + length + "m.\n");
result +=("the name of the room is: " + description +".\n");
return result;
}
}
//HOUSE CLASS
import java.util.*;
public class House {
private ArrayList<Room> abode;
private int idNum, numRooms;
private double totalArea;
private static int internalCount = 1;
private String address, roomInfo, houseType;
public House (String address, String houseType, int numRooms){
System.out.println("THIS IS THE START OF MY 3 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
System.out.println("THIS IS THE END OF MY 3 ARGUMENT CONSTRUCTOR");
}
public House (String address, String houseType, int numRooms, String roomInfo){
System.out.println("THIS IS THE START OF MY 4 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
this.roomInfo = roomInfo;
Scanner scan = new Scanner(roomInfo);
String desc;
Double l;
Double w;
while (scan.hasNext()){
desc= scan.next();
l = Double.parseDouble(scan.next());
System.out.println("the length from here"+l);
w = Double.parseDouble(scan.next());
System.out.println("the width from here"+w);
new Room (desc,l,w);
}
System.out.println("THIS IS THE END OF MY 4 ARGUMENT CONSTRUCTOR");
}
public void addRoom (){
totalArea=0;
abode.add(new Room ());
for (int i=0; i<abode.size(); i++){
totalArea += abode.get(i).getArea();
}
}
public House () {
totalArea = 0;
abode = new ArrayList<Room>();
idNum = ++internalCount;
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter address of house:");
address = scan.next();
System.out.println("Enter number of rooms:");
numRooms = scan.nextInt();
System.out.println("Enter type of house:");
houseType = scan.next();
for (int i=1; i<=numRooms; i++){
addRoom();
}
}
int getIdNum() {
return idNum;
}
#Override
public String toString() {
String result =("************************************\n");
result +=(" House Viewing \n");
result +=("************************************\n");
result +=("The house ID is " + idNum +".\n");
result +=("The house address is " + address +".\n");
result +=("The number of rooms here is " + numRooms +".\n");
result +=("The house type is " + houseType +".\n");
result +=("The total area of the house is " + totalArea +".\n");
result +=(abode);
return result;
}
}
//DRIVER
import java.util.*;
import java.io.*;
public class PropertyMenu {
private ArrayList<House> properties =new ArrayList<House>();
public static void main (String[] args) throws IOException{
PropertyMenu menu = new PropertyMenu();
menu.runMenu();
}
public void runMenu() {
House h = null;
char selection = ' ';
Scanner s = new Scanner(System.in);
while (selection != 'e') {
System.out.println();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Welcome to my Property database");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("What do you want to do?");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("To ADD a house enter......A");
System.out.println("To VIEW a house enter.....V");
System.out.println("To DELETE a house enter...D");
System.out.println("To USE a file.............F");
System.out.println("To QUIT enter.............E");
selection = s.next().toLowerCase().charAt(0);
switch (selection) {
case 'a':
properties.add(new House());
break;
case 'v':
System.out.println("Do you want to view all houses (y/n)?");
String all = "";
all = s.next();
if (all.equalsIgnoreCase("y")){
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)));
}
}
else if(all.equalsIgnoreCase("n")){
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to view.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to view:");
int viewHouse = s.nextInt();
if (viewHouse <= properties.size() && viewHouse >= 1){
System.out.println(properties.get(viewHouse-1));
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
else{
System.out.println("Do you want to view all houses (y/n)?");
all = s.next();
}
break;
case 'd':
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to delete.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to delete:");
int deleteHouse = s.nextInt();
if (deleteHouse <= properties.size() && deleteHouse >= 1){
properties.remove(deleteHouse -1);
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
break;
case 'e':
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Goodbye ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
break;
//*********************************THIS IS WHERE MY PROBLEM IS, FROM HERE*************
case 'f':
try{
Scanner fileScan = new Scanner (new File("property.txt"));
while (fileScan.hasNext()){
System.out.println("THIS IS A FRESH LOOP");
String a;
String ht;
String rms1;
int rms;
String yn;
String rmInfo;
a = fileScan.nextLine();
System.out.println("ADDRESS"+a);
ht = fileScan.nextLine();
System.out.println("HOUSE TYPE"+ht);
rms1 = fileScan.next();
rms = Integer.parseInt(rms1);
System.out.println("HOUSEROOMs"+rms);
yn = fileScan.next();
String overflow = fileScan.nextLine();
System.out.println("Yes/no"+yn);
if (yn.equalsIgnoreCase("Y")){
System.out.println("THIS IS THE START OF CHOICE = Y");
rmInfo = fileScan.nextLine();
properties.add(new House(a, ht, rms, rmInfo));
System.out.println("THIS IS THE END OF CHOICE = Y");
}
else{
System.out.println("THIS IS THE START OF CHOICE = N");
properties.add(new House(a, ht, rms));
System.out.println("THIS IS THE END OF CHOICE = N");
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
//******************************************TO HERE^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
default:
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Try again! ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
System.out.println("Exiting program.");
}
}
This is could be a guess that you are not reading file correctly. Whatever I see from your block of file reading code and input file "property.txt" , make following changes.
In your while use following, as you are reading file line by line.
while (fileScan.hasNextLine()){
Only use nextLine() method
rms1 = fileScan.nextLine();
yn = fileScan.nextLine();
I hope these will solve your problem.

Categories

Resources