Java Error when using clearform(); on a save button - java

This is a Java Swing application to record CA results.The application will ask students to enter their Name, Student Number and CA Grade. The system must remember the Student
with the highest and Lowest Grades and display them on the input screen. I am currently receiving an error when using the
clearForm();
when coding the save button on my GUI.Subsequently the clearform(); and listResults(); methods are giving me errors.
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Creating a temp Result
result r = new result(nameTf.getText(), numTf.getText(), Integer.valueOf(resultTf.getText()));
// Saving it to the object array
registration[counter] = r;
// Checking the high value currently being stored, if it is higher than the new score, update
if (Integer.valueOf(highNum.getText()) < Integer.valueOf(resultTf.getText())) {
highNum.setText(resultTf.getText());
}
// Checking the low value currently being stored, if it is lower than the new score, update
if (Integer.valueOf(resultTf.getText()) < Integer.valueOf(lowNum.getText()) || counter == 0) {
lowNum.setText(resultTf.getText());
}
clearForm(); // clear the three input boxes when the user presses save
counter++; // Increment the student counter
listResults(); // List all stuudents currently stored in our object array
}
Asking this would be a lot easier with images.

Related

JAVA seperate class method not incrementing a variable in my main class method

so this is the main code for my text-based game.
import java.util.Scanner;
public class D_M_RPG {
public static void main(String[] args) {
//Creating the class to call on my toolbox
D_M_RPGtoolbox toolbox = new D_M_RPGtoolbox();
//Creating the scanner class for user input
Scanner input = new Scanner(System.in);
//Initiating variables and final variables aswell as arrays
//token variable to validate open spots in an array
int slotCounter = 0;
int inventoryExpander = 11;
//First initiated will be the character creation variables
String hairColor = "";
String eyeColor = "";
String skinColor = "";
String gender = "";
//Initiating the arrays for character inventory slots
String[] weaponSlots = new String[10];
//initiating the arrays for the character creation
String[] hairColorARR = {"black","Green","Yellow","Brown","Blue","Blonde","Grey","White"};
String[] eyeColorARR = {"Green","Brown","Blue","Grey",};
String[] skinColorARR = {"White","brown","Black",};
String[] genderARR = {"Male","Female"};
//Creating the introduction title and introduction
System.out.println("Welcome to, COLD OMEN.");
System.out.println("\nNOVEMBER 12th, 2150: ONTARIO, CANADA");
System.out.println("\nYou hear loud shouts and gun fire all around you but can't pinpoint the location of anything, you feel a bit dazed until someone grabs you and you open your eyes and snap out of it.");
System.out.println("\nUnknown: 'Get up, its time to move out. Take this.'");
System.out.println("\nUnknown hands you a 'M4-A4 RIFLE'");
System.out.println("\nyou manage to catch a small glimpse of him before you get up.");
//Character creation screen
System.out.println();
//ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "M4-A4 RIFLE");
System.out.println("\n" + weaponSlots[0]);
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "ak47");
System.out.println(weaponSlots[0]);
}
}
so I have this method I made to basically add an "item" to the weaponSlots array (the inventory) but whenever I run it it will add to the first element in the array [0] but it wont incremement the slotcounter which should go up by one every time the method is used so that I dont replace any items in the array It should just add items until its full which is checked using the inventoryExpander variable. at the moment I have it printing the element at 0 and 0 for the array but i have checked 1 aswell and 1 is just null no item added it only just replaces the element at 0. heres the code for the method to increment etc:
public class D_M_RPGtoolbox {
//method for random number generating to be used for crit hits, turns, loot generation etc
public int randomGen(){
int x = (int) (Math.random()*((20-0)+1)+0);
return x;
}
//method for inserting into an array ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER FIX
public void insert(String[] a, int b, int d , String c) {
if(b < d) {
a[b] = c;
b++;
}//end of if statement
}//end of method
}
What you are actually performing the ++ operation on in b is a copy of the value in slotCounter.
The variable slotCounter is passed into insert "by-value".
This unlike what you probably imagine, that it is passed "by-reference".
One solution would be to do the slotCounter++ from the call row instead; and another would be to let the toolbox own the slotCounter variable completely.
This question uses the image of passing a copy of document content (by value) where changes to the document would not be seen by the sender; or as a link to a shared document (by reference), where changes could be made to the same page that the sender sees.
Its always going to be zero since you are passing zero and incrementing the local variable b.
Try calling the method as below with post increment ++ to slotCounter and see if it works for you,
toolbox.insert(weaponSlots, slotCounter++, inventoryExpander, "M4-A4 RIFLE");

Java array in for loop

I'm trying to create a menu for toll data entry that runs in a loop until the user requests to exit. The menu will ask the user to enter data which is stored in an array and keeps adding to the array until the user exits from the menu.
The menu should look as follows:
Toll Data Entry Menu
My menu works fine until asking the user to enter the trip date. The menu will continue to ask for each trip date up until the end of the length of the array (30 - arbitrary length).
I however want the menu to ask for the trip date, store the value entered by the user, then move onto entering the entry point, store value, etc and then loop back to the selection for the user to enter the above details again for a separate trip until they choose to exit. (I need to print these values later on) I'm not sure how to store the values from the user separately without prompting the user to enter all (30) values at the one time.
Should I be using an array or is there another way to store multiple values for a looped menu?
Hope my explanation is clear.
To fetch the complete set of details one at a time, you just need a single for loop as:
String[] datesA = new String [30];
int[] entryP = new int [30];
int[] exitP = new int [30];
for (int i = 0; i < 30; i++) {
System.out.println("Enter trip date: ");
datesA[i] = inputA.nextLine();
// User to enter entry point
System.out.println("Enter entry point: ");
entryP[j] = inputA.nextInt();
// User to enter exit point
System.out.println("Enter exit point: ");
exitP[k] = inputA.nextInt();
}
To improve the implementation though think over the lines of creating an object that includes all the details in one as :
class TollDataEntry {
String entryDate;
int entryPoint;
int exitPoint;
.... getter, setter etc.
}
and then use an array or Collection of this object to store the details of each TollDataEntry with those three values as a single entity.

Java: Adding two random array elements for each category of a custom arraylist

I am providing the user with two random videos for each category they have selected.
I have an ArrayList of strings for the user preferences.
I also have an ArrayList of all of the videos in the database.
So I am trying to search through each of those category preferences one by one and find two random videos that fit into it those category.
I have implemented a solution that works (On a small dataset). But I am not sure it is optimal method considering there will soon be 500 videos, 50 categories and the user will be able to select 5 category preferences:
This is how I worked it out:
//Create a new array to store the videos
ArrayList<Video> videos = new ArrayList<>();
// Create counter for the position in the user preference array
int userPrefernceArrayIndex = 0;
// Create counter for number of successful category guesses
int numberOfSuccessfulGuesses = 0;
// Keep running until we have 2 videos for each of the user preferences
while (videos.size() < MainActivity.userPrefrencesStaticArraylist.size() * 2){
// Generate a random integer to get an entry random integer from the database array
Random rand = new Random();
int randomAlarmVidInt = rand.nextInt(MainActivity.allVideosFromDatabaseStaticArray.size());
// Find the category of the random video that was chosen
String categoryForRandomGuess = MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt).getVideoCategory();
// Find the current user video category we are testing for
String currentCategoryPreference = MainActivity.userPrefrencesStaticArraylist.get(userPrefernceArrayIndex);
// Check if category of the random video we got is the same as the category user
// preference we are testing for
if (categoryForRandomGuess.equals(currentCategoryPreference)){
// If it the the preference and the random video categories match add it to the video array
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
numberOfSuccessfulGuesses++;
// If the number of successful guesses is divisible by two then we have added two correct videos
// for that category so iterate to the next category
if (numberOfSuccessfulGuesses % 2 == 0){
userPrefernceArrayIndex++;
}
}
Because of the possibility for problems I hardly ever use a while loop or random unless necessary. I also see that guessing the number may not be the best solution memory wise. So I just want to make sure I am doing it the best way to avoid issues.
Thanks for your help
Yes you can optimize your solution as following:
Currently your iterations of while loop are getting wasted: Say categoryForRandomGuess and currentCategoryPreference both are equal to "Category 1".
So numberOfSuccessfulGuesses becomes 1, but userPrefernceArrayIndex stays 0. So if in next iteration if categoryForRandomGuess is "Category 4", the iteration will be wasted even if currentCategoryPreference can become equal to "Category 4" for some other value of userPrefernceArrayIndex, that is value other than 0.
I would Suggest using a HashMap<String,Integer> where String stores the video category and Integer stores the index of first video found in database of the category.
if the Integer value is -1, it will mean we have 2 videos and we are done with the category.
Now you can eliminate the variable userPrefernceArrayIndex and your code will be a lot shorter
So your code would be:
HashMap<String,Integer> mymap = new HashMap<>();
while (videos.size() < MainActivity.userPrefrencesStaticArraylist.size() * 2)
{
// Generate a random integer to get an entry random integer from the database array
Random rand = new Random();
int randomAlarmVidInt = rand.nextInt(MainActivity.allVideosFromDatabaseStaticArray.size());
// Find the category of the random video that was chosen
String categoryForRandomGuess = MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt).getVideoCategory();
//check if the hashmap has the category
if(mymap.get(categoryForRandomGuess) == null)
{
mymap.put(categoryForRandomGuess,randomAlarmVidInt);
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
}
else
{//-1 means we already have 2 videos of the category.
if(mymap.get(categoryForRandomGuess) == -1)
continue;
//if following condition is true, then its a duplicate video
if(mymap.get(categoryForRandomGuess) == randomAlarmVidInt)
continue;//skip the rest of loop and get new value of randomAlarmVidInt
else
{
mymap.put(categoryForRandomGuess,-1);//second video added
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
}
}
}

Looping through Arrays in Java

I am trying to write a program to simulate an airline reservation system. I an supposed to use an array of type boolean to represent the number of seats. First five seats represent first class and last five represent economy. Initially the program must allow the user to make a choice between first class and economy and then his choice is processed as follows:
A user can only be assigned an empty seat in the class he chooses.
Once a class is full, the user is offered the option to move to the next class
If the user agrees to move to the next class a simple boarding pass is printed.
If the user refuses to move to the next class. The time for the next flight is displayed. i would appreciate help on how to loop through the elements of the array to determine whether its true of false. Also i am trying to display the number of seats available in each class before the user makes a selection this is what i've written so far.. My code is far from complete, i acknowledge that, i am a novice programmer please help. Thank you.
import java.util.Scanner;
public class AirlineReservation
{
private boolean[] seats =; // array to hold seating capacity
private String AirlineName; // name of airline
private int[] counter = new int[5]
// constructor to initialize name and seats
public Airline(String name, boolean[] capacity )
{
AirlineName = name;
seats = capacity;
} // end constructor
// method to set the Airline name
public void setName( String name )
{
AirlineName = name; // store the course name
} // end method setCourseName
// method to retreive the course name
public String getName()
{
return AirlineName;
} // end method getName
// display a welcome message to the Airline user
public void displayMessage()
{
// display welcome message to the user
System.out.printf("Welcome to the Self-Service menu for\n%s!\n\n",
getName() );
} // end method displayMessage
// processUserRequest
public void processUserRequest()
{
// output welcome message
displayMessage();
// call methods statusA and StatusB
System.out.printf("\n%s %d:\n%s %d:\n\n",
"Number of available seats in First class category is:", statusA(),
"Number of available seats in Economy is", statusB() );
// call method choice
choice();
// call method determine availability
availability();
// call method boarding pass
boardingPass();
} // end method processUserRequest
public int statusA()
{
for ( int counter = 0; counter <= (seats.length)/2; counter++ )
} // revisit method
// method to ask users choice
public String choice()
{
System.out.printf(" Enter 0 to select First Class or 1 to select Economy:")
Scanner input = new Scanner( System.in );
boolean choice = input.nextBoolean();
} // end method choice
// method to check availability of user request
public String availability()
{
if ( input == 0)
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
else
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
}
}
#Anthony : As you are novice, hence please look at following comments :
1. Be specific while asking your question. In this case the question was "how to loop through array!". You posted complete problem statement.
2. Please google it or research it properly on internet if similar question has been asked by anybody before. In this case, similar question can be find here :
Iterate through string array in Java
Because of these reasons people are giving your query downvote!
Now just want to provide answer to your question as you look quite new to programming :
boolean flag[] = {true,false,true,false};
for(int i=0;i<flag.length;i++){
System.out.println(flag[i]);
}
I hope it helps!

How can I add new data to an Arraylist & How can I remove user input duplicates?

What i am shooting for is to be able to take the input from my text field in my GUI and put it into an ArrayList. Then I need to check the array and see if I already have the Integer in the array. If so I need to remove both Integers so the Integer is no longer inside the array. I also need to be able to add the Integer if it is not a duplicate to the ArrayList.
The purpose of this is to be able to have users sign in with a number. The vision I have is for them to put their unique number in when they sign in or sign out (Like a time clock). If their number is not in the array, they are signing in. If their number is in the arraylist then they are signing out.
This is what i have for code so far, i am getting a problem with signing out. It keeps sending the second value in the array back as the only one able to sign out. I have tried fixing it and can't seem to figure out what is wrong. Let me know if it would be more helpful if i posted my whole program or if this code snippet is enough to figure it out.
Thanks,
private void btnSignInActionPerformed(java.awt.event.ActionEvent evt) {
// Get data from form and put it into an Array List
Integer txtUserSignInName = Integer.valueOf(txtUserSignIn.getText());
ArrayList<Integer> userSignInNumber = new ArrayList();
userSignInNumber.add(12345678); //sample data
userSignInNumber.add(55489563); //sample data
userSignInNumber.add(26489564); //sample data
userSignInNumber.add(78654865); //sample data
userSignInNumber.add(txtUserSignInName);
// Setting up HashSet so no duplicate data
Set<Integer> hashSet = new HashSet<>();
hashSet.addAll(userSignInNumber);
userSignInNumber.clear();
userSignInNumber.addAll(hashSet);
// Other settings needed
SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a");
String time = df.format(new Date());
if ((txtUserSignIn.getText() != null && txtUserSignIn.getText().isEmpty())) {
String userSignInErrorMessage = "Sorry, Please Try Again";
JOptionPane.showMessageDialog(new JFrame(), userSignInErrorMessage, "Incorrect Sign In",JOptionPane.ERROR_MESSAGE);
//setting focus
txtUserSignIn.setText("");
txtUserSignIn.requestFocus();
} else {
for(int i = 1; i < userSignInNumber.size(); i++) {
// If number is already in array, remove it
if(txtUserSignInName.equals(userSignInNumber.get(i))) {
userSignInNumber.remove((Integer)txtUserSignInName);
System.out.println(txtUserSignInName + " has signed out");
txtLoggedInUsers.append(txtUserSignInName + " has signed out at " + time + "\n");
break;
} else { // If number is not in the array, add it to the array
System.out.println(txtUserSignInName + " has signed in");
txtLoggedInUsers.append(txtUserSignInName + " has signed in at " + time + "\n");
break;
}
}
System.out.println(userSignInNumber);
}
}
Lists are not really suitable for what you are trying to do. You would be better off using one of the Set interface implementations. Sets provide fast contains()/add()/remove() methods that you can use, without generally having to iterate over all elements manually in a loop. And if you do need to quickly iterate over all elements for some reason, then a LinkedHashSet would work just fine. For example:
Set<Integer> signedIn = new LinkedHashSet<>();
...
if (signedIn.add(loginNumber)) {
// The set was modified, therefore this is a new login
} else {
// The number was already present, log-off the user.
signedIn.remove(loginNumber);
}
...
if (signedIn.contains(loginNumber)) {
// Allow the user to...
} else {
// Error, user not signed in
}
There are a number of problems with your implementation.
The loop starts at 1 when array indices start at 0, so you are skipping the first entry.
Then you always break out of the loop straight away after checking the 2nd item and so don't check any others.
A better approach would be to use a Set, not just to remove duplicates, but as a primary way to store who is signed in. Then you can check if a number is in the set easily with the contains method so you don't need to loop through manually (which means you don't have to deal with the problems associated with removing items from a list while you are looping through it).

Categories