<identifier> expected when creating an array? - java

I am writing an airline program that will allow the user to input names and meal choice for each seating section economy, business, and first. I am trying to save all the names and meals into an array. but I am getting a syntax error.
I get expected message when I implement my flyer array.
I have looked on stack overflow. From what I can tell it should be ok to initialize my array this way.
Thanks for any help.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Flyers
{
public Flyers()
{
}
public List<String> seat = new ArrayList<>();
int numberOfFlyers;
int numberOfMeals;
String name;
String meal;
String[][] flyer;
public void addEconomyFlyer()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
numberOfFlyers = in.nextInt();
flyer = new [numberOfFlyers][numberOfFlyers];
}
}

I want each [][] to have the same number of items that is equal to the number of people on the plane. Then I will add a nested for loop that will add a name for each of the flyers, and a meal choice. ultimately i need to be able to print out the array Name and their Meal choice.
Almost, the issue here is you haven't specified a type for the array.
flyer = new [numberOfFlyers][numberOfFlyers];
should probably be
flyer = new String[numberOfFlyers][numberOfFlyers];
However that doesn't make a lot sense. One solution is to use,
flyer = new String[numberOfFlyers][2];
where 0 is name and 1 is meal. But, really you should probably have a flyer POJO,
flyer = new Flyer[numberOfFlyers];
Where Flyer might look something like,
class Flyer {
Flyer(String name, String mealType) {
this.name = name;
this.mealType = mealType;
}
String name;
String mealType;
public String toString() {
return "Name: " + name + ", Meal: " + mealType;
}
}
Then you can create new Flyer(s) and call toString() in your loop. You might also choose to add getter and setter functions for name and mealType.

change :
flyer = new [numberOfFlyers][numberOfFlyers];
to:
flyer = new String[numberOfFlyers][numberOfFlyers];

Scanner class
Scan.scanner.scan
You need scan it!!!!
identifier = here
This trickes computer in think identifier there! YES! WORK!

Related

How to do linearSearch to two ArrayList<String>?

I received a homework assignment to create a shopping list program where it will ask the user for a list of ingredients, and after the user enters them, it will compare the inputs to a "pantry list" to see if everything is available. If yes, then it will print out "You got everything you need!" and if no, it will print out "You still need" + "item that is missing." The specific instructions are:
A pre-created list for pantry items
User input into an ingredient list
Pass the ingredient list to a method
Use a conditional and loop in the method
Print out the results of whether the user needs to go shopping based on the items in the ingredient list that are not in the pantry.
Below is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class TheList
{
public static String linearSearch(ArrayList<String> pantry, ArrayList<String> input)
{
for (int i = 0; i < pantry.size(); i++)
{
if (pantry == input)
{
return "You got everything you need!";
}
}
return "You still need something!";
}
public static void main(String[] args)
{
// Create list for pantry items
ArrayList<String> pantry = new ArrayList<String>();
pantry.add("Bread");
pantry.add("Peanut Butter");
pantry.add("Chips");
pantry.add("Jelly");
//Create list for input items
ArrayList<String> input = new ArrayList<String>();
input.add("ingredientOne");
input.add("ingredientTwo");
input.add("ingredientThree");
input.add("ingredientFour");
// Execution
input();
System.out.println(linearSearch(pantry, input));
}
private static void input()
{
Scanner ingredientScan = new Scanner(System.in);
System.out.println("Please enter an ingredient: ");
String ingredientOne = ingredientScan.nextLine();
System.out.println(ingredientOne + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientTwo = ingredientScan.nextLine();
System.out.println(ingredientTwo + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientThree = ingredientScan.nextLine();
System.out.println(ingredientThree + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientFour = ingredientScan.nextLine();
System.out.println(ingredientFour + " Done.");
}
}
What am I missing? This is pretty amateur, but I am a beginner and really need some help!
My main question is the if part for the loop in the linearSearch string. When I execute the program, it always print out "You still need something!" As for which thing is missing, I have no clue where to start in that aspect.
I am assuming by linear search you mean searching if the pantry has everything in one pass.
For scenarios such as these using a Set is the best option because in a set you can search for a key in constant time.
private void search(Set<String> pantry,Set<String> ingredients){
for(String ingredient : ingredients){
if(!pantry.contains(ingredient)){
System.out.println("Something is missing");
return;
}
}
System.out.println("Everything is available");
return;
}
//Create a set like this
public void main(){
Set<String> pantry = new HashSet<>();
}
The answer is not hard, and since it's an assignment, maybe you need some advice:
The loop in the code is not utilized.
Also objects can't be compared using ==, it can only be compared using equals and in general you need to rewrite it.
Your problem is not that you need to use equals to compare, but that you need to do difference sets

How do I find the smallest variable from a list of objects? (JAVA)

The code doesn't show any errors. However, I am getting an unexpected output. I am supposed to get the smallest number for age, but what I keep getting is the last value entered for age. Can you help me point out the mistakes in this code?
Maybe there is some logical error in the getYoungestPet() method?
package pet;
public class Pet
{
public static String petName;
public static int petAge, petWeight;
int youngestAge=9999;
static int test;
public static String setPetName()
{
return petName;
}
public int setPetAge()
{
return petAge;
}
public int setPetWeight()
{
return petWeight;
}
public int getYoungestPet() //probably an error here..?
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
}
package pet;
import java.util.Scanner;
public class PetMain extends Pet
{
public static void main(String[] args)
{
System.out.println("How many pets do you want to enter? " );
Scanner data= new Scanner(System.in);
int petNumber=data.nextInt();
for (int i = 1;i<=petNumber; i++)
{
Pet PetObject = new Pet();
System.out.println("Please enter name for Pet " + i );
Scanner input = new Scanner(System.in);
petName= input.next();
System.out.println("Your pet's name is : " + petName);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Age" );
petAge= input.nextInt();
System.out.println("Your pet's age is : " + petAge);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Weight" );
petWeight= input.nextInt();
System.out.println("Your pet's weight is : " + petWeight);
System.out.println(" ");
System.out.println(PetObject.getYoungestPet());
}
}
}
The code is supposed to show the smallest age but it shows the latest entered age.
you should declare youngestAge as static variable. so that all of the petObject could share the same value.
static int youngestAge=9999;
your setter and getter methods are also not proper.
public static String setPetName()
{
return petName;
}
should be:
public static void setPetName(String name)
{
petName=name;
}
Also don't forget to set values into PetObject from main method.
...
petName= input.next();
PetObject.setPetName(petName);
...
There are many things that are problematic with this code.
But just to answer your question directly, think about how many pet objects there could be in this program if every time the for loop runs it recreates the pet object because it is inside the for loop.
however, simply moving it outside the for loop will not help because then you will simply keep resetting the values of the same pet object every time you run the for loop.
Consider making an array of pet objects.
Also, your code never actually accesses the pet objects instance variables
In addition, there are other problems with your use of static as others have pointed out.
cheers.
Each time you are creating a Pet, you are getting a different youngestAge with value 9999 for that object. So each time it is comparing the latest petAge with 9999 and giving you the latest petAge as your enterd petAge is less than 9999.
If you need to store the smallest age, then keep it in a static field. Cause, keeping an extra field to store the smallest age for all object is redundant for memory.
If you want your desired output with the existing design, then do this:
Make youngestAge static:
static int youngestAge=9999;
And also don't forget to make the method static too. There is no need to make it object property anymore, both the field variables, it is using, are static.
public static int getYoungestPet()
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}

Finding specific instance of class? [duplicate]

This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 5 years ago.
I've just started learning java and I'm trying to create an application to register students.
Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.
public class RegStudent {
ArrayList<Student> studentList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void reggaStudent(int start) {
while (start != 0) {
String programNamn, studNamn;
int totalPoint, antalKurser;
System.out.println("Vad heter programmet?");
programNamn = input.nextLine();
System.out.println("Vad heter studenten");
studNamn = input.nextLine();
System.out.println("Hur många poäng har studenten?");
totalPoint = input.nextInt();
System.out.println("Hur många kurser är studenten registrerad på?");
antalKurser = input.nextInt();
// Add student to list of students
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
System.out.println("Vill du registrera in en fler studenter? "
+ "Skriv 1 för ja och 0 för nej");
start = input.nextInt();
input.nextLine();
} // End of whileloop
}
}
The class is:
public class Student {
private int totalPoint;
private int antalKurser;
private String programNamn;
private String studNamn;
private static int counter;
public Student(int totalPoint, int antalKurser, String program, String studNamn) {
this.totalPoint = totalPoint;
this.antalKurser = antalKurser;
this.programNamn = program;
this.studNamn = studNamn;
counter++;
}
public int getTotalPoint() {
return totalPoint;
}
public void setTotalPoint(int totalPoint) {
this.totalPoint = totalPoint;
}
public int getAntalKurser() {
return antalKurser;
}
public void setAntalKurser(int antalKurser) {
this.antalKurser = antalKurser;
}
public String getProgramNamn() {
return programNamn;
}
public void setProgramNamn(String programNamn) {
this.programNamn = programNamn;
}
public String getStudNamn() {
return studNamn;
}
public void setStudNamn(String studNamn) {
this.studNamn = studNamn;
}
public static int getCount(){
return counter;
}
#Override
public String toString() {
return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
+ "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
}
}
How do I go about to get and set the instance variables in specific instance? I.e find the instances.
I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.
I've added a counter just to see I actually created some instances of the class.
You simply query objects for certain properties, like:
for (Student student : studentList) {
if (student.getProgramName().equals("whatever")) {
some match, now you know that this is the student you are looking for
In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.
Alternatively, you could "externalize" a property, and start putting objects into maps for example.
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
You now have your Student objects in a list. I assume you have something like
List<Student> studentList = new ArrayList<>();
somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?
Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.

Display multiple Array Lists from another class

In our current chapter we are using arrays which I'm having some trouble creating a listing to be called upon from another class.
Goal: Display the parallel arrays from another class, this can be singular or in a group.
Question: Best or efficient way to call on a multi-parallel array with different data types?
Error: Starts with an illegal statement, as previously instructed here is the whole code, please ignore the loop display I was just testing to make sure the arrays were setup correctly.
Thanks Everyone, Yet again any assistance is much appreciated
import java.util.ArrayList;
public class Employee {
public static void main(String[] args) {
// create an array with employee number, first name, last name, wage, and Skill
int[] empID = {1001, 1002, 1003};
String[] firstName = {"Barry", "Bruce", "Selina"};
String[] lastName = {"Allen", "Wayne", "Kyle"};
double[] wage = {10.45, 22.50, 18.20};
String[] skill = {"Delivery Specialist", "Crime Prevention", "Feline Therapist"};
/*
for ( int i = 0; i < empID.length; i++ )
{
System.out.print( "Employee ID: " + empID[i] + "\n");
System.out.print( "First Name: " + firstName[i] + "\n");
System.out.print( "Last Name: " + lastName[i] + "\n");
System.out.print( "Hourly Wage: $" + wage[i] + "\n");
System.out.print( "Skill: " +skill[i] );
System.out.println("\n");
}
*/
//create an object to be called upon from another class
public ArrayList<int, String, String, double, String> getEmployee() {
ArrayList<int, String, String, double, String> employeeList = new ArrayList<int, String, String, double, String>();
employeeList.add(empID);
employeeList.add(firstName);
employeeList.add(lastName);
employeeList.add(wage);
employeeList.add(skill);
return employeeList;
}
}
} //end of class
First, you can't declare an ArrayList like this:
ArrayList<int, String, String, double, String>
If you want that, you can create your own object, create a class which can take these values, then you can create an ArrayList of this Object for example:
class MyClass{
int att1;
String att2;
String att3;
double att4;
String att5;
public MyClass(int att1, String att2, String att3, double att4, String att5) {
this.att1 = att1;
this.att2 = att2;
this.att3 = att3;
this.att4 = att4;
this.att5 = att5;
}
}
Then you can create an ArrayList like this :
List<MyClass> list = new ArrayList<>();
Going back to the basics of Java, it is an object oriented programming language so you should always aim to abstract "things" into an object if possible. You should encapsulate all of the common properties about an 'employee' into a class with all of the data as fields.
As the answer above shows, creating an ArrayList<MyClass> is the proper way of initialising arraylists as they can only take ONE type of data. You may have seen other classes take multiple types such as HashMap<Type1, Type2> but these are for a specified reason. Make sure to check the API doc first!

Using a class to store information and calling that to build an array

So here is my questions. I am working on building an array using a defined class. The class looks like below:
class InventoryItem {
String ItemName;
int ItemNumber;
int InStock;
double UnitPrice;
double InventoryValue;
public InventoryItem(String ItemName, int ItemNumber, int InStock, double UnitPrice) {
this.ItemName = ItemName;
this.ItemNumber = ItemNumber;
this.InStock = InStock;
this.UnitPrice = UnitPrice;
this.InventoryValue = UnitPrice * InStock;
}
public void output() {
System.out.println("Item Name = " + ItemName);
System.out.println("Item Number = " + ItemNumber);
System.out.println("In Stock = " + InStock);
System.out.println("Item Price = $" + UnitPrice);
System.out.println("Item value of stocked items = $" + InventoryValue);
}
}
This works just fine when I load it with a test example.
However when I try to build the array using this class something breaks.
import java.util.*;
public class Inventory {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("Welcome to the inventory program\n")
System.out.println("This will help keep track of your inventory of office supplies");
InventoryItem[] Stock;
InventoryItem[10] = Stock;
Stock[1] = new InventoryItem("Test", 123456, 500, .99);
System.out.println("Please enter the Item Nmae");
ItemName = user_input.nextline();
the problem I am having is that it doesn't like the InventoryItem[] Stock; It keeps telling me that it cannot find InventoryItem. I thought that I could use this class as the array basically. I think that I am asking the right questions, but I am new to this so please bear with me. BTW this test example does not work. However this is the initial test example.
public static void main(String[] args) {
InventoryItem Stock = new InventoryItem("TEST", 123456789, 999, 1.25);
Stock.output();
Which works fine to load that one line, but I am working towards having the user input each section of the array in order to load it up. Does that make sense or do I just sound like an idiot? I am not great with the terminology, but I am working on it. Any help would be appreciated.
InventoryItem[] Stock;
InventoryItem[10] = Stock;
Should be
InventoryItem[] Stock = new InventoryItem[10];
Also, I see you doing this (which probably doesn't cause a problem, but just an FYI in case you don't know.
Stock[1] = new InventoryItem("Test", 123456, 500, .99);
Arrays' indices are zero-based, meaning that start at 0. So if you're trying to access the first index with the code above, you're actually accessing the second index.
Use new to allocate space for your Stock array of InventoryItem
InventoryItem[] Stock = new InventoryItem[10];
Also, I notice you are using array index 1 to add something to your Stock:
Stock[1] = new InventoryItem("Test", 123456, 500, .99);
This is fine, but if you want it to be in the first position, know that Java arrays are zero based.
See Oracle's tutorial on Java arrays for more information.
Use this instead of brackets:
ArrayList<InventoryItem> Stock = new ArrayList<InventoryItem>();
adding items:
Stock.add(new InventoryItem(/*parameters*/);
You can find the rest of the methods you can use here

Categories