**this is what I have done so far. This program need me to display student info. There is no error when I run the program but the grade just isn't displayed. **
import java.io.*;
import java.math.MathContext;
class StudInfo {
public static DataInputStream d = new DataInputStream(System.in);
public static String matricNo[] = new String[100];
public static String name[] = new String[100];
public static int courseWorkMark []= new int[100];
public static int finalExamMark[] = new int [100];
public static String grade[] = new String[100];
public static double mark1;
public static double mark2;
public static int x = 1;
public static String sgrade;
public static int scourseWorkMark;
public static int sfinalExamMark;
//MENU
public static void main(String[] args)throws IOException {
menu();
}
public static void menu()throws IOException {
System.out.println("<<<-- MAIN MENU -->>>");
System.out.println("");
System.out.println("[1] Add\n[2] Edit\n[3] Delete\n[4] Search\n[5] View\n[6] Exit");
System.out.println("");
System.out.print("Select a menu: ");
int m = Integer.parseInt(d.readLine());
switch(m) {
case 1: //ADD DATA
addData();
break;
case 2: //EDIT DATA
editData();
break;
case 3: //DELETE DATA
DeleteData();
break;
case 4: //SEARCH DATA
SearchData();
break;
case 5: //VIEW DATA
viewData();
break;
case 6: //EXIT SYSTEM
break;
default:
break;
}
}
//DELETE
public static void DeleteData()throws IOException {
boolean result = false;
int index = 0;
spacing();
System.out.print("<<<-- DELETE RECORDS -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print("Matric: "+matricNo[index].toUpperCase()+ " ");
System.out.print("Name: "+name[index].toUpperCase()+ " ");
System.out.print("Course Work: "+courseWorkMark[index]+ " ");
System.out.print("Final Exam: "+finalExamMark[index]+ " ");
System.out.print("Grade: "+grade[index].toUpperCase()+ " ");
System.out.println("");
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = null;
name[index] = null;
courseWorkMark[index] = 0;
finalExamMark[index] = 0;
grade[index] = null;
for(int j=index+1;j<matricNo.length;j++)
{
matricNo[j-1] = matricNo[j];
name[j-1] = name[j];
courseWorkMark[j-1] = courseWorkMark[j];
finalExamMark[j-1] = finalExamMark[j];
grade[j-1] = grade[j];
}
System.out.println("Record succesfully deleted!");
System.out.println("\n\n<Press Enter>");
String Ques1 = d.readLine();
spacing();
menu();
} else{
spacing();
menu();
}
} else{
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//SEARCH
public static void SearchData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- SEARCH DATA -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result==true) {
System.out.print("Matric: " + matricNo[index].toUpperCase() + " ");
System.out.print("Name: " + name[index].toUpperCase() + " ");
System.out.print("Course Work: " + courseWorkMark[index] + " ");
System.out.print("Final Exam: " + finalExamMark[index] + " ");
System.out.print("Grade: " + grade[index].toUpperCase() + " ");
System.out.println("");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//ADD
public static void addData()throws IOException {
spacing();
System.out.print("<<<-- ADD DATA -->>>\n\n");
System.out.print("Student Matric Number: ");
String smatricNo = d.readLine();
System.out.print("Student Name: ");
String sname = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[x] = smatricNo;
name[x] = sname;
courseWorkMark[x] = scourseWorkMark;
finalExamMark[x] = sfinalExamMark;
grade[x] = sgrade;
x++;
spacing();
menu();
}else if(Ques.equalsIgnoreCase("n")) {
spacing();
menu();
}
}
public static void spacing() {
System.out.print("\n\n\n");
}
//VIEW
public static void viewData()throws IOException {
boolean center = false;
spacing();
System.out.print("<<<-- VIEW DATA -->>>\n\n");
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] != null) {
System.out.print("Matric Number: " + matricNo[i].toUpperCase()+ " ");
System.out.print("Name: " + name[i].toUpperCase()+ " ");
System.out.print("Course Work: " + courseWorkMark[i]+ " ");
System.out.print("Final Exam: " + finalExamMark[i]+ " ");
System.out.print("Grade: " + grade[i].toUpperCase()+ " ");
System.out.println("");
center=true;
}
}
if(center == false) {
System.out.print("\nEMPTY DATABASE. NO RECORDS FOUND!");
}
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
//EDIT
public static void editData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- EDIT DATA -->>>\n\n");
System.out.print("Search Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print(matricNo[index] + " " +name[index]+ " " +courseWorkMark[index]+ " " +finalExamMark[index]+ " " +grade[index]+ " \n\n");
System.out.print("Student Matric Number: ");
String smatricNoedit = d.readLine();
System.out.print("Student Name: ");
String snameedit = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to update this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = smatricNoedit;
name[index] = snameedit;
courseWorkMark[index] = scourseWorkMark;
finalExamMark[index] = sfinalExamMark;
grade[index] = sgrade;
spacing();
menu();
}
else if(Ques.equalsIgnoreCase("n"))
{
spacing();
menu();
}
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//CALCULATION PART
public static String Calculate()
{
double mark1 = scourseWorkMark * 60 / 100;
double mark2 = sfinalExamMark * 40 / 100;
double totalMark = mark1 + mark2;
if (totalMark >= 90)
{
sgrade = "A+";
}
else if (totalMark >= 80)
{
sgrade = "A";
}
else if (totalMark >= 70)
{
sgrade = "A-";
}
else if (totalMark >= 65)
{
sgrade = "B+";
}
else if (totalMark >= 60)
{
sgrade = "B";
}
else if (totalMark >= 55)
{
sgrade = "C+";
}
else if (totalMark >= 50)
{
sgrade = "C";
}
else if (totalMark >= 45)
{
sgrade = "D";
}
else if (totalMark >= 40)
{
sgrade = "E";
}
else
{
sgrade = "F";
}
return;
}
}
Why can't the grade be displayed?
In the public static String Calculate() function, you need to return return sgrade; and currently, you are not returning any object, but the method calls for the return of a string.
Also, remove String sgrade = d.readLine(); from line 199 (in the addData function). This is causing problems, because you are defining a new variable with the same name as a class variable, and not specifying which one to use on the next few lines.
When I fix this, here is the output:
<<<-- MAIN MENU -->>>
[1] Add [2] Edit [3] Delete [4] Search [5] View [6] Exit
Select a menu: 1
<<<-- ADD DATA -->>>
Student Matric Number: 1
Student Name: Jake Chasan
Course Work: 100
Final Exam: 100 Grade: A+
<<<-- VIEW DATA -->>>
Matric Number: 1 Name: JAKE Course Work: 100
Final Exam: 100 Grade: A+
Related
I've just started programming recently and have ran into a few minor errors. I'm creating a library object which holds references to book objects and member objects, however I'm having trouble accessing methods from the member class and using them in the library class without errors popping up in the LibraryTester class. This is what I've coded
Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private MemberList members;;
public Library(ArrayList<Book> Books, Member member) {
this.Books = Books;
this.members=members;
};
public void displayBooks() {
System.out.println("\t\t\t-----The Current Books in the library are-----");
for (int i = 0; i < Books.size(); i++) {
System.out.println("\n" + "\t\t" + Books.get(i).getTitle() + "\t\t\t" + "\n\t\tAuthor: "
+ Books.get(i).getAuthor() + "\n\t\tThis Books ID is: " + Books.get(i).getBookID() + "\t\t\t\t\t\t"
+ "\n\t\tIs this book on loan? " + Books.get(i).getOnLoan() + "\t\t\t\t\t"
+ "\n\t\tThe number of times which this book has been loaned: " + Books.get(i).getNumOfLoans()
+ "\t\t");
}
}
// method to remove permanently a book object
public void removeBook() // the parameter that is passed through
// is the book id of the book that is to
// be removed
{
Scanner input = new Scanner(System.in);
int bookID = 0;
boolean successful = false;
try {
do {
System.out.println("Please enter the book ID of the book you wish to delete");
bookID = input.nextInt();
for (int i = 0; i < Books.size(); i++) {
if (bookID == Books.get(i).getBookID())
{
System.out.println("The Book " + Books.get(i).getTitle() + " was removed");
Books.remove(i);
successful = true;
break;
}
}
if (!successful) {
System.out.println("Book ID " + bookID + " does not exist");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void editBook() {
boolean successful = false;
try {
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the book ID of the book who's details you wish to change");
int bookID = sc.nextInt();
sc.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
System.out.println("Please enter the new name of the book:");
String newTitle = sc.nextLine();
Books.get(i).setTitle(newTitle);
System.out.println("Please enter the name of the author of the book:");
String newAuthor = sc.nextLine();
Books.get(i).setAuthor(newAuthor);
System.out.println("Change of book details successful" + "\nNew book title: " + newTitle
+ "\nNew author: " + newAuthor);
successful = true;
}
}
if (!successful) {
System.out.println("This book does not exist ");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void addBook() {
boolean successful = false;
int bookID = 0;
String title = "";
String author = "";
Scanner input = new Scanner(System.in);
do {
System.out.println("Please assign a 3 digit number for the books ID ");
bookID = input.nextInt();
input.nextLine();
if(bookID > 99 && bookID <1000){
for (int i = 0; i < Books.size(); i++) {
if(Books.get(i).getBookID()!= bookID){
successful = true;
} else {
System.out.println("This book ID already exists ");
}
}
} else { System.out.println("You must enter a number between 99 and 1000 ");
}
} while (successful == false);
do {
System.out.println("Please enter the name of book");
title = input.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getTitle().equalsIgnoreCase(title)) {
System.out.println("ERROR: This book already exists");
successful = false;
} else {
successful = true;
}
}
} while (successful == false);
do {
System.out.println("Please enter the author of the book");
author = input.nextLine();
successful = true;
} while (successful == false);
Book Book = new Book(bookID, title, author, false, 0, 0);
Books.add(Book);
System.out.println(
"Book creation succcessful:" + "\nTitle: " + title + "\nAuthor: " + author + "\nBook ID:" + bookID);
}
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
do {
System.out.println(
"\nPlease enter the book ID of the book that you wish to take out (Press 9 to exit to the main menu)");
int bookID = input.nextInt();
if (bookID == 9) {
successful = true;
break;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
do {
System.out.println("\nHow long would you like to loan the book for (20 Days maximum):");
int durationOnLoan = input.nextInt();
if (durationOnLoan <= 20 && 1 <= durationOnLoan) {
Books.get(i).setDurationOnLoan(durationOnLoan);
successful = true;
} else {
System.out.println("The number of days you have entered is invalid");
}
} while (successful == false);
System.out.println("\nThe book " + Books.get(i).getTitle() + " is now on loan");
Books.get(i).setOnLoan(true);
Books.get(i).setNumOfLoan(Books.get(i).getNumOfLoans() + 1);
successful = true;
}
}
if (successful == false) {
System.out.println("This book does not exist ");
}
} while (successful == false);
}
public void returnBook() {
boolean successful = false;
Scanner input = new Scanner(System.in);
try {
do {
System.out.println(
"Please enter the book ID of the book you wish to return (Press 9 to exit to the main menu");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
if (Books.get(i).getOnLoan() == true) {
System.out.println("How long did you loan the book for?");
int durationOnLoan = input.nextInt();
if (durationOnLoan > Books.get(i).getDurationOnLoan()) {
durationOnLoan -= Books.get(i).getDurationOnLoan();
if (durationOnLoan < 3) {
System.out.println("You are " + durationOnLoan
+ " day(s) late in returning the book" + "\nYou have been fined £3."
+ "\n The book " + Books.get(i).getTitle() + " is now returned");
successful = true;
} else {
System.out.println("You are " + durationOnLoan + " days late in returning the book"
+ "\nYou have been fined £6.");
System.out
.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else {
Books.get(i).setOnLoan(false);
System.out.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else if (Books.get(i).getOnLoan() == false) {
System.out.println("\nThis book was not on loan");
System.out.println("\nYou have been returned to the main menu");
successful = true;
}
} else if (successful == false) {
System.out.println("This book does not exist");
}
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
}
MemberList class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class MemberList {
private ArrayList<Member> Members;
public MemberList(ArrayList<Member> Members) {
this.Members = Members;
}
public void addNewMember() {
Scanner input = new Scanner(System.in);
boolean successful = false;
int memberID = 0;
String memberName = "";
int memberAge;
String address;
int contactNumber;
System.out.println("\t\tCreate new member");
do {
System.out.println("Please enter your full name:");
memberName = input.nextLine();
if (!input.hasNextInt()) {
successful =true;
} else {
input.next();
System.out.println("Your name cannot contain a number");
}
} while (successful == false);
do {
try{
input.nextLine();
System.out.println("please create your unique 2 digit member ID");
memberID = input.nextInt();
for (int i = 0; i < Members.size(); i++) {
if (Members.get(i).getMemberID() == memberID) {
System.out.println("This member ID is already in use");
successful =false;
}
if (memberID <= 9 || memberID > 99) {
System.out.println("PLease enter 2 digit ID (between 10 and 100) ");
}
if(Members.get(i).getMemberID() != memberID && memberID > 9 && memberID < 100) {
successful = true;
}
}
} catch(NumberFormatException e)
{
System.out.println("Invalid input");
}
} while (successful == false);
do{
System.out.println("Please enter your age: ");
memberAge = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful =true;}
}while(successful == false);
do{
System.out.println("Please enter your adress");
address = input.nextLine();
successful =true;
}while(successful==false);
do {
System.out.println("please enter your contact number:");
contactNumber = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful = true;}
}while(successful==false);
Member newMember = new Member(memberID,memberName,memberAge,0,0,address,contactNumber);
Members.add(newMember);
}
public void displayMembers()
{
System.out.println("\t\t\t-----The current members in the library are-----");
for (int i = 0; i < Members.size(); i++)
{
System.out.println("\n" + "\t\t" + Members.get(i).getMemberName() + "\t\t\t" + "\n\t\tMember ID: "
+ Members.get(i).getMemberID() + "\n\t\tAge: " + Members.get(i).getMemberAge() + "\t\t\t\t\t\t"
+ "\n\t\tAddress: " + Members.get(i).getAddress() + "\t\t\t\t\t"
+ "\n\t\tContact number: " + Members.get(i).getContactNumber()
+ "\t\t" + "\n\t\tNumber of books loaned: " + Members.get(i).getNumOfBooksLoaned()
+ "\t\t" + "\n\t\tNumber of Late Fees: " + Members.get(i).getPenalties());
}
}
}
LibraryTester Class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class LibraryTester {
public static void main(String[] args) {
String title = "";
String author = "";
int bookID = 0;
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberlist = new MemberList(List){};
Member John = new Member(10,"John McLaughlin", 44, 5, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(John);
Member Cathy = new Member(11,"Cathy McLaughlin", 43, 7, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(Cathy);
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, );
Book HarryPotter = new Book(100, "Harry Potter and The Philosopher's Stone", "J.K Rowling", false, 5, 0);
list.add(HarryPotter);
Book theOriginOfSpecies = new Book(101, "The Origin Of Species", "Charles Darwin", false, 3, 0);
list.add(theOriginOfSpecies);
Book LOTR = new Book(102, "The Lord of The Rings: The Fellowship of The Ring", "J.R.R Tolkien", false,7,0);
list.add(LOTR);
Scanner input = new Scanner(System.in);
boolean B = true;
while (B == true) {
System.out.println(" \nMenu ");
System.out.println("Press 1 to add a book");
System.out.println("Press 2 to edit a books details");
System.out.println("Press 3 to delete a book");
System.out.println("Press 4 to take out a book on loan");
System.out.println("Press 5 to return a book");
System.out.println("Press 6 to see all the books in the library");
System.out.println("Press 7 to become a member");
System.out.println("Press 8 to see the members of the library");
System.out.println("Press 9 to exit the program");
switch (input.nextInt()) {
case 1:
library.addBook();
B = true;
break;
case 2:
library.displayBooks();
library.editBook();
B = true;
break;
case 3:
library.displayBooks();
library.removeBook();
B = true;
break;
case 4:
library.displayBooks();
library.loanBook();
B = true;
break;
case 5:
library.displayBooks();
library.returnBook();
break;
case 6:
library.displayBooks();
B = true;
break;
case 7:
memberlist.addNewMember();
break;
case 8:
memberlist.displayMembers();
B = true;
break;
case 9:
System.out.println("Exiting .....");
System.exit(1);
break;
default:
System.out.println("You have not entered a valid option");
break;
}
}
}
}
The error occurs at the code
Library library = new Library(list , ) {
};
I'm not sure what to put after the comma, I've tried everything and nothing seems to work. Any thoughts?
EDIT
Edited Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private ArrayList<Member> members;;
public Library(ArrayList<Book> Books, ArrayList<Member> member) {
this.Books = Books;
this.members=member;
};
Edited LibraryTester class
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberList = new MemberList(List){};
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, memberList ){};
The error says "The constructor Library(ArrayList, MemberList) is undefined" But i've changed the relevant things in the library class?
You need to pass an array of Book and, a Member :
public Library(ArrayList<Book> Books, Member member)
Since Library class is having the constructor
public Library(ArrayList<Book> Books, Member member){};
you can't just create a object as you are doing in LibraryTester class.
you need to pass the second parameter i.e, object of Member class.
Here you miss a member:
Library library = new Library(list, );
Try to add it like this creating an object of Member:
Member memberlist = new Member(10,"Joe Blogs", 44, 5, 0,"Bleaker Street",123456789);
Library library = new Library(list, memberlist);
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()
I've been working on a java project for me class, and I am almost done. the program is a hangman game, where the user inputs a letter, and the program continues depending whether the letter is in the word or not. The issue I am having is that I cannot figure out how to make it so when the user enters more than one letter, a number or a symbol, the program prints out a statement that says "Invalid input, try again" and has the user input something again, instead of showing it to be a missed try or the " letter" not being in the word. Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println();
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
System.out.println("Choose a letter: ");
letter = game.in.next();
if(letter.length() == 1)
{
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}else
{
System.out.println("Invalid input, try again");
}
You can use a regular expression to check the input.
if (!letter.matches("[a-zA-Z]{1}")) {
System.out.println("Invalid Input") {
else {
<your other code>
}
Try this,
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
String input = in.readLine();
if(input.length() == 1){
game.puzzles[count] = ; //get line of data
count++; //Increment CWID counter
}
else{
System.out.println("INVALID INPUT");
}
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println();
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
You can use String.length() for checking the length of the input, e.g. in your case
if(letter.length() != 1) {
// do something to handle error
}
String.length() can be used to determine, if the input has one letter. To check if the read String is a letter you can use Character.isLetter(char):
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
String line = null;
while (in.ready()) { //while there is another line in the input file
line = in.readLine();
if (line.length() == 1 && Character.isLetter(line.charAt(0)) {
game.puzzles[count] = line; //get line of data
count++; //Increment CWID counter
} else {
// handle the else-case
}
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
This is my code for STUDENT RECORD SYSTEM. I think it is on its 80% of completion. The problem here is that when i have many students and i update a specific student(subj & grade) the updated element is not being saved on that specific student. And when I display all of the results the updated values are given to other student. Please help me out with this issue. And btw this code has 2 classes Student and StudentGrade. I hope you'll help me fix this. Thanks in advance. :) and Advance Happy New Year!
public class Student
{
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student()
{
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Student(String IDNum, String fName, String mName, String lName, String deg,int level )
{
this.IDNumber=IDNum;
this.firstName=fName;
this.middleName=mName;
this.lastName=lName;
this.degree=deg;
this.yearLevel=level;
}
public void setIdNumber(String IDNumber)
{
this.IDNumber = IDNumber;
}
public String getIdNumber()
{
return IDNumber;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName()
{
return firstName;
}
public void setMiddleName(String middleName)
{
this.middleName=middleName;
}
public String getMiddleName()
{
return middleName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public String getLastName()
{
return lastName;
}
public void setDegree(String degree)
{
this.degree=degree;
}
public String getDegree()
{
return degree;
}
public void setYearLevel(int yearLevel)
{
this.yearLevel=yearLevel;
}
public int getYearLevel()
{
return yearLevel;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class test2 {
static ArrayList<Student> studentList = new ArrayList<Student>();
static ArrayList<StudentGrade> studentLists = new ArrayList<StudentGrade>();
public static void main(String[] args)
{
menu();
}
public static void menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("*********STUDENT RECORD SYSTEM*********\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1)
{
add();
}
else if (choice == 2)
{
displayAll();
}
else if (choice == 3)
{
displaySpecific();
}
else if (choice == 4)
{
update();
}
else if (choice == 5)
{
average();
}
else if( choice == 6)
{
System.exit(0);
}
else
menu();
}
public static void add()
{
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("NUMBER OF STUDENTS YOU WANT TO INPUT: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("**********STUDENT INFORMATION**********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
/* // SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
} */
menu();
}
public static void displayAll() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY lageeeee!!! \nPLEASE INPUT FIRST\n\n");
in.nextLine();
}
else
{
if(studentLists.size() == 0){
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()/* +"\nGrade: "
+ studentLists.get(i).getGrade() */+"\n\n");
}
in.nextLine();
}
else{
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++)
{
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()+"\n\n");
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void displaySpecific() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY oe!!! KALAGOT!\nPLEASE INPUT FIRST\n");
in.nextLine();
}
else
{
String id = new String();
/* in.nextLine(); */
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
if(studentLists.size()==0)
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + /* "\nGrade: "
+ studentLists.get(j).getGrade()+ */"\n\n");
System.out.println();
in.nextLine();
}
/* else
{
System.out.print("STUDENT DOES NOT EXIST IN THIS WORLD!");
in.nextLine();
} */
}
}
else
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() +"\n\n");
System.out.println();
}
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();
int total;
for(int x=0;x<studentList.size();x++)
{
if(idnum.equals(studentList.get(x).getIdNumber()))
{
System.out.println("NUMBER OF SUJECTS YOU WANT TO INPUT: ");
total = in.nextInt();
do
{
StudentGrade[] update = new StudentGrade[total];
for(int y = 0;y<update.length;y++)
{
update[y] = new StudentGrade();
in.nextLine();
System.out.print("ENTER SUBJECT: ");
update[y].setSubject(in.nextLine());
System.out.print("ENTER GRADE: ");
update[y].setGrade(in.nextDouble());
studentLists.add(update[y]);
}
System.out.print("Enter another subject and grade? [y/n]");
String ans = in.next();
answer = ans.charAt(0);
}while(answer == 'y');
}
menu();
}
}
public static void average()
{
Scanner in = new Scanner(System.in);
double sum=0;
double average=0;
String ID = new String();
System.out.print("ENTER ID NUMBER: ");
ID = in.nextLine();
for(int xx=0;xx<studentList.size();xx++)
{
if(ID.equals(studentList.get(xx).getIdNumber()))
{
for(int ind=0;ind<studentLists.size();ind++)
{
sum += studentLists.get(ind).getGrade();
average=sum/studentLists.size();
}
System.out.print("ID NUMBER:"+studentList.get(xx).getIdNumber()+"\nNAME: "
+studentList.get(xx).getFirstName()+" "
+studentList.get(xx).getMiddleName()+" "
+studentList.get(xx).getLastName());
System.out.print("\nAVERAGE: "+average+"\n");
in.nextLine();
}
}
menu();
}
}
First of all I would change studentList to Map to be able to get the student by id directly and not to search for the matching student every time.
The access to the collections of all students is then like this:
for(Map.Entry<String, Student> entry : studentList.entrySet()){
String id = entry.getKey();
Student student = entry.getValue();
// ...
}
A a second step you should check your update method. I see, that you a searching for the student, but you don't updating this object. You are adding a new one at the end of the loop with studentList.add().
You have store the matching Student into the local variable and just modify this without modifying the collection of students.
You have two reader statements in update function
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();//1
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();//2
I think there should be only one as your just reading the id number and as #Vlad said your adding a new element to the array list rather than modifying the existing data .
also for your code you can use
arrayList.set(index i,String replaceElement);// this will help you replace the value at a particular index
it is better to use HashMap instead of array list so when you put an existing element into
a map the value is overwritten.
static Map <String,Student> studentList = new HashMap<String,Student>();
static Map<String, List<StudentGrade>> studentLists = new HashMap<String, List<StudentGrade>>();
Here the key will be the student idNumber
Here is my issue. I am trying to build an array of HomeLoan in my main, and then from my main, call the printHLoans(hLoans) from my main, so that I can list them and then add more functionality. Unfortunately, it is saying that hLoan cannot be resolved as a variable.
Main Class
import java.util.InputMismatchException;
import java.util.Scanner;
public class LoanTest
{
static int term;
static int loanID=0;
static int hHowMany=0;
static int cHowMany=0;
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter name: ");
String name = input.nextLine();
System.out.print("Enter Customer ID: ");
int custID=0;
do
{
try
{
custID = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Customer IDs are numbers only");
input.next();
}
}while (custID<1);
boolean aa=true;
while(aa)
{
System.out.println("Do you have a (h)ome loan or a (c)ar loan?");
String a = input.next();
switch (a)
{
case "h": System.out.println("You selected Home Loan");
System.out.println("How many Home Loans would you like to enter?");
hHowMany = input.nextInt();
HomeLoan[] hLoans = new HomeLoan[hHowMany];
int z=0;
while (hHowMany>z)
{
hLoans[z] = new HomeLoan(name, custID);
z++;
}
break;
case "c": System.out.println("You selected Car Loan");
System.out.println("How many Car Loans would you like to enter?");
cHowMany = input.nextInt();
int x=0;
CarLoan[] carLoans = new CarLoan[cHowMany];
while (x<cHowMany)
{
System.out.print("Enter Loan ID: ");
loanID=0;
do
{
try
{
loanID=input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Loan IDs are number only");
input.next();
}
}while (loanID<1);
boolean b=true;
while(b)
{
System.out.print("Enter term: ");
term=input.nextInt();
boolean t = CarLoan.termCorrect(term);
if(t){System.out.println("Error: Maximum of 6 year");}
else {b=false; System.out.println("You entered: " + term + " years");}
}
carLoans[x] = new CarLoan(name, custID, loanID, term);
x++;
}
break;
default: System.out.println("Invalid input");
break;
}
System.out.print("Would you like to enter another loan?");
System.out.print("(y)es or (n)o:");
String m = input.next();
System.out.println("");
switch (m)
{
case "y": break;
case "n": aa=false;
break;
default: System.out.print("Invalid entry");
}
}
printHLoans(hLoans);
System.out.println("Thank you for using Loan Software");
System.out.println("Have a nice day");
}
public static void printHLoans(HomeLoan hLoans[])
{
System.out.println("Here are the loans you entered . . .");
int zzz=0;
while (zzz<hHowMany)
{
term = hLoans[zzz].getTerm();
loanID=hLoans[zzz].getLoanID();
String address=hLoans[zzz].getAddress();
double loanAmount = hLoans[zzz].getLoanAmount();
System.out.print(zzz + ": ");
System.out.print(hLoans[zzz].toString(loanID, address, term, loanAmount));
System.out.println();
zzz++;
}
}
}
HomeLoan Class
import java.util.InputMismatchException;
import java.util.Scanner;
public class HomeLoan extends Loan
{
private String address;
int howMany;
private double loanAmount;
private int term;
private int loanID;
public HomeLoan()
{
}
public HomeLoan(String name, int custID)
{
//super(name, custID, loanID);
Scanner input = new Scanner (System.in);
System.out.print("Enter Loan ID: ");
loanID=0;
do
{
try
{
loanID=input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Loan IDs are number only");
input.next();
}
}while (loanID<1);
boolean l=true;
while (l)
{
System.out.print("Enter term: ");
term=input.nextInt();
boolean s = HomeLoan.termCorrect(term);
if (s){System.out.println("Error: Maximum of 30 years");}
else {l=false;}
}
//System.out.println();
input.nextLine();
System.out.print("Enter your address: ");
address=input.nextLine();
System.out.print("Enter loan ammount: ");
loanAmount = input.nextDouble();
double annualInterest = 10.99;
double monthlyPayment = amortization(loanAmount, annualInterest, term);
double newBalance=payment(monthlyPayment, loanAmount);
//System.out.println("Payment: " + monthlyPayment);
//System.out.println("New balance after payment: " + newBalance);
}
public static boolean termCorrect(int term)
{
boolean a;
if (term>30) {a=true; return a;}
else {a=false; return a;}
}
public String toString(String name, int custID, int loanID)
{
String display = "Name: " + name + " Customer ID: " + custID + " Address: "+ address+ " Loan ID: " + loanID + " Loan Amount: $" + loanAmount
+ " Current Balance: $";
return display;
}
public String getAddress()
{
return address;
}
public double getLoanAmount()
{
return loanAmount;
}
public int getTerm()
{
return term;
}
public int getLoanID()
{
return loanID;
}
public String toString(int loanID, String address, int term, double loanAmmount)
{
String displa = "ID: " + loanID + " Address:" + address + " Term: " + term + " Loan Ammount: " + loanAmmount;
return displa;
}
private void equals()
{
}
public void printHLoans(HomeLoan hLoans[], int xxx)
{
}
}
How do I make this work?
That's because you've declared the HomeLoan[] hLoans = new HomeLoan[hHowMany]; within the while loop and are trying to access it after that. That's why once the while loop is over, the hLoans goes out of scope. In your case, its more specifically within the case "h" of the switch, which further narrows down the scope of hLoans to just within it.
To be able to access it outside the while, you need to declare it at a scope higher than the while. Do something like this.
HomeLoan[] hLoans; // Before while
while(aa) {
...
switch..
case "h": hLoans = new HomeLoan[hHowMany];
}
printHLoans(hLoans);