My array is over writing the previous entry [duplicate] - java

This question already has an answer here:
my input array keeps over writing itself
(1 answer)
Closed 9 years ago.
My current problem contains two arrays, everytime i enter a book, the book ID goes up one. This seems to work ok. But my current issue is that when i put in a new book, it completely over writes the last entry. eg John smith BookID1 could be my first entry. But then i add Penny Jones BookID2 , the john smith disappears.
To try resolve this i have added static int location = 0 in the class and also changed this is the array entry but it still not working.
import java.util.Scanner;
public class library {
static Scanner keyboard = new Scanner(System.in);
static boolean run = true;
static int location = 0;
public static fiction [] fictionArray = new fiction[2];
public static nonfiction [] nonfictionArray = new nonfiction[2];
public static void main (String[] args){ // main class method
while (run){ // this while statement allows the menu to come up again
int answer = 0; // answer initialized to Zero
boolean isNumber;
do{ // start of validation
System.out.println("1. Add book"); // Menu selections
System.out.println("2. Display the books available for loan");
System.out.println("3. Display the books currently on loan");
System.out.println("4. Make a book loan");
System.out.println("5. Return book ");
System.out.println("6 Write book details to file");
if (keyboard.hasNextInt()){ // I would like to set values to =>1 <=6
answer = keyboard.nextInt(); // this is more validation for the input for menu selection
isNumber = true;
} else { // else if number not entered, it will prompt for the correct input
System.out.print(" You must enter a number from the menu to continue. \n");
isNumber = false;
keyboard.next(); // clears keyboard
}
}
while (!(isNumber)); // while to continue program after the do has completed
switch (answer){ // switch statement - uses answer from the keyboard to select a case
case 1:
addBook(); // adds book
break;
case 2:
for (int i=0; i<2; i++){
if (fictionArray[i] != null){
System.out.println(fictionArray[i]);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray[i]);}}
break;
case 3:
for (int i=0; i<2; i++){
if(fictionArray[i].getTitle() != "Onloan"){
System.out.println(fictionArray[i]);}
if(nonfictionArray[i].getTitle() != "Onloan"){
System.out.println(nonfictionArray[i]);}}break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
}
static void addBook(){
loanbook [] loanArray = new loanbook[2];
String title,author;
int choice;
boolean onloan = false;
for(int x = 0; x < loanArray.length; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
for(int count = 0; count < fictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
fictionArray[location] = new fiction(title, author, onloan);
System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array
count++; }}
else if (choice == 2) {
for(int count = 0; count < nonfictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
nonfictionArray[location] = new nonfiction(title, author, onloan);
System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array
count++;}}
else{ int noBooks = loanArray.length;
for (int i=0; i<noBooks; i++){
System.out.print(loanArray[x]);
}}}} // addbook
} // Library end
Superclass
public class loanbook {
private String title,author;
static int bookID = 0;
private boolean onloan;
public loanbook(String pTitle,String pAuthor,boolean ponloan){
title = pTitle;
author = pAuthor;
onloan = ponloan;
bookID++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return " Onloan = "+onloan +"\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook

you need to increment your location after you set something to it.

Related

How can i get back to main menu and entering any panel after exiting from admin panel?

I'm building a university management system where admin can log in, add student, department, 2ndly there is a faculty panel and lastly, there is a student panel where they can set course. But I've been facing some problems after adding a new student through the admin panel. The problem is if want to exit from the admin panel the whole program close. Is there any solution that if I exit from admin panel I should get back to main menu where i can enter in any panel again. there is one more problem if i tried to remove a student from registered it shows not found. Can anyone help me through this problem?
Here is my code MainActivity.java
import java.util.Scanner;
import mainpanel.*;
import interfacepart.*;
//import transactionpart.*;
public class MainActivity{
public static void main(String args[]){
boolean flag = true;
Student[] student1 = new Student[2000];
Scanner sc = new Scanner(System.in);
Admin a = new Admin("Admin", "1234");
System.out.println("**********Welcome to University Management*******");
//do {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Adming Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int choose = sc.nextInt();
sc.nextLine();
if(choose == 1){
Scanner ac = new Scanner(System.in);
System.out.println("**********Welcome to Admin panel*******");
System.out.println("Please enter the userName: ");
String user = sc.nextLine();
System.out.println("Please enter the password: ");
String password = sc.nextLine();
if("Admin".equals(user) && "1234".equals(password)){
do{
System.out.println("Login successful");
System.out.println ( "**** 1. add students and department *****");
System.out.println ( "**** 2. remove students *****");
System.out.println ( "**** 3. student Information *****");
//System.out.println ( "**** n 5, print student *****");
System.out.println ( "**** 4, exit the system *****");
int sel = sc.nextInt();
switch (sel){
case 1:
System.out.println("Enter the number of student you want to add: ");
int num = sc.nextInt();
sc.nextLine();
for (int i = 0; i<num; i++) {
if (student1[i] == null) {
System.out.println("Enter the deptname: ");
String depntName = sc.nextLine();
System.out.println("Enter the deptId: ");
String depntId = sc.nextLine();
System.out.println("Enter the totalCredit: ");
int totalCredit = sc.nextInt();
sc.nextLine();
Department cs = new Department(depntName, depntId, totalCredit);
Scanner mc = new Scanner(System.in);
System.out.println("Enter the StudentName: ");
String StudentName = mc.nextLine();
System.out.println("Enter the StudentId: ");
String StudentId = mc.nextLine();
System.out.println("Enter the StudentAge: ");
String StudentAge = mc.nextLine();
System.out.println("Enter the email: ");
String email = mc.nextLine();
System.out.println("Enter the bloodGroup: ");
String bloodGroup = mc.nextLine();
System.out.println("Enter the phoneNumber: ");
String phoneNumber = mc.nextLine();
System.out.println("Enter the Address: ");
String Address = mc.nextLine();
mc.nextLine();
Student s1 = new Student(StudentName,StudentId,StudentAge,email,bloodGroup,phoneNumber,Address);
student1[i] = s1;
a.addNewRegister(student1[i]);
a.addNewDepartment(cs);
student1[i].SetAdmin(a);
student1[i].SetDeparment(cs);
cs.addNewRegister(student1[i]);
//break;
}
else{
System.out.println ( "Number of students in full");
break;
}
}
break;
case 2:
boolean isStudentRegistered = false;
System.out.println("Please Enter the Id you want to remove: ");
Scanner newCheck = new Scanner(System.in);
String stdId = newCheck.nextLine();
for(Student total : student1){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}if(!isStudentRegistered){
System.out.println("No student found");
}
break;
case 3:
for(int i=0; i<1; i++){
a.showRegisteredInfo();
break;
}
break;
case 4:
System.exit(0);
//flag = false;
//break;
//continue;
break;
default:
break;
}
}while (true);
} else {
//flag = true;
System.out.println ( "Login failed please re-enter:");
}
}
else if(choose == 3){
Scanner std = new Scanner(System.in);
System.out.println ( "Welcome to Student Panel*******");
System.out.println("Please enter the StudentId: ");
String userId = std.nextLine();
System.out.println("Please enter the password: ");
String password = std.nextLine();
do{
for(Student total : student1){
if(total != null){
if(total.getId() == userId){
System.out.println("*********Welcome to university Portal***");
//isStudentRegistered = true;
total.showInfo();
}else{
System.out.println("You are not registered yet");
}
}
}
}while(true);
}
else{
System.out.println ( "Login failed please re-enter:");
}
/*} while (true);
}*/
}
}
Admin.java
package mainpanel;
public class Admin{
protected String userName;
protected String passWord;
Student[] addNewStudent;
Department[] department;
Courses[] courses;
int totalRegisterCount;
int totalDepartmentCount;
int totalCourseCount;
public Admin(){
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public Admin(String userName, String passWord){
this.userName = userName;
this.passWord = passWord;
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public void SetUserName(String userName){
this.userName = userName;
}
public String GetUserName(){
return userName;
}
public void SetpassWord(String passWord){
this.userName = userName;
}
public String GetPassword(){
return passWord;
}
public void addNewRegister(Student NewStudent){
addNewStudent[totalRegisterCount++] = NewStudent;
}
//public void removeNewStudent(Student removeNewStudent){
//}
public void addNewDepartment(Department dept){
department[totalDepartmentCount++] = dept;
}
public void addNewCourse(Courses crs){
courses[totalCourseCount++] = crs;
}
public void showDepartmentInfo(){
for(int i=0; i<totalDepartmentCount; i++){
department[i].showInfo();
}
}
public void showRegisteredInfo(){
for(int i=0; i<totalRegisterCount; i++){
addNewStudent[i].showInfo();
//addNewStudent[i].AllCourseInfo();
}
}
public void searchStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total.showInfo();
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
/*
public void removeStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
*/
}
//courses[num].showInfo();
/*public void showCourseInfo(){
for(int i=0; i<totalCourseCount; i++){
courses[i].showInfo();
}
}
*/
Approach 1 - Not recommended
You can either have a loop surrounding the core functionality of your application and break out of any internal loops to go back to the beginning of the core loop.
Approach 2 - Recommended
You could refrain from using a core loop and refactor your code such that each menu interaction is a separate function.
Each function would present the user with a specific menu and depending on the user's input another function would be called for the next menu. Generally speaking, you would not require any loops to keep the application running.
This would reduce the complexity and confusion of your code and make it much easier to expand the application with new features without needing to concern yourself with where to place code within the loop.
I recommend reading up on SOLID design principles to get an idea of how best to structure code. Here is an example article. This answer and example code is not meant to be a full representation of SOLID design and I would recommend that you strongly consider using interfaces and separate classes for each distinct part of the system and not having all the code in the MainActivity class.
An example of a function-based approach would be as follows.
I mainly focussed on the Main Menu and Admin Menu. The principle can be applied across the entire application.
Scanner sc = new Scanner(System.in);
private void displayMainMenu() {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Admin Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int input = sc.nextInt();
sc.nextLine();
switch (input) {
case 1:
displayAdminLoginMenu();
break;
case 2:
displayFacultyLoginMenu();
break;
case 3:
displayStudentLoginMenu();
break;
default:
// Display the main menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayMainMenu();
break;
}
}
private void displayAdminLoginMenu() {
// Perform login operation here
// After successful login display admin options menu
displayAdminOptionsMenu();
}
private void displayFacultyLoginMenu() {
}
private void displayStudentLoginMenu() {
}
private void displayAdminOptionsMenu() {
System.out.println("**** 1. add students and department *****");
System.out.println("**** 2. remove students *****");
System.out.println("**** 3. student Information *****");
System.out.println("**** 4, return to main menu *****");
System.out.println("**** 5, exit the system *****");
int input = sc.nextInt();
switch (input) {
case 1:
// Call function for option 1.
break;
case 2:
// Call function for option 2.
break;
case 3:
// Call function for option 3.
break;
case 4:
displayMainMenu();
break;
case 5:
exitApplication();
break;
default:
// Display the admin menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayAdminOptionsMenu();
break;
}
}
private void exitApplication() {
System.exit(0);
}
These are not necessarily the only options available, but they are what I could think of at the moment.

Reading user input as a String and comparing it to any ArrayList for validation

I'm working on a program for a plant nursery that has two classes; PlantNursery and Plant. The user gets promoted 4 questions. 1) Add a plant, 2) List all the plants, 3) Edit a plant, and 4) Quit. I got 1, 2, and 4 working fine. My problem lies within option 3. I display the current list of plants in the array and ask the user to pick one by it's common name. Then I store the String and compare it with an if statement. The if statement is not working as expected. I get the error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at plantnursery.PlantNursery.main(PlantNursery.java:92)
C:\Users\diggz\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 52 seconds)
Plant class:
package plantnursery;
public class Plant
{
//Variables
private String commonName, scientificName;
private double maxHeight, price;
private boolean fragile;
//Constructor
public Plant(String commonName, String scientificName, double maxHeight,
double price, boolean fragile)
{
this.maxHeight = maxHeight;
this.price = price;
this.commonName = commonName;
this.scientificName = scientificName;
this.fragile = fragile;
}
public double getMaxHeight()
{
return maxHeight;
}
public void setMaxHeight(double maxHeight)
{
this.maxHeight = maxHeight;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
public String getCommonName()
{
return commonName;
}
public void setCommonName(String commonName)
{
this.commonName = commonName;
}
public String getScientificName()
{
return scientificName;
}
public void setScientificName(String scientificName)
{
this.scientificName = scientificName;
}
public boolean isFragile()
{
return fragile;
}
public void setFragile(boolean fragile)
{
this.fragile = fragile;
}
#Override
public String toString() {
return "Plant{" + "commonName= " + commonName + ", scientificName= "
+ scientificName + ", maxHeight= " + maxHeight + ", price= "
+ price + ", fragile= " + fragile + '}';
}
}
PlantNursery class:
package plantnursery;
import java.util.ArrayList;
import java.util.Scanner;
public class PlantNursery
{
public static void main(String[] args)
{
//Variables to hold user input.
double userHeight, userPrice;
String userComName, userSciName, blankLine;
boolean userFragile;
int ans, choice;
//Reference variable to an object.
Plant p;
//Scanner for user input.
Scanner scan = new Scanner(System.in);
//ArrayList to store all the plants in.
ArrayList<Plant> plantList = new ArrayList<>();
//While loop asking the user to create new plants and store them
//in the the ArrayList. Edit any of the plants already in the ArrayList
//or quit the program.
while(true)
{
//Ask the user what they want to do.
System.out.println("What do you want to do?\n1. Add a plant. "
+ "\n2. List all plants.\n3. Edit a plant. \n4. Quit.");
//Store answer
ans = scan.nextInt();
//Choice 1. Add a new plant into the ArrayList.
if(ans == 1)
{
//Get rid of buffer overflow from int ans.
blankLine = scan.nextLine();
//Ask the user for input for a new plant object.
System.out.println("Please enter the common name of the plant:");
userComName = scan.nextLine();
System.out.println("Please enter the scienitific name of the plant: ");
userSciName = scan.nextLine();
System.out.println("Please enter the maximum height (in feet) of the plant: ");
userHeight = scan.nextDouble();
System.out.println("Please enter the price of the plant: ");
userPrice = scan.nextDouble();
System.out.println("Please enter if the plant is fragile (true or false): ");
userFragile = scan.nextBoolean();
//Create the new plant object.
p = new Plant(userComName, userSciName, userHeight, userPrice,
userFragile);
//Add the plant object to the ArrayList.
plantList.add(p);
}
//Choice 2. Display all plant(s) in the ArrayList.
if(ans == 2)
{
//List all the current plants in the ArrayList.
for(Plant curList : plantList)
{
System.out.println(curList);
}
}
//Choice 3. Edit information on plant(s) in ArrayList.
if(ans == 3)
{
//Allows the user to edit until they wish to quit.
while(true)
{
//Counter for ArrayList
int i;
//String to hold which plant the user wishes to edit.
String userAns;
//Ask the user which plant they wish to edit.
System.out.println("Which plant to wish to edit (choose the common name)?");
//Display the plant(s).
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
//Get the user input and compare it to the Common Name
blankLine = scan.nextLine();
userAns = scan.nextLine();
if(userAns.equalsIgnoreCase(plantList.get(i).getCommonName())) //PROBLEM CODE
{
//Ask what the user wishes to edit.
System.out.println("What do you wish to edit?\n1. Common Name."
+ "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
+ "\n5. Is it fragile (true or false)?\n6. Quit.");
//Get user choice.
choice = scan.nextInt();
//Choice 1
if(choice == 1)
{
System.out.println("What is the new Common Name? ");
String newComName = scan.nextLine();
plantList.get(i).setCommonName(newComName);
}
//Choice 2
if(choice == 2)
{
System.out.println("What is the new Scientific Name? ");
String newSciName = scan.nextLine();
plantList.get(i).setScientificName(newSciName);
}
//Choice 3
if(choice == 3)
{
System.out.println("What is the new Maximum Height? ");
double newHeight = scan.nextDouble();
plantList.get(i).setMaxHeight(newHeight);
}
//Choice 4
if(choice == 4)
{
System.out.println("What is the new Price?");
double newPrice = scan.nextDouble();
plantList.get(i).setPrice(newPrice);
}
//Choice 5
if(choice == 5)
{
System.out.println("Is the plant Fragile (true or false)? ");
boolean newFragile = scan.nextBoolean();
plantList.get(i).setFragile(newFragile);
}
//Choice 6
if(choice == 6)
{
break;
}
}
}
}
//Choice 4. End program.
if(ans == 4)
{
break;
}
}
}
}
Okay so I changed the third choice into a switch statement. Now the problem I have is I can only do one edit. After that first edit when I try to pick another plant or the same one to edit it doesn't read it and keeps asking me the same question.
Code:
//Choice 3. Edit information on plant(s) in ArrayList.
if(ans == 3)
{
OUTER:
while (true) {
int i;
String userAns;
System.out.println("Which plant to wish to edit (choose the common name)?");
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
blankLine = scan.nextLine();
userAns = scan.nextLine();
if (userAns.equalsIgnoreCase(plantList.get(i-1).getCommonName())) {
System.out.println("What do you wish to edit?\n1. Common Name."
+ "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
+ "\n5. Is it fragile (true or false)?\n6. Quit.");
choice = scan.nextInt();
//Choices
switch (choice)
{
//Choice 1
case 1:
System.out.println("What is the new Common Name? ");
blankLine = scan.nextLine();
String newComName = scan.nextLine();
plantList.get(i-1).setCommonName(newComName);
break;
//Choice 2
case 2:
System.out.println("What is the new Scientific Name? ");
blankLine = scan.nextLine();
String newSciName = scan.nextLine();
plantList.get(i-1).setScientificName(newSciName);
break;
//Choice 3
case 3:
System.out.println("What is the new Maximum Height? ");
double newHeight = scan.nextDouble();
plantList.get(i-1).setMaxHeight(newHeight);
break;
//Choice 4
case 4:
System.out.println("What is the new Price?");
double newPrice = scan.nextDouble();
plantList.get(i-1).setPrice(newPrice);
break;
//Choice 5
case 5:
System.out.println("Is the plant Fragile (true or false)? ");
boolean newFragile = scan.nextBoolean();
plantList.get(i-1).setFragile(newFragile);
break;
//Choice 6
case 6:
break OUTER;
default:
break;
}
}
}
}
ArrayList index starts with 0, so you have to do plantList.get(i-1).setPrice(newPrice);
You are starting index 0. So if you type 2 it means you trying to access 3 values
array[0], array[1], array[2].
Change for(i = 0; i < plantList.size(); i++)
to for(i = 1; i < plantList.size(); i++)
if you do not wish to change your for loop then you need to change plantList.get(i) to plantList.get(i-1) to make sure it is within the range
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
You've incremented i to plantList.size(). When you access the list with plantList.get(i).getCommonName(), i is already larger that the largest index.
You probably shouldn't use a variable defined outside the loop as the counter in the loop.
Have you considered a Map instead of seaching through the list?

Where do i write if item is not found, and display an appropriate message?

public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
}
}
You should refactor to separate the loop for finding/not finding the ball (or not), and do whatever you need to do with the ball (or error if not found) OUTSIDE the loop. This helps with readability because more of your lines are less indented, and it helps communicate your intent because most of your code in the loop is only going to be executed once anyway.
int ballIndex = -1;
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
ballIndex = nameBallArray[i];
break;
}
}
if (ballIndex >= 0) {
// found - do everything using ballIndex
} else {
// not found - display error
}
Set a flag variable to 0 before loop. Inside if set it 1. After the loop check if it is still zero. then print appropriate message that no item found.
Boolean flag = false; // before loop
flag = true; //inside if
// After loop
if(!flag)
System.out.println("Not Found");
Try this:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
return;
}
}
System.out.println("ball not found");
}
You could create a boolean and set it to true in your if statement that means it's been found. You could check the boolean after loop to see if it's true or false then display error message if true.
Example:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
boolean found = false; //boolean for if it's found or not
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
found = true; //set boolean if found
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
break; //break out of loop if item found
}
}
//check if boolean is false then print error message
if (!found)
{
System.out.println("There was a problem finding your item.");
}
I also added a break at end of if statement to break out of the loop if the item was found(no point in continuing on if the item was already found).

Trying to sort objects in an arraylist by a property but the objects don't always sort properly

I have four classes but they're just templates so I'll only post my main class (I have overridden toString for each). The sort method is at the bottom. Everything else is fine (more or less) with my code, but when I create the objects in the array and then go to sort them (by a string value called uid) sometimes one or two of them will be out of order. How can I fix this?
Here's the code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
enum ClassStanding{FRESHMAN,SOPHOMORE,JUNIOR,SENIOR,UNKNOWN,MASTERS_STUDIES,PHD_STUDIES};
enum Major{CS,CEG,EE,ISE,BME,ME,MET,UNKNOWN};
enum StudentType{UNDERGRADUATE,GRADUATE,UNDECLARED};
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<>();
int counter;
boolean continueInput;
int contCounter;
do {
do {
System.out.print("Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: ");
switch (stdin.next().toLowerCase()) {
case "add":
add(stdin, studentList);
counter = 0;
break;
case "remove":
remove(studentList, stdin);
counter = 0;
break;
case "list":
list(studentList);
counter = 0;
break;
case "save":
String fileName = getFileName(stdin);
save(fileName, studentList);
counter = 0;
break;
case "sort":
counter = 0;
sort(studentList);
break;
default:
System.out.println("Improper input, please enter only ADD, REMOVE, LIST, or SAVE.");
counter = 1;
}
} while (counter == 1);
do {
System.out.print("\nDo you want to continue? Yes or no: ");
switch (stdin.next().toLowerCase()) {
case "yes":
contCounter = 0;
continueInput = true;
break;
case "no":
contCounter = 0;
continueInput = false;
break;
default:
contCounter = 1;
continueInput = false;
System.out.print("\nPlease only enter 'yes' or 'no'.");
}
} while (contCounter == 1);
} while (continueInput);
} // end main method
public static void add(Scanner stdin, ArrayList<Student> studentList) {
String firstName;
String lastName;
String uid;
StudentType studentType;
ClassStanding studentClassStanding;
Major major;
double overallGPA;
double majorGPA;
String majorProfessor;
boolean thesisOption;
System.out.print("Please enter the student's first name: ");
String tempName = stdin.next();
firstName = checkName(tempName);
System.out.print("Please enter the student's last name: ");
tempName = stdin.next();
lastName = checkName(tempName);
System.out.println("Please enter the student's UID in the format 'U####' or 'U#####': ");
String tempUID = stdin.next();
uid = checkUID(tempUID).toUpperCase();
int count;
do {
System.out.print("Please enter the student's status as UNDECLARED, UNDERGRADUATE, or GRADUATE: ");
switch (stdin.next().toUpperCase()) {
case "UNDECLARED":
studentType = StudentType.UNDECLARED;
studentClassStanding = setStudentClassStanding(studentType);
count = 0;
Student student = new Student(firstName, lastName,
uid, studentType, studentClassStanding);
studentList.add(student);
break;
case "UNDERGRADUATE":
studentType = StudentType.UNDERGRADUATE;
major = setMajor();
studentClassStanding = setStudentClassStanding(studentType);
System.out.println("Enter the student's overall GPA below.");
overallGPA = setGPA();
System.out.println("Enter the student's major GPA below.");
majorGPA = setGPA();
count = 0;
UnderGraduate underGraduate = new UnderGraduate(firstName, lastName, uid, studentType,
studentClassStanding, major, overallGPA, majorGPA);
studentList.add(underGraduate);
break;
case "GRADUATE":
studentType = StudentType.GRADUATE;
studentClassStanding = setStudentClassStanding(studentType);
majorProfessor = setMajorProfessor();
thesisOption = setThesisOption();
count = 0;
Graduate graduate = new Graduate(firstName, lastName, uid, studentType,
studentClassStanding, majorProfessor, thesisOption);
studentList.add(graduate);
break;
default:
System.out.println("Please enter either Undeclared, Undergraduate, or Graduate only.");
count = 1;
}
} while (count == 1);
} // end add method
public static String checkName(String tempName) {
int a = 1;
String name1;
Scanner scanner = new Scanner(System.in);
do {
name1 = tempName; // hold the value of firstName in name1
for (int i = 0; i < tempName.length(); i++) { // loop to check input consists of letters (is a name)
if (!Character.isLetter(tempName.charAt(i))) { // if non-letters detected, ensure this was intentional
System.out.println("Please ensure you've entered the correct name. Re-enter the name or enter 'continue' to proceed: ");
tempName = scanner.nextLine();
if (tempName.equalsIgnoreCase("continue")) { // if user enters "continue", use original input
a = 0;
tempName = name1; // pass name1 value to firstName
break;
} else {
a = 1; // continue prompting for firstName
}
} else { // accept input
a = 0;
}
}
} while (a == 1); // loop to ensure proper input
return tempName;
} // end checkName method
public static String checkUID(String tempUID) {
Scanner scan = new Scanner(System.in);
int a;
do {
if (tempUID.charAt(0) == 'U' || tempUID.charAt(0) == 'u') {
if (tempUID.length() == 6 || tempUID.length() == 5) {
a = 0;
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} while (a == 1);
return tempUID;
} // end checkUID method
public static ClassStanding setStudentClassStanding(StudentType studentType) {
Scanner scan = new Scanner(System.in);
int count;
ClassStanding studentTempClassStanding = null;
do {
if (studentType == StudentType.UNDECLARED || studentType == StudentType.UNDERGRADUATE) {
System.out.print("Please enter the student's class standing as either Freshman, Sophomore, Junior, Senior, or Unknown: ");
switch (scan.next().toUpperCase()) {
case "FRESHMAN":
studentTempClassStanding = ClassStanding.FRESHMAN;
count = 0;
break;
case "SOPHOMORE":
studentTempClassStanding = ClassStanding.SOPHOMORE;
count = 0;
break;
case "JUNIOR":
studentTempClassStanding = ClassStanding.JUNIOR;
count = 0;
break;
case "SENIOR":
studentTempClassStanding = ClassStanding.SENIOR;
count = 0;
break;
case "UNKNOWN":
studentTempClassStanding = ClassStanding.UNKNOWN;
count = 0;
break;
default:
System.out.println("Please enter only Freshman, Sophomore, Junior, Senior, or Unknown.");
count = 1;
}
} else {
System.out.print("Please enter the student's class standing as either 'Masters' for Masters Studies or 'PhD' for PhD Studies: ");
switch (scan.next().toUpperCase()) {
case "MASTERS": studentTempClassStanding = ClassStanding.MASTERS_STUDIES; count = 0; break;
case "PHD": studentTempClassStanding = ClassStanding.PHD_STUDIES; count = 0; break;
default: System.out.println("Please enter only 'Masters' or 'PhD'.");
count = 1;
}
}
} while (count == 1);
return studentTempClassStanding;
} // end setStudentClassStanding method
public static Major setMajor() {
Major tempMaj = null;
Scanner s = new Scanner(System.in);
int c;
do {
System.out.print("Please enter the student's major as either CS, CEG, EE, ISE, BME, ME, MET, or Unknown: ");
switch (s.next().toUpperCase()) {
case "CS":
tempMaj = Major.CS;
c = 0;
break;
case "CEG":
tempMaj = Major.CEG;
c = 0;
break;
case "EE":
tempMaj = Major.EE;
c = 0;
break;
case "ISE":
tempMaj = Major.ISE;
c = 0;
break;
case "BME":
tempMaj = Major.BME;
c = 0;
break;
case "ME":
tempMaj = Major.ME;
c = 0;
break;
case "MET":
tempMaj = Major.MET;
c = 0;
break;
case "UNKOWN":
tempMaj = Major.UNKNOWN;
c = 0;
break;
default:
System.out.println("Please enter only the specified values. ");
c = 1;
}
} while (c == 1);
return tempMaj;
} // end setMajor method
public static double setGPA() {
Scanner s = new Scanner(System.in);
double gpa;
int a;
do {
try {
System.out.print("Please enter the student's GPA: ");
gpa = s.nextDouble();// read in the gpa
if (gpa < 0.0 || gpa > 4.0) { // ensure the gpa is in the correct range
System.out.println("Invalid input, please enter a positive value between 0.0 and 4.0.");
a = 1;
} else {
a = 0;
}
} catch (InputMismatchException ex) { //catch any exceptions, prompt for correct input
a = 1;
gpa = 0.0;
System.out.println("Sorry, please enter a double value.");
s.nextLine(); // skip the last input
}
} while (a == 1 || gpa < 0.0 || gpa > 4.0); //loop while gpa is negative or incorrect input is received
return gpa;
} // end setGPA method
private static String setMajorProfessor() {
Scanner s = new Scanner(System.in);
String prof;
System.out.print("Please enter the name of the major professor: ");
String tempName = s.nextLine();
prof = checkName(tempName);
return prof;
} // end setMajorProfessor method
private static boolean setThesisOption() {
Scanner s = new Scanner(System.in);
boolean thesis = false;
int a;
do {
System.out.print("Please enter 'yes' if a thesis will be written, otherwise enter 'no': ");
switch (s.next().toUpperCase()) {
case "YES": thesis = true; a = 0; break;
case "NO": thesis = false; a = 0; break;
default: System.out.println("Please enter only 'yes' or 'no'."); a = 1;
}
} while (a == 1);
return thesis;
} // end setThesisOption method
private static void list(ArrayList<Student> studentList) {
for (int i = 0; i < studentList.size(); i++) {
System.out.println(studentList.get(i).toString());
}
} // end list method
public static String getFileName(Scanner stdin) {
System.out.print("Please enter the file name: "); // Prompt for input
String fileString = stdin.next();
return fileString; // Pass the fileString var to the main method
}//end of getFileName method
private static void save(String fileName, ArrayList<Student> studentList) {
int a; // create a counter
Scanner stdin = new Scanner(System.in);
do {
try {
PrintWriter writer = new PrintWriter(fileName); // Create a printwriter
for (int i = 0; i < studentList.size(); i++) {
writer.print(studentList.get(i).toString() + "\n"); //Print the arraylist to file
}
writer.close(); //Close the printwriter and save the file
a = 0;
} catch (FileNotFoundException ex) { // Catch any exceptions
System.out.println("The file could not be found, please re-enter the file name: "); // get new file name if an exception is thrown
fileName = stdin.nextLine();
a = 1;
}
} while (a == 1); // loop while exceptions are thrown
System.out.println("All information has been saved at " + fileName); // output that the arraylist has been saved in the specified file
// Make the following its own method
System.out.print("Would you like to read the contents of the file? Yes or no: ");
int b;
do {
switch (stdin.next().toLowerCase()) {
case "yes": readFromFile(fileName); b = 0; break;
case "no": b = 0; break;
default: System.out.println("Please enter only yes or no."); b = 1;
}
} while (b == 1);
} // end save method
private static void remove(ArrayList<Student> studentList, Scanner stdin) {
System.out.print("Please enter the UID of the student to be removed: ");
String tempUID = stdin.next();
String uidRemove = checkUID(tempUID);
for (int i = 0; i < studentList.size(); i++) {
if ((studentList.get(i).getUid()).equalsIgnoreCase(uidRemove)) {
studentList.remove(i);
}
}
System.out.println("The student with UID " + uidRemove + " has been removed.");
} // end remove method
private static void sort(ArrayList<Student> studentList) {
String uidLessU1;
String uidLessU2;
for (int i = 0; i < studentList.size(); i++) {
uidLessU1 = (studentList.get(i).getUid()).substring(1, studentList.get(i).getUid().length());
for (int j = 0; j < studentList.size(); j++) {
uidLessU2 = (studentList.get(j).getUid()).substring(1, studentList.get(j).getUid().length());
if (Integer.parseInt(uidLessU1) < Integer.parseInt(uidLessU2)) {
Student hold = studentList.get(i);
studentList.set(i, studentList.get(j));
studentList.set(j, hold);
}
}
}
} // end sort method
private static void readFromFile(String fileName) {
System.out.println("The contents of " + fileName + " as read from NotePad: ");
try {
Scanner fileReader = new Scanner(new File(fileName)); //Create a scanner
while (fileReader.hasNextLine()) { //Loop to read the file
String fromFile = fileReader.nextLine();
System.out.println(fromFile); //Output the file contents
}
} catch (FileNotFoundException ex) { //Catch any exceptions
System.out.println("Exception caught");
}
} // end readFromFile method
} // end main class
A sample of the problem would be (at this point I've already entered all the values instantiating the objects):
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: list
Student s w whose UID is U3333 is a
UNDECLARED student doing JUNIOR work.
Student p o whose UID is U1111 is a
UNDECLARED student doing JUNIOR work.
Student p u whose UID is U44444 is a
UNDECLARED student doing JUNIOR work.
Student w e whose UID is U4444 is a
UNDECLARED student doing JUNIOR work.
Student s r whose UID is U2222 is a
UNDECLARED student doing JUNIOR work.
Student s u whose UID is U7777 is a
UNDECLARED student doing JUNIOR work.
Student po iu whose UID is U77777 is a
UNDECLARED student doing JUNIOR work.
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: sort //calls the sort method
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: list // calls the list method and prints out the arraylist
Student p o whose UID is U1111 is a
UNDECLARED student doing JUNIOR work.
Student s r whose UID is U2222 is a
UNDECLARED student doing JUNIOR work.
Student s w whose UID is U3333 is a
UNDECLARED student doing JUNIOR work.
Student s u whose UID is U7777 is a //why is this out of place?
UNDECLARED student doing JUNIOR work.
Student w e whose UID is U4444 is a
UNDECLARED student doing JUNIOR work.
Student p u whose UID is U44444 is a
UNDECLARED student doing JUNIOR work.
Student po iu whose UID is U77777 is a
UNDECLARED student doing JUNIOR work.
Just make Student implement Comparable and then you can do
Collections.sort(studentList);

Show a java console menu again after switch finishes

I am trying to write a java console menu but i can't render it in the console. Here is the code i wrote so far.
package com.registrar;
import java.util.*;
class GUIMenu {
private Course[] courses = new Course[100];
private Person[] persons = new Person[1000];
public void display_menu() {
System.out.println("****************MENU*****************");
System.out.println("[1] Add Course\n[2] Add Student to Course \n[3] Verify Registration \n[4] Remove Student \n[5] Add Persons");
System.out.println("**************************************");
System.out.println("Selection: ");
}
public GUIMenu(){
Person p = null;
Scanner in = new Scanner (System.in);
int input = in.nextInt();
switch (input){
case 1:
Scanner sc = new Scanner(System.in);
System.out.println("Enter Course Name: ");
String name = sc.nextLine();
System.out.println("Enter Course ID:");
Integer cID = sc.nextInt();
System.out.println("Enter Instructor ID:");
Integer pn = sc.nextInt();
for(int i = 0; i < persons.length; i ++){
System.out.println(persons[i]);
}
for(int i = 0; i<persons.length; i++){
if(persons[i] !=null){
if(persons[i].getId().intValue() == pn){
System.out.println("Record Found");
p = persons[i];
}
else
System.out.println("Record Not Found");
}
}
Course c = new Course(name, cID);
if(p!=null){
Instructor ins = new Instructor(p);
c.setInstructor(ins);
}
System.out.println(c + " has been created");
for(int i = 0; i < courses.length; i ++){
if(courses[i] == null){
courses[i] = c;
break;
}
}
new GUIMenu();
case 2:
for(int i = 0; i < courses.length; i ++){
if(courses[i] != null)
System.out.println(courses[i]);
}
break;
case 3:
System.out.println ( "You picked option 3" );
break;
case 4:
System.out.println ( "You picked option 4" );
break;
case 5:
Scanner pers = new Scanner(System.in);
System.out.println("Enter Person Name: ");
String pname = pers.nextLine();
System.out.println("Enter Person ID:");
Integer oiID = pers.nextInt();
Person per = new Person(pname, oiID);
for(int i = 0; i < persons.length; i ++){
if(persons[i] == null){
persons[i] = per;
break;
}
}
display_menu();
default:
System.err.println("Unrecognized option");
}
}
public static void main ( String[] args ) {
GUIMenu a = new GUIMenu();
a.display_menu();
}
}
I am trying that after a selection on the menu the code returns the menu again after completing the code associated with that particular selection. What i am doing wrong? I dont see the menu at all displaying.
What i am doing wrong?
Look at the code: This is where it starts:
public static void main ( String[] args ) {
GUIMenu a = new GUIMenu(); // This is executed first...
a.display_menu();
}
let's have a look at it
public GUIMenu(){
Person p = null;
Scanner in = new Scanner (System.in);
int input = in.nextInt(); // this is where it's waiting for your input.
...
Looking at the flow of your code, it is pretty clear why the menu is not shown.
EDIT:
You are looking for something like this:
public void runApplication() {
// init Scanner
boolean nextRound = true;
while(nextRound) {
displayMenu();
int input = sc.nextInt();
switch(input) {
case 1: // do stuff
break;
case 2: // this is the exit command
nextRound = false;
break;
// more cases
default:
// undefined input
}
}
}
So you use your constructor only for constructor relevant code and later call the runApplication() method.

Categories