Not able to serialize java.util.HashMap object - java

I am trying to write hashmap to file and read it back. Initially, my file is empty. so, when i try to read using readObject(), it throws EOFException. I caught it and proceed with normal execution. Then, I input details of a student. Insert the details in hashmap using rollnumber as key. Then, i write the hashmap to the file using writeObject(). I check the file and it had something written in it.
I close the program and execute it again.
This time it should have read the hashmap that i had written. But, instead it clears the file and still throws EOFException.
Help me.. how should i do it???
Student.java
package student;
public class Student implements java.io.Serializable {
private String name;
private int age;
class Address implements java.io.Serializable{
String house;
String street;
String city;
String state;
int pin;
Address(String house,String street,String city,int pin,String state){
this.house = new String(house);
this.street = new String(street);
this.city = new String(city);
this.state = new String(state);
this.pin = pin;
}
}
private Address addr;
private int rollnumber;
private String courses[];
public Student(String name,int age,String house,String street,String city,String state,int pin,int roll, String courses[]){
this.name = new String(name);
this.age = age;
this.addr = new Address(house,street,city,pin,state);
this.rollnumber = roll;
this.courses = new String[4];
System.arraycopy(courses, 0, this.courses, 0, 1);
System.out.println("NEW STUDENT CREATED..");
}
public String toString(){
String s = rollnumber +" "+name+" "+age+"\n";
return s;
}
int getRollNumber(){
return rollnumber;
}
}
I have made both classes Student and inner class Address serializable. Tell me if there is any trouble here.
StudentRunner.java
package student;
import java.io.*;
import java.util.*;
public class StudentRunner {
public static void main(String [] args) throws java.io.IOException, ClassNotFoundException{
String file = "student.txt";
StudentProcessor sp = new StudentProcessor();
FileOutputStream fout = new FileOutputStream(file);
FileInputStream fin = new FileInputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fout);
ObjectInputStream in = new ObjectInputStream(fin);
HashMap<Integer, Student> hm= new HashMap<Integer, Student>();
Student stud=null;
try{
hm = (HashMap<Integer, Student>)in.readObject();
///////// TROUBLE IN THE ABOVE LINE ///////////
}catch(EOFException eof){
System.out.println("sfdasfasfas");
}
Scanner scanner = new Scanner(System.in);
int option=0;
do{
System.out.println("(1) Add User Details");
System.out.println("(2) Display User Details");
System.out.println("(3) Delete User Details");
System.out.println("(4) Save User Details");
System.out.println("(5) Exit");
try{
option = scanner.nextInt();
}catch(InputMismatchException ime){
System.out.println("Error!!! provide valid option(1-5).");
continue;
}
switch(option){
case 1:
try{
scanner.nextLine();
System.out.println("Enter full name: ");
String name = scanner.nextLine();
System.out.println("Enter age: ");
int age = scanner.nextInt();
System.out.println("Enter rollnumber: ");
int rollnumber = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter Address:");
System.out.println(" Enter house number ");
String house_num = scanner.nextLine();
System.out.println(" Enter street: ");
String street = scanner.nextLine();
System.out.println(" Enter city: ");
String city = scanner.nextLine();
System.out.println(" Enter state: ");
String state = scanner.nextLine();
System.out.println(" Enter pin: ");
int pin = scanner.nextInt();
String courses[] = new String[4];
System.out.println("Enter four courses(A-F)");
System.out.println(" Enter first course: ");
courses[0] = scanner.next();
System.out.println(" Enter second course: ");
courses[1] = scanner.next();
System.out.println(" Enter third course: ");
courses[2] = scanner.next();
System.out.println(" Enter fourth course: ");
courses[3] = scanner.next();
boolean flag = Validator.validateStudent(name, age, rollnumber, house_num, street, city,
state, pin, courses);
stud= new Student(name,age,house_num,street,city,state,pin,rollnumber,courses);
if(flag){
hm.put(rollnumber, stud );
}
}catch(InputMismatchException ime){
System.out.println("Error!!! Provide numeric value..");
continue;
}
break;
case 2:
Set set = hm.entrySet();
Iterator itr = set.iterator();
while(itr.hasNext()){
Map.Entry<Integer, Student> m =(Map.Entry<Integer, Student>) itr.next();
System.out.println(m.getValue());
}
break;
case 3:
break;
case 4:
out.writeObject(hm);
break;
case 5:
break;
default:
System.out.println("Error!!! provide valid option(1-5).");
continue;
}
if(option>=5)
break;
}while(true);
}
}
hm.readObject() in StudentRunner.java, is where i am reading the content. But it clears the already written content and throws EOFException.

Remember always to call the close method on the OutputStream you are using to write. The accepted idiom to do so is to do it inside a finally {} block so you make totally sure you are closing the OutputStream (and thus actually flushing the buffer into disk)

Related

How to alphabetize a phonebook in a string

I have my PhoneBook program but I am trying to get the entries to automatically be put in alphabetical order when the user enter "l" for the list of entries. I can't figure out though how to do that. I've tried putting it into a list a sorting it that way but it only takes the first name of the entry.
import java.io.*;
import java.util.*;
class Entry {
public String fname, number, note, lname;
}
public class Main {
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{
int i; char C;
String code, Command;
contactList = new Entry[200];
num_entries = 0;
readPhoneBook("PhoneBook.txt");
System.out.println("Please Enter A Command.\nUse" +
" \"e\" for enter," +
" \"f\" for find," +
" \"l\" for listing all the entries," +
" \"m\" to merge duplicate entries," +
" \"d\" to delete an entry," +
" \"q\" to quit.");
Command = null;
C = ' ';
while(C != 'q'){
System.out.print("Command: ");
Command = stdin.next();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
code = stdin.next();
stdin.nextLine();
i = index(code);
if (i >= 0) displayContact(contactList[i]);
else System.out.println("**No entry with code " + code); break;
case 'l':
listAllContacts(); break;
case 'q':
CopyPhoneBookToFile("PhoneBook1.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt"); break;
case 'm':
break;
case 'd':
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.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}
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))
return i; // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t"+
contact.lname+"\t"+
contact.number+"\t"+
contact.note);
}
public static void listAllContacts() {
int i = 0;
while (i < num_entries) {
displayContact(contactList[i]);
i++;
}
}
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);
}
}}
this is the bit for entering a new contact
public static void addContact() {
System.out.print("Enter First Name: ");
String fname = stdin.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}
I would make a compareTo method in your Entry class and set it up to compare how you want it to. The most important part would be how you store your Entries though. If you use a sorted array, you can just sort everything as you enter it into the array, and blast through linearly when you want to read it out

Output prints first and part of second string. String sizes not set correctly

I've been writing this program that is supposed to build accounts for people inputted, saving their info all together in as one "superString" string, so it can be written and read from a txt file. I thought I had it all together correctly, but after testing various inputs and then reading back, it seems as though it isn't setting up the string lengths correctly.
If I only want account number 1, it will print out the account number 1.
If I put more accounts in and then try to only print out account 1, it'll print out account 1 and part of 2.
The output changes based on the size of the inputs, even though I put loops in there to have strict sizes.
I've been looking at the same problem for too long now and hopefully I'm just overlooking an easy fix. Can anyone help me out with this?
public class FirstTr {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
File loc = new File("C:\\Users\\Desktop\\Exc2.1.txt");
RandomAccessFile store = new RandomAccessFile(loc, "rw");
for(int i=0; i<20; i++)
{
String dummy = "12345678901234567890123456789012345678901234567890123456789012345678901";
store.writeUTF(dummy);
}
String userChoice = GettingUserInput();
System.out.println("The choice you entered: " +userChoice);
while(true){
if(userChoice.equals("new"))
{
String playerID = PlayerIDMethod();
System.out.println("The playerID you entered: " +playerID);
String playerName = PlayerNameMethod();
System.out.println("The playerName you entered: " +playerName);
String playerTeamName = PlayerTeamNameMethod();
System.out.println("The playerTeamName you entered: " +playerTeamName);
String playerSkillLevel = PlayerSkillLevelMethod();
System.out.println("The playerSkillLevel you entered: " +playerSkillLevel);
String todaysDate = TodaysDateMethod();
System.out.println("The date you entered: " +todaysDate);
String superString = "";
superString = playerID + playerName+ playerTeamName + playerSkillLevel + todaysDate;
//System.out.println("Combined string is: "+superString);
int playerIDDigit = Integer.parseInt(playerID);
store.seek((playerIDDigit-1)*73);
store.writeUTF(superString);
System.out.println("Length of string: " +superString.length());
userChoice = GettingUserInput();
}
if(userChoice.equals("old"))
{
System.out.println("Please enter player ID: ");
String desiredID = input.next();
int recLocation;
recLocation = Integer.parseInt(desiredID);
store.seek((recLocation-1)*73);
String printed = store.readUTF();
System.out.println("String: "+printed);
userChoice = GettingUserInput();
}
if(userChoice.equals("end"))
{
System.out.println("Program Closed.");
store.close();
System.exit(0);
}
}
}
public static String GettingUserInput()
{
System.out.println("Please type in a command: new, old, or end to exit");
String userChoice = input.next();
while(!userChoice.equals("New") && !userChoice.equals("new") && !userChoice.equals("Old") && !userChoice.equals("old") && !userChoice.equals("End") && !userChoice.equals("end"))
{
System.out.println("Looks like you didn't enter a correct choice.");
System.out.println("Please type in a command: new, old or end");
userChoice = input.next();
}
return userChoice;
}
public static String PlayerIDMethod()
{
String playerID = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please input Player ID: ");
playerID = input.next();
int playerIDDigit = Integer.parseInt(playerID);
if (playerID.length()> 5){
playerID.substring(0,5);
}
if (playerID.length()< 5){
StringBuilder paddedName = new StringBuilder(playerID);
while(paddedName.length()<5){
paddedName.append(" ");
}
playerID = paddedName.toString();
}
while(Pattern.matches("[a-zA-Z]+", playerID)|| playerID.startsWith("-")|| playerIDDigit>20 || playerIDDigit<0)
{
System.out.println("Player ID cannot have characters, negatives, and must be within 1-20!");
System.out.println("Please input Player ID: ");
playerID = input.next();
}
loop = false;
}
catch(Exception e)
{
System.out.println("No way Hosay! Only Integers!");
}
}
return playerID;
}
public static String PlayerNameMethod ()
{
String playerName = "";
try{
System.out.println("Enter Player's Name: ");
playerName = input.next();
while(Pattern.matches("^\\d+", playerName))
{
System.out.println("No cool names include numbers! Try again.");
System.out.println("Enter Player's Name: ");
playerName = input.next();
}
if (playerName.length()> 26){
playerName.substring(0,26);
}
if (playerName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerName = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerName;
}
public static String PlayerTeamNameMethod ()
{
String playerTeamName = "";
try
{
System.out.println("Please enter Team name: ");
playerTeamName = input.next();
if (playerTeamName.length()> 26){
playerTeamName.substring(0,26);
System.out.print("The Player Name is" + playerTeamName);
}
if (playerTeamName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerTeamName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerTeamName = paddedName.toString();
}
}
catch(Exception e)
{
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerTeamName;
}
public static String PlayerSkillLevelMethod ()
{
String playerSkillLevel = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
while(Pattern.matches("[a-zA-Z]+", playerSkillLevel))
{
System.out.println("Player skill level must be an integer!");
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
}
loop = false;
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN ");
}
}
return playerSkillLevel;
}
public static String TodaysDateMethod (){
String todaysDate = "";
try{
System.out.println("Please enter todays date: ");
todaysDate = input.next();
if (todaysDate.length()> 9)
{
todaysDate = todaysDate.substring(1,9);
}
if (todaysDate.length()< 9)
{
StringBuilder paddedName = new StringBuilder(todaysDate);
while(paddedName.length()<26){
paddedName = paddedName.append(" ");
}
todaysDate = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR ");
}
return todaysDate;
}
//CONVERT TO STRING
public static String RecordtoFile (RandomAccessFile store){
return null;
}
//WRITE INTO FILE AT RECORD LOCATION INDICATED BY ID
public static String WriteToFile (RandomAccessFile store){
return null;
}
}
The way I see it resolved is creating a Person class with a constructor that would take an int id and a String name as parameters.
This class would have a private void recordToFile method and you would only record one person per line in the id space name format.
Aditionally, in the FirstTr class you would have a private Person retrieveFromFile(int id) that would verify every line in the file and would return the Person with the given id or null if no person was found. That method could get a String name too in the parameters but it's really your call.
The way using a String[ ] could be useful too but you should decide.
I found what was causing the problem. When parsing, three of the five values that make up the string had been set to length 26, so this already created a string of length 78. The desired size is 71, and when the other two values are added, it can reach to 80 or 81. Changing what the strings are parsed or added to changed the length of the super string and no longer run into any issues. Thanks for the help

How to get a scanner to loop until it reads a desired string?

Scanner one = new Scanner(System.in);
System.out.print("Enter Name: ");
name = one.nextLine();
System.out.print("Enter Date of Birth: ");
dateofbirth = one.nextLine();
System.out.print("Enter Address: ");
address = one.nextLine();
System.out.print("Enter Gender: ");
gender = //not sure what to do now
Hi I've tried to figure this out myself but I can't quite get it from looking at other examples, most are either only accepting certain characters or A-Z+a-z
I'm trying to make the program only accept input of male or female ignoring the case and if the input is wrong to repeat the "Enter Gender:" until a correct value is entered.
You can put the piece of code in a while and validate each time. for instance:
String gender;
do
{
System.out.print("Enter Gender ('male' or 'female'): ");
gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))
do {
System.out.print("Enter Gender (M/F): ");
gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));
You can add an if check after gender assignment to display a invalid message
One way to do this is to use infinite loop and a label to break out.
Like this:
//Start
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
String str = one.nextLine();
switch (str.toUpperCase()){
case "MALE":
System.out.println("Cool");
break here;
case "FEMALE":
System.out.println("Nice");
break here;
default:
System.out.println("Genders variants: Male/Female");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = readValue(scanner, null);
System.out.print("Enter Date of Birth: ");
String dateofbirth = readValue(scanner, null);
System.out.print("Enter Address: ");
String address = readValue(scanner, null);
System.out.print("Enter Gender: ");
String gender = readValue(scanner, createGenderMatcher());
}
private static IMatcher createGenderMatcher() {
return new IMatcher() {
#Override
public boolean isMatch(String value) {
return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
}
};
}
private static String readValue(Scanner scanner, IMatcher matcher) {
String value = null;
do {
value = scanner.nextLine();
} while (matcher != null && !matcher.isMatch(value));
return value;
}
private interface IMatcher {
public boolean isMatch(String value);
}

Can someone help me figure out why one of my methods is not running at all?

Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}

Programming "Add Method" array seems to not be working

Hi, I'm very new to java and I'm currently trying to create a student name and mark menu but I'm having trouble with my add method, I think it's something to do with my Arrays but I can't figure it out, any help would be appreciated.
Below is my unitResult method
public class UnitResults
{
private String unitTitle;
private String [] fName;
private String [] surname;
//private String [] UnitResults;
private int [] Marks;
private int Mark;
private int pointer ;
private static String course = "HND Computing";
public UnitResults(int Size,String title)
{
this.fName = new String [Size];
this.surname = new String [Size];
this.Marks = new int [Size];
pointer = 0;
fName[pointer] = "Daniel";
surname[pointer] = "Scullion";
Marks[pointer] = 60;
unitTitle = title;
pointer ++;
}
public Boolean add( String tempfName, String tempsName, int newGrade)
{
if (pointer == fName.length)
{
System.out.println("The Students Database is full");
return false;
}
else
{
fName [pointer] = tempfName;
surname [pointer] = tempsName;
Marks[pointer] = newGrade;
pointer ++;
return true;
}
}// end Add
but when I try to add this using a menu system below
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempfName,newGrade);
break;
When I enter my option 1 the output that I get is :
Please Enter The Students First Name
Please Enter The Students Last Name
Any ideas what's wrong here been searching for a long time, probably something simple but I've no idea :/
Edit: below is my menu class
import java.util.Scanner;
public class MenuResults {
static Scanner keyb = new Scanner(System.in);
public static int menuSystem()
{
System.out.println("*********************************");
System.out.println(" ");
System.out.println("1.Add New Student");
System.out.println("2.Display Students Details");
System.out.println("3.Delete a Students");
System.out.println("4.Update Student Details");
System.out.println("5.Sort Students By Mark");
System.out.println("6.Sort Students By Surname");
System.out.println("7.Search For A Student");
System.out.println(" ");
System.out.println("**********************************");
System.out.print("\n Enter choice:");
int option = keyb.nextInt();
return option;
}
public static void main(String[] args) {
UnitResults myUnit = new UnitResults(3, "Java");
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
break;
case 2:
myUnit.display();
break;
case 3:
break;
case 4:
break;
case 5:
case 6:
break;
default:
System.out.println(" Invalid Entry");
}//end switch
}
}
}
There is my whole menu class as asked for.
EDIT: when I forget the user input and hard input it using: myUnit.add("John","tommy",12);
I get "Student Database is full" about one hundred times..
Wild guess, when you use your menu and type 1 then ENTER a carriage return (\n) for the ENTER is still present in your Scanner after nextInt() is called.
So next call to readLine() will use the \n (remaining ENTER) for the line and will not wait for user input.
Possible correction:
public static int menuSystem()
{
final Scanner keyb = new Scanner(System.in);
// ...
}
public static void main(String[] args) {
final UnitResults myUnit = new UnitResults(3, "Java");
int option = menuSystem();
while (option != 6) {
final Scanner keyb = new Scanner(System.in);
// ...
option = menuSystem();
}
}
And removal of the static kbd declaration
A better solution is to simply call keyb.nextLine() after calling keyb.nextInt() to handle the end of line token. Quite simply change this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
to this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
keyb.nextLine(); // ****** add this *******
myUnit.add(tempfName, tempsName,newGrade);

Categories

Resources