Getters are not visible in other classes - java

I'm learning Java for a week, and now i have a problem, because i want to print all Arraylist in method printArray, but the method don't see getName() and other methods and I don't know how to solve my problem. Thanks a lot for your help.
If you can, please show my what I;m doing wrong.
Class Positions:
public class Positions {
List<Positions> list = new ArrayList<>(15);
int ageAdd;
int IDAdd;
String nameAdd;
int counter;
String name;
int age;
int ID;
public Positions(String name, int age, int ID) {
this.name = name;
this.age = age;
this.ID = ID;
}
public Positions() {
this("", 0, 0);
}
//there are methods:
//adding element
//removing element
//changing values
//etc
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getID() {
return ID;
}
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.getName(i) + " AGE: " + list.getAge(i) + " ID: " list.getID(i));
}
}
Class main:
public class ArrayList2
{
public static void main (String[] args)
{
Positions p = new Positions();
System.out.println("----LISTA TABLICOWA-----");
System.out.println("Co chcesz wykonać? ");
System.out.println("1. Dodac element do listy. ");
System.out.println("2. Usunac elemnt z listy.");
System.out.println("3. Wstawić na dowolna pozycje.");
System.out.println("4. Rozmiar listy.");
System.out.println("5. Zmienic wartosc na podanym indeksie.");
System.out.println("6. Wyświetlić listę. ");
while(true) {
System.out.println("podaj pozycję: ");
Scanner ch = new Scanner(System.in);
int choice= ch.nextInt();
switch (choice)
{
case 1:
{
p.addPosition(); //?
break;
}
case 2:
{
p.removePosition();
break;
}
case 3:
{
p.setOnAnyPosition();
break;
}
case 4:
{
p.ArraySizeShow();
break;
}
case 5:
{
p.changePosition();
break;
}
case 6:
{
p.printArray();
break;
}
}
}
}
}

You simply have a problem with the array access:
Instead of using:
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.getName(i) ...);
}
}
You should use:
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.get(i).getName() ...);
}
}
because you want to get the name of a specific element, and in OO languages, that usually means calling the method on the object itself.
Ijn your example, you have a list that contains objects that contains a name. So if you want to access the name from the list, you need to first get an element then get his name.
HTH.

Try to change method with below code. Hope it would help.
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.get(i).getName() + " AGE: " + list.get(i).getAge() + " ID: " list.get(i).getID());
}
}

To loop over your list either use
for (int i = 0; i < list.size(); i++) {
Positions p = list.get(i);
System.out.println(i + " : " + " NAME: " + p.getName() + " AGE: " + p.getAge() + " ID: " + p.getID());
}
or
int index =0;
for (Positions p : list) {
System.out.println(index++ + " : " + " NAME: " + p.getName() + " AGE: " + p.getAge() + " ID: " + p.getID());
}

Related

Write search methods in array by Java

I have an array it has (id,name,salary)
I want to search specific ID using Employee search method, my code is:
Employee SearchID(int i_d) {
for (int i = 0; i < staff.length; i++) {
boolean check = true;
if (staff[i].id == i_d) {
System.out.println("Id: " + staff[i].id + ", name: " + staff[i].name + " and salary: " + staff[i].salary);
} else {
System.out.println("Sorry, no record exists with record id = " + i_d);
}
}
return staff[i].id;
}
Your SearchID method returns an Employee object but you return a primitive type. (staff[i].id) You must change return type of your method.
You can fix your method like this:
Employee SearchID(int i_d) {
for (int i = 0; i < staff.length; i++) {
if (staff[i].id == i_d) {
System.out.println("Id: " + staff[i].id + ", name: " + staff[i].name + " and salary: " + staff[i].salary);
return staff[i];
}
}
System.out.println("Sorry, no record exists with record id = " + i_d);
return null;
}
And, of course, you need to handle the null result after calling SearchID properly.

Array values being set for everything (Java)

In my code below, I am having an issue where I add the customer name to one room, but instead it adds the customer to every room. I can't figure out what in my code the issue is. I have tried removing the procedure but that still produced the same problem.
package test;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice, custName = "";
int roomNum = 1;
String[] hotel = new String[12];
String[] customer = new String[12];
hotelInitialise(hotel);
custInitialise(customer);
while ( roomNum < hotel.length-1 ) {
for (int i = 0; i < hotel.length-1; i++) {
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("V: " + "View all rooms\n");
choice = input.next().toUpperCase();
if (choice.equals("A")) {
System.out.println("Enter room number(1-10)");
roomNum =input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
custName = input.next();
addNewBooking(hotel, custName);
System.out.println(" ");
}
if (choice.equals("V")) {
seeAllRooms(hotel, custName);
}
}
}
}
// When the program loads it will assign all the values of the array as being empty
private static void hotelInitialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++){
hotelRef[x] = "Room " + x + " is empty.";
}
System.out.println( "Welcome to the Summer Tropic Hotel.\n");
}
private static void custInitialise (String custRef[]) {
for (int i = 0; i < 11; i++) {
custRef[i] = ", no customer has occupied this room";
}
}
private static void addNewBooking(String hotel[], String customer) {
for (int x =1; x <11; x++) {
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
System.out.println("Room " + x + " is empty.");
else {
System.out.println("Room " + x + " is occupied by "+ customer);
}
}
}
private static void seeAllRooms(String hotel[], String customer) {
for (int i = 0; i < hotel.length-1; i++) {
int j=0;
String custName = customer;
hotel[j]= custName;
if (hotel[i].equals("Room " + i + " is empty."))
System.out.println("Room " + i + " is empty.");
else {
System.out.println("Room " + i + " is occupied by "+ hotel[j] + ".");
}
}
}
}
In addNewBooking method you have this line:
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
However hotel[x] has a value of "Room x is empty" e.g. hotel[1] is "Room 1 is empty" So the final check is becoming "hotel[x].equals(Room Room x is empty is empty.)" which is never equals to your hotel[x]
You have to change your code to
if (hotel[x].equals("Room " + x + " is empty."))
//do something there like add the booking

Trouble linking the correct items to the correct owner in a registry

I’m working on a registry for persons and their belongings. This program is command based and therefore has some different functions. My problem here is that when the command ”show richest person" is performed, incorrect belongings of the calculated person are printed. The person and the total value of this owner’s items are correct; only the list of gadgets seem to be mixed up with someone else’s. This is how the code looks like:
public void getRichest() {
double maxValue = -1;
ArrayList<Person> richestPersons = new ArrayList<Person>();
for (int i=0; i<personRegistry.size(); i++) {
double totalValue = personRegistry.get(i).getTotalValue();
if (totalValue > maxValue) {
maxValue = totalValue;
richestPersons = new ArrayList<Person>();
richestPersons.add(personRegistry.get(i));
} else if (totalValue == maxValue)
richestPersons.add(personRegistry.get(i));
}
System.out.print("The richest person is ");
for (int i=0; i<richestPersons.size();i++) {
System.out.print(richestPersons.get(i).getName() + " ");
}
System.out.println("with the total value " + maxValue);
for (int i=0; i<richestPersons.size();i++) {
String name = richestPersons.get(i).getName();
ArrayList<Item> items = personRegistry.get(i).getItems();
// I GUESS THE PROBLEM STARTS HERE...
System.out.println(name + " owns the following items:");
for (int j=0; j<items.size(); j++) {
String itemName = items.get(j).getName();
double itemValue = items.get(j).getValue();
System.out.println(itemName + " " + itemValue + " ");
}
}
}
The described problem only occurs in the execution of this command and no other. For example, If I perform a command called ”show information about specific person” and select the same person (the richest) the belongings of this person will now be correct. The code is almost identical with the earlier shown:
}
public void search(String name) {
for (int i=0; i<personRegistry.size(); i++) {
if (name.equalsIgnoreCase(personRegistry.get(i).getName())) {
String foundName = personRegistry.get(i).getName();
double totalValue = personRegistry.get(i).getTotalValue();
System.out.println(foundName + " has a total value of " + totalValue + " ");
System.out.println(foundName + " owns the following items:");
ArrayList<Item> items = personRegistry.get(i).getItems();
for (int j=0; j<items.size(); j++) {
String itemName = items.get(j).getName();
double itemValue = items.get(j).getValue();
System.out.println(itemName + " " + itemValue + " ");
}
return;
}
}
System.out.println("Error: Could not find the person you were searching for.");
}
I’ve tried to figure this out (for example, I've tried copy-paste the latter code into the "getRichest"), but I would really appriciate some help!
If you're simply trying to print out only the richest person and their belongings, you should use:
Person richest = new Person(/*Any default initializers here*/);
// This will set 'richest' to the richest person
for (Person p : personRegistry) {
if (p.getValue() > richest.getValue())
richest = p;
}
System.out.println("Richest person is: " + richest.getName());
System.out.println("Total value: " + richest.getTotalValue());
System.out.println(richest.getName() + " owns: ");
for (Item i : richest.getItems()) {
System.out.println(i.getName() + " " + i.getValue());
}
If you wish to hold duplicates (that is, Person objects with the same totalValue),
ArrayList<Person> richestPeople = new ArrayList<Person>();
Person richest = new Person(/*Any default initializers here*/);
for (Person p : personRegistry) {
if (p.getValue() > richest.getValue())
richest = p;
}
// now check to see if there are people with same value
for (Person p : personRegistry) {
if (p.getValue() == richest.getValue())
// add them to the list
richestPeople.add(p);
}
// now we loop through the list of richest people and print them out
for (Person p : richestPeople) {
System.out.println("Richest person is: " + p.getName());
System.out.println("Total value: " + p.getTotalValue());
System.out.println(p.getName() + " owns: ");
for (Item i : p.getItems()) {
System.out.println(i.getName() + " " + i.getValue());
}
}

For loop populates whole instead of one instance

I'm creating a booking system in Java to prevent double bookings i have created a for loop that should change a Boolean to booked once the booking is made however it is changing all the bookings to booked when i only want one instance of booking so no one else can make a booking.
public static boolean booked;
private void FSubmitActionPerformed(java.awt.event.ActionEvent evt) {
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}
You have not put any condition to check, how a particular seat will be set selected.
So you will need to modify your code as:
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
if(your_condition_to_check_if_this_seat_is_selcted ){
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
}
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}

Issue using methods and an array

My problem here is displaying the data using another method. I tried both of the methods but there was no output.
I think that objects in the ArrayList are gone when I made them as parameters on both methods or maybe not.
Please kindly help me with this problem of mine. There are still more options to be filled, I also need some help for it.
public class Student {
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student() {
this.IDNumber = IDNum;
this.firstName = fName;
this.middleName = mName;
this.lastName = lName;
this.degree = deg;
this.yearLevel = level;
}
public void setIdNumber(String IDNumber) {
this.IDNumber = IDNumber;
}
public String getIdNumber() {
return IDNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getMiddleName()
{
return middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getDegree() {
return degree;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
public int getYearLevel() {
return yearLevel;
}
/* #Override
public String toString(){
return ("ID Number: "+this.getIdNumber()+
"\nName: "+ this.getFirstName()+
" "+ this.getMiddleName()+
" "+ this.getLastName()+
"\nDegree and YearLevel: "+ this.getDegree() +
" - " + this.getYearLevel());
} */
}
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("****STUDENT RECORD SYSTEM****\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1) {
options();
}
else if (choice == 2) {
displayAll(student, studentList);
}
else if (choice == 3) {
displaySpecific(student, studentList);
}
}
public static void options() {
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
char ans;
String temp;
int total;
do {
System.out.println("TOTAL: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("*********STUDENT INFORMATION*********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out
.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
// SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
menu();
}
public static void displayAll(Student student,
ArrayList<Student> studentList) {
System.out.printf("STUDENT RECORD");
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
}
public static void displaySpecific(Student student,
ArrayList<Student> studentList) {
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
}
}
Move
ArrayList <Student> studentList = new ArrayList <Student>();
from options method to class field.
EDIT:
As you can see, now studentList is not a local variable of
public static void options()
but of the class.
Anyway i edited the args of some methods because you don't need to pass students as argument since now it's a field of the class.
import java.util.ArrayList;
import java.util.Scanner;
public class test {
static ArrayList<Student> studentList = new ArrayList<Student>();
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("****STUDENT RECORD SYSTEM****\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1) {
options();
}
else if (choice == 2) {
displayAll();
}
else if (choice == 3) {
displaySpecific(student);// here you should ask to the user what studend he want to show - here it continues to give you error
}
}
public static void options() {
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("TOTAL: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("*********STUDENT INFORMATION*********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out
.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
// SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
menu();
}
public static void displayAll() {
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
}
public static void displaySpecific(Student student) {
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
}
}

Categories