Compare elements within an array - java

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)).

Related

Cannot invoke because Array[] is null [duplicate]

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!

Finding the index of a string with specific requirements?

I'm a bit of a newbie to programming. :P
I'm working with Processing right now to create a table of subjects with their ID, Title and Availability.
I have a 2D array that contains information like this:
units[0][0] = "CAKE100"; //Subject ID
units[1][0] = "Eating Cake And Baking Too"; //Subject Title
units[2][0] = "November"; //Subject Availability
units[0][1] = "TACO204"; //Subject ID
units[1][1] = "Tacos And Other Delicious Things"; //Subject Title
units[2][1] = "April"; //Subject Availability
units[0][2] = "KITC102"; //Subject ID
units[1][2] = "Kitchen Safety"; //Subject Title
units[2][2] = "June"; //Subject Availability
I'm trying to filter through the unit[0][x] section to find the index location of every Subject ID that has "1" in the fourth position of the string.
For example, I want to return [0] [0] and [0] [2], because "CAKE100" and "KITC102" both have "1" in the fourth position.
I've tried to use indexOf or .substring but for some reason I can't figure it out.
EDIT:
Not sure how much help it will be but here's my butchered code:
void checkLevel100() {
for ( int j = 0; j < units.length; j++) {
position = 0;
// position = units[0][j].indexOf("1"); //This returns 4;
if (units[0][j].substring(4) == "1") { //This doesn't run at all, and so it returns 0.
position = j;
}
fill(0);
text(position, width/2, height/2);
}
}
I also did what Kevin Workman suggested. Here is the code for that:
for (int i = 0; i < units.length; i++) {
if(units[0][i] == "TACO204"){ //This results in 1, as expected
location[i] = i;
println(i);
}
Once again, thank you for your time :)
You need to break your problem down into smaller steps.
Step 1: Loop over your 2D array. You might use a nested for loop for this.
To test that this step works, you might just print every element in your 2d array before worrying about any logic.
Step 2: Write an if statement that checks whether the value at that index passes your test.
To test that this step works, you might want to create a separate program that just tests a hardcoded value instead of using arrays.
Step 3: Once you have the first two steps working, then you can save the indexes that pass your test into some kind of data structure. You might us an ArrayList<Integer> for this.
Create a separate example program that just loops over an array without worrying about any logic. Create another separate program that just uses an if statement to test your condition against a hard-coded value. Then if you get stuck on a specific step, you can post a more specific question along with an MCVE. Good luck.
I think it would be simpler for you to store your subject's values as an object of a class. Perhaps store the numerical portion of the ID as an int too? Using a class will enable you to write more human readable code.
public class FoodSubject {
String stringID;
int numID;
String title;
String availability;
public FoodSubject(String stringID, int numID,
String title, String availability) {
this.stringID = stringID;
this.numID = numID;
this.title = title;
this.availability = availability;
}
}
To make a new array of your FoodSubject objects use this code:
FoodSubject[] subjectArray = new FoodSubject[3];
subjectArray[0] = new FoodSubject("CAKE", 100, "Eating Cake And Baking Too", "November");
Access the values like this subjectArray[0].numID
Look into overriding the toString() method in your class to print out all the values of your subject easily. This will help you identify problems in the rest of your code much easier!
If you still want to store the entire ID as a String use the charAt(int index) function to test if the character is a '1'.
This if (units[0][j].substring(4) == "1") { code is incorrect. Look at the String Java documentation for information on what substring does.

How do I use this set method in a loop

This is a homework question so preferably I would like to write as much code as possible, just need a pointer.
I have a class called Sandwich that has a Method to set a main Ingredient and a few other things -
public class Sandwich {
private String mainIngredient, bread;
String getMainIngredient(){
return mainIngredient;
}
void setMainIngredient(String mainIng){
mainIngredient = mainIng;
}
void setBread(String dough){
bread = dough;
}
void setPrice(double cost){
price = cost;
}
Now in another class TestSandwich I've initialized an Array, as part of the question;
Sandwich[] sandwiches = new Sandwich[5];
Now what I need to do is loop through and assign a value to mainIngredient and bread each time.
I think I would want to do something along the lines of this but I'm not really sure how to do it correctly.
for(int i = 0; i < 5; i++){
System.out.println("Insert a main ingredient");
String userInput = sc.next();
sandwiches[i].setBread(userInput);
System.out.println("Insert a bread");
userInput = sc.next();
sandwiches[i].setMainIngredient(userInput);
System.out.println(sandwiches[i].getMainIngredient());
System.out.println("");
}
The main issue is - sandwiches[i].setMainIngredient(userInput);
Im not really experienced with arrays and methods such as these so any help with the correct syntax would be great.
Thanks
Sandwich[] sandwiches = new Sandwich[5]; creates an array of 5 null references.
You need to initialise each element yourself; in your loop write
sandwiches[i] = new Sandwich();
else you'll get NullPointerExceptions. Once you've done that you can call the setting methods as you currently do. Going forward, you could declare a two argument constructor taking the bread and main ingredient as arguments. That's better style since (i) you avoid setters and (ii) the object being in an ill-defined state between construction and use.
Sandwich[] sandwiches = new Sandwich[5];
This allocates an array to hold 5 sandwiches, but it doesn't create any sandwiches. Just the array. You're on the right track to create the sandwiches in a loop.
When you write this loop, instead of iterating until 5, it's better to use sandwiches.length, so that if you want 10 instead of 5 sandwiches, you can change the number in one place instead of 2. It will be safer and less error-prone:
for (int i = 0; i < sandwiches.length; ++i) {
// TODO: get the ingredients from user
// ready to create the sandwich, yum yum
Sandwich sandwich = new Sandwich();
sandwich.setBread("...");
sandwich.setMainIngredient("...");
sandwiches[i] = sandwich;
}

String naming convention in java

I am currently trying to make a naming convention. The idea behind this is parsing.
Lets say I obtain an xml doc. Everything can be used once, but these 2 in the code below can be submitted several times within the xml document. It could be 1, or simply 100.
This states that ItemNumber and ReceiptType will be grabbed for the first element.
ItemNumber1 = eElement.getElementsByTagName("ItemNumber").item(0).getTextContent();
ReceiptType1 = eElement.getElementsByTagName("ReceiptType").item(0).getTextContent();
This one states that it will grab the second submission if they were in their twice.
ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(1).getTextContent();
ReceiptType2 = eElement.getElementsByTagName("ReceiptType").item(1).getTextContent();
ItemNumber and ReceiptType must both be submitted together. So if there is 30 ItemNumbers, there must be 30 Receipt Types.
However now I would like to set this in an IF statement to create variables.
I was thinking something along the lines of:
int cnt = 2;
if (eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();)
**MAKE VARIABLE**
Then make a loop which adds one to count to see if their is a third or 4th. Now here comes the tricky part..I need them set to a generated variable. Example if ItemNumber 2 existed, it would set it to
String ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
I do not wish to make pre-made variable names as I don't want to code a possible 1000 variables if that 1000 were to happen.
KUDOS for anyone who can help or give tips on just small parts of this as in the naming convention etc. Thanks!
You don't know beforehand how many ItemNumbers and ReceiptTypes you'll get ? Maybe consider using two Lists (java.util.List). Here is an example.
boolean finished = ... ; // true if there is no more item to process
List<String> listItemNumbers = new ArrayList<>();
List<String> listReceiptTypes = new ArrayList<>();
int cnt = 0;
while(!finished) {
String itemNumber = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
String receiptType = eElement.getElementsByTagName("ReceiptType").item(cnt).getTextContent();
listItemNumbers.add(itemNumber);
listReceiptTypes.add(receiptType);
++cnt;
// update 'finished' (to test if there are remaining itemNumbers to process)
}
// use them :
int indexYouNeed = 32; // for example
String itemNumber = listItemNumbers.get(indexYouNeed); // index start from 0
String receiptType = listReceiptTypes.get(indexYouNeed);

Changing an array attempt

I posted this question up earlier and it was pretty much a lazy post as I didn't provide the code I had and as a result got negged pretty badly. Thought I'd create a new one of these ....
I have an array dogArray which takes ( name, secondname, dogname )
I want to be able to change the dogname:
here's my attempt :
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
String namgeChange = rp.next(); {
for (int i = 0; i < dogArray.length; i++){
for (int j = 0; j < dogArray[i].length; j++){
if (dogArray[i][j] == name){
dogArray[i][j] = nameChange;
}
}
}
}
For a start it doesn't like the fact I've used ' name ' although it is defined in the dogArray. I was hoping this would read input so that users are able to change 'name' to whatever they input. This will change the value of name in the array.
Do you guys think I'm getting anywhere with my method or is it a pretty stupid way of doing it?
Only one loop is necessary, also move your call to next.
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
for (int i = 0; i < dogArray.length; i++){
String nameChange = rp.next(); {
if(!dogArray[i].name.equals(nameChange)){
dogArray[i].name = nameChange;
}
}
}
You might want to make this function static as well and use accessors and mutators to change and get the name. Might want to tell the user what you want them to type as well. Also there is no point in testing if the name changed, if it changed then set it, if it didnt change then set it (it doesnt hurt). Just get rid of if and keep the code inside.

Categories

Resources