I'm stuck at this part of my program. These are 2 options for my Student Information System (not using GUI/JOption and without linking to a database. I already have a 2-dimensional array (String records[][] = new String [5][3];) that has the first 2 "rows" ([0][0] to [0][2] and [1][0] to [1][2]) filled up with pre-assigned data (First Name, Last Name, Course).
If you look below, the part where "b" or "B" option is selected, this is for adding new values to a new array (incremented so that when option B is used, it will assign first [2][0], then [3][0]
and so on). It seemed to work since it does show that all the data I've entered was added and is displayed in the proper order. THE PROBLEM IS: when I choose 'Y" to return to the top menu and select option A to VIEW the newly added record (using ID number 2), it shows that it contains all "null". Is there something I've missed? This is the missing step I need in order to finish this program. Thanks ahead for the help.
if("a".equals(option1)|| "A".equals(option1)){
System.out.println("Please enter the Student ID for the record to view.");
String a = reader1.readLine();
idcheck = Integer.parseInt(a);
x1=idcheck;
for(int y=0;y<3;y++){
System.out.print(records[x1][y] + " ");
}
System.out.println("\nReturn to Main Menu or Exit? (Y/N)");
cont1= reader1.readLine();
}
else if("b".equals(option1)||"B".equals(option1)){
arr_count++;
for (int y = 0; y<3;y++){
System.out.println("Enter Value for "+ option [y]+":" );
String X = reader1.readLine();
records[arr_count][y] = X;
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I'm still new to programming and I want to make a program that will take the food order from user until the user presses "n" to stop. But I can't seem to make it work like I want it to.
I want my output to be like this.
Buy food: Burger
Order again(Y/N)? y
Buy Food: Pizza
Order again(Y/N)? n
You ordered:
Burger
Pizza
But my output right now is this.
Buy food: Burger
Order again(Y/N)? y
Buy food: Pizza
Order again(Y/N)? n
You ordered:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Array.getFoodName()" because "food_arr2[i]" is null
at Food.main(Food.java:50)
Here is my code:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Food food = new Food();
Array[] food_arr;
boolean stop = false;
String foodName;
int k = 1;
int j = 0;
while(stop == false) {
food_arr = new Array[k];
System.out.print("Buy food: ");
foodName = s.next();
food_arr[j] = new Array(foodName);
food.setFoodArray(food_arr);
System.out.print("Order again(Y/N)? ");
String decide = s.next();
if(decide.equalsIgnoreCase("y")) {
k++;
j++;
}
else if(decide.equalsIgnoreCase("n")) {
stop = true;
}
}
Array[] food_arr2 = food.getFoodArray();
for (int i = 0; i < food_arr2.length; ++i) {
System.out.println("\nYou ordered: ");
System.out.println(food_arr2[i].getFoodName()); //This line is the error according to my output
}
}
I don't know how to fix this and I was hoping for someone to help me.
I think I see what you are trying to do with the k value setting the size of the array you are using.
However, with each iteration of the while loop:
food_arr = new Array[k];
Will create a new empty array each time!
So, for example, on the second iteration
food.setFoodArray(food_arr);
Will set foods array as something like [null, "Pizza"]
Even if this did work, creating a new array each time is not a very efficient method.
I would strongly recommend using a different, dynamically allocated data structure such as an ArrayList and defining it outside the scope of the while loop.
ArrayList<Food> food_arr = new ArrayList<Food>()
// Note that I'm just guessing the data type here - I can't see what you are actually using!
while(stop == false) {
System.out.print("Buy food: ");
foodName = s.next();
food_arr.add(foodName)
// etc, etc
}
food.setFoodArray(food_arr)
// ! Note: You will need to convert the array list into an array
// ! or change the data struture in the Food class
// etc, etc
However, this is just the first solution that popped into my head, check out different kinds of data structures and think about how else you could design this program yourself!
I am creating a project where the user enters names of multiple sports teams. The user is not allowed to enter the same name of a team twice. I can't figure out how to compare elements of an array. I tried to use a while loop with equals but I don't think it's the right way.
for(int i = 0; i<tabEquipe.length;i++){ // tabEquipe is the table content of the teams that the user enters.
System.out.println("Entrez les noms des equipes: "); // Asks user to enter team names.
rep2 = a.nextLine();
tabEquipe[i] = rep2;
while(tabEquipe[i].equals(tabEquipe[i])){
}
}
That's confusing, so I assume you have already a new user you want to add, and it seems you can compare users with equals. If there's a new user newUser then it could look like this:
boolean found = false;
for(int i = 0; i < tabEquipe.length; i++){
if (tabEquipe[i].equals(newUser))
{
found = true;
break;
}
}
or, shorter:
boolean found = Arrays.asList(tabEquipe).contains(newUser);
You can use a HashSet to store the names of teams in such a manner that the check if a new name was already used happens very efficiently. For example:
...
Set<String> teamNamesSet = new HashSet<>();
for (int i = 0; i < teamNames.length; i++) {
...
// Checking if a team name was already used
while (teamNamesSet.contains(name)) {
// Show some error message, request input again, etc.
}
// Adding a new team name to the set
teamNamesSet.add(name);
// Adding a new team name also to the array you need
teamNames[i] = name;
}
The great advantage of this approach is that the check if a name is already in a HashSet takes a constant time (O(1)). Using a for loop to check has a linear complexity (O(n)).
"If a player's playerID ends in 00 to 49, this person is on the “lucky list”; however if the playID ends in 50 to 99, this person is on the “normal list”."
//Players ID, is what i have so far
System.out.println("Please enter the player’s ID (8 digits): ");
int playerId = input.nextInt();
//When i use if else statements i can select for certain cases. for example
if (playerId % 50)
normalList;
if (playerId % 3)
luckyList;
These are two example that i can think of. I assume there is a shorter and more logical way to do this but i dont have a clue how.
Be more clear on what normal list; and what luckyList; are. You say lists, so I am assuming you are using array or java.util.ArrayList to store your objects.
What I would do is to the effect of this:
`//Players ID, is what you have so far.
int playerID;
System.out.println("Please enter the player’s ID (8 digits): ");
playerID=input.nextInt();
System.out.println("Please re-enter the player's ID(8 digits):");
String IDword=input.next(); //can also use nextLine here
//now what happens is I have made a string version and an int version of your ID. Now, using charAt, I can access the last two values.
if(IDword.charAt(IDword.length()-2)=='4')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='3')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='2')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='1')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='0')
{
LuckyList.add(playerID);
}
else
normalList.add(playerID);`
This detects the second to last digit- if it is 4 or less, it adds to luckyList. Else, it will add to normalList.
You may just want to add something indicating that the data is always 8 digits (that just being if(IDword.size()==8) do the following.
I have written a Java menu console which asks users to select an option. I have successfully compiled the menu system which takes a users input and directs them to a menu page. The first of these pages asks 2 questions using "InputDialog" boxes.
Here is the code for the "InputDialog", when I run the java console i can access and enter information into these boxes fine.
private void enterInfor()
{
String carInfo;
int carHours;
int i = 0;
double fee = Double.parseDouble("7.50");
double sum = 0;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car 1 entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carHours == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
I have the "String" and "int" information to store the information that is input by the user, however I need the program to store at least 20 different inputs which can be accessed later in the console.
I have successfully made a console repeat information and then output the combined answers using a for loop =
"for(int Num=1; Num <= 6; Num++)"
and this allowed me to repeat a set of questions and then compile the information into statistics afterwards but for this console I need the "InputDialog" to only take in one set of answers at a time and then return the user to the initial console menu.
I'm sorry again if this is all pretty vague of information or formats, just need some kind of help on how/where to put the correct code.
Goal: Add a new Movie object to an existing Movie[] if there is room to add.
Code:
// Create the new Movie object
Movie movieToAdd = new Movie (newTitle, newYear);
// Add it to the Array
count = addMovie(movieList, movieToAdd, count);
Method Code:
public static int addMovie (Movie[] movieArray, Movie addMe, int count)
{
if (count != movieArray.length)
{
count++;
movieArray[count] = addMe;
System.out.println("Movie added successfully!");
}
else
{
System.out.println("Array size of " + movieArray.length + " is full. Could not add movie.");
}
return count;
}
QUESTION:
Currently, when the movieList array is printed out, the new entry prints as null even though the created Movie object will print just fine outside of the way. Therefore, I'm assuming the best way to add the addMe object into the array is to create a second new Movie object initialized within the array and build it piece by piece (so addMe will remain in memory, and a "copy" of addMe will be set into the array).
This to me doesn't feel very efficient (I hate extra data laying about...). Is there a better way to do this?
NOTE: The Movie object actually has 10 private data members. For this exercise I only needed to pass in two parameters and set defaults for the rest. You can imagine why I don't to use ten GET statements to build this array and have extra objects stuck in memory...
EDIT:
Current Print Out (Portions):
Menu options:
1. Show all movies:
2. Show movies sorted - manual
3. Show movies sorted - auto
4. Show Movie by Index
5. Search for movie Linearly
6. Search for movie using Binary Search
7. Add a movie
20. Quit
Please choose an option from the menu: 1 to 20:
7
Let's add the information for the new movie. Give me a Title and 4-digit Year, and I'll fill in the rest.
Title?
Me
Year of Release?
Please enter a valid 4 digit year: 1000 to 9999:
1213
Movie added successfully!
Menu options:
1. Show all movies:
2. Show movies sorted - manual
3. Show movies sorted - auto
4. Show Movie by Index
5. Search for movie Linearly
6. Search for movie using Binary Search
7. Add a movie
20. Quit
Please choose an option from the menu: 1 to 20:
25 | Les Vampires (1915) | Louis Feuillade | "Edouard Mathe, Marcel Levesque" | 1915 | 0 | http://www.imdb.com/title/tt0006206/ | http://www.guardian.co.uk/film/movie/117077/vampires | France | Horror | 175
null | 176
=============================================================================
MORE EDITS:
Constructor and Setters code - all this SHOULD be working right though.
public Movie (String t, int y)
{
// passed in
this.title = setTitle(t);
this.year = setYear(y);
// defaults
this.ranking = 0;
this.director = "No Director";
this.actors = "No Actors";
this.oscars = 0;
this.linkIMDB = "No IMDB Link";
this.linkGuardian = "No Guardian Link";
this.country = "No Country";
this.genre = "No Genre";
}
public String setTitle (String newTitle)
{
if (newTitle == null)
{
this.title = "No Title";
}
else
{
this.title = newTitle;
}
return this.title;
}
public int setYear (int newYear)
{
if (newYear >= 999 && newYear <=10000)
{
this.year = newYear;
}
else
{
newYear = 0000;
}
return this.year;
}
It isn't clear what you are asking, but this portion is incorrect:
count++;
movieArray[count] = addMe;
What if movieArray.length is 10, and count is 9? Then it will pass the count != movieArray.length check and then you will try to assign the element at index 10. Use post increment:
movieArray[count++] = addMe;
GOT IT!
I was using Count to set the index at which the new movie was stored.
Original count was 176.
Last index was 175.
I was increment BEFORE setting the movie, so the movie was being set at index 177.
So 176 was getting skipped.
It was only printing to 176 because that was the actual count, which wasn't accounting for the skipped space (there was an extra object in the array that wasn't getting printed).
(Figured this out when I attempted adding 2 new Movie objects to the array and got a null and then the first object only on print).
Solved by switching the set and the increment:
if (count <= movieArray.length)
{
movieArray[count] = addMe;
count++;
System.out.println("Movie added successfully!");
}