How do I use this set method in a loop - java

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;
}

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.

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.

For Loop Not Terminating

I'm trying to get back into Java - it's been about 5 years since I studied the basics and I've been lost in the .Net world since.
I'm trying to create a student class below, however the for loop for reading in the integers into the array gets stuck when the program runs.
From my previous knowledge, and from research, the loop seems to be constructed properly and I can't seem to figure out where it's going wrong.
I'm sure it's something silly - as always but I was wondering if someone could point me in the right direction? :)
import java.util.*;
import acm.io.*;
public class Student {
// instance variables
private int studNumber; //Must be between (and including) 0 and 99999999. If input value invalid default to 0.
private String studName;
private int marks[];
/*
* Constructor Student Class
*/
public Student(int studNumber, String StudName, int marks[]) {
// initialise instance variables
if (studNumber >=0 && studNumber<= 99999999) {
this.studNumber= studNumber;
} else {
this.studNumber = 0; //default value
}
this.studName= StudName; // no validation
this.marks = marks;
IOConsole console = new IOConsole();
for (int i = 0; i <= 6; i++) {
marks[i] = console.readInt();
}
}
}
I think that the problem lies here:
for (int i = 0; i <= 6; i++)
{
marks[i] = console.readInt();
}
The only instance where I found a reference to IOConsole was here and it does not seem to be something which is part of the standard Java framework.
If you just need to scan numbers from console, you can use the Scanner class and the use the nextInt() method like below:
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 6; i++)
{
marks[i] = input.nextInt();
}
The loop seems correct. Is it possible the console.readInt() call is blocking, which keeps you stuck in the loop (the IOConsole class is not part of the standard JDK, and I am not familiar with it)
readInt() is waiting for user input
from http://jtf.acm.org/javadoc/student/acm/io/IOConsole.html#readInt%28%29:
Reads and returns an integer value from the user
The problem is with console.readInt(), where another non-stop loop is executing or some other problem with that method
I believe the problem lies in the readInt() part. It's unusual to read input from the Console in a constructor for initializing the attributes, delegate that task to another part of your code and move it outside the constructor.

beginner java, help me fix my program?

I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.

Categories

Resources