Array help needed - Coding errors - java

I need to implement a method that takes an array called applicants, and two instances from a seperate class called Person, and prints out names of those applicants whose age is between 22 and 30 inclusive. The class Person has methods getName() and getAge() that return the name and the age of the applicant. In other words, the class Person is declared as follows:
public class Person{
public String getName(String name) {
return name;
}
public int getAge(int age){
return age;
}
}
Here is my main method:
public class Applicants
{
public static void main(String args[]){
String [] name = new String[8];
name[0] = "Student A";
name[1] = "Student B";
name[2] = "Student C";
name[3] = "Student D";
name[4] = "Student E";
name[5] = "Student F";
name[6] = "Student G";
name[7] = "Student H";
int [] age = new int[8];
age[0] = 21;
age[1] = 28;
age[2] = 16;
age[3] = 23;
age[4] = 22;
age[5] = 28;
age[6] = 22;
age[7] = 21;
}
public static void printSelection(Person applicants[]) {
for (int i = 0; i < applicants.length; i++)
if (22 <= applicants[i].getAge() && applicants[i].getAge() <= 30)
System.out.println(applicants[i].getName());
}
}
I know I have not prepared an array called applicants (yet). I am not sure how I can basically take these two arrays called names and ages and make the one array called applicants?
Or do I just convert the array names to applicants?
This is a class session so please forgive my errors. I just need to learn how a professional would do this sort of thing so that I may learn from it and move on.
The final output is required to print out the applicant name and age that is between 22 and 30. The getName and getAge must be called from a separate class as shown below.

Firstly, there is no need for two arrays. You can simply create object instances of type Person.
public class Person{
public String getName(String name) {
// Why would the user pass a value they want returned right back to them?
return name;
}
public int getAge(int age){
// Same here as well. This needs to be addressed!
return age;
}
}
Firstly this code will not work. There is no field name and field age in the class. That is your first problem to solve. You also need to make a constructor for this class, that takes name and age as a parameter, and binds them to the fields you have defined. ie:
public Person(int age, String name)
{
this.age = age;
this.name = name;
}
The next step would be to add the values to a person object, then adding that person object to a collection(like an array, or arraylist). In your main method, you might have something like..
Person[] applicants = new Person[8];
Now you should add new instances of the Person object to this collection, with the relevant data.
Pass this array to your function and you will print out the selected values.

Related

Referencing the array variables in the Reference class, sorting it using another method, and invoking the sorted values in the case statement

I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.

Insert two arrays in one using two methods for each array

i want to create 3 arrays with objects.The two arrays(pin and age) i want to put them on one array named Alltogether.I use from each method to return me an array i dont know if this is right i try it.In the end i want to systemout only the array that has all this.
package worklin1;
public class worklin1{
static int N; //from keyboard i have a class userinput
private String Name; // name
private int age; // age
private int costVehicle; //vehicle
public worklin1(){}
public worklin1(String Name, int Age, int cost, String name) {
Name=name;
Age=age;
costVehicle=cost;
}
// Access methods
public String getName(){
return Name;
}
public int getAge(){
return age;
}
public int getcostVehicle(){
return costVehicle;
}
// Mutator methods
public void setName(String name){
Name=name;
}
public void setSurname(String age){
age=age;
}
public void setcostVehicle(int cost){
costVehicle=cost;
}
public String toString() {
String s=name+" "+age+", "+cost+"\t";
return s;
}
public static void main(String[] args){ //main
int[] pin= new int[N]; // the first array
int[] age=new int[]; // the second array.i dont know why it is false this array maybe i use an object as name for an array thats why its false.
Allmethodtogether[] pin = new Allmethodtogether[N]; // Allmethodotogether is an array.It has the combination of age and the cost.The N is just a number i give from keyboard i dont care about this right now.I just wanted to focus on my problem which is how to combine the two methods(which they give me each one 2 arrays and i will add them in this array name Allmethodtogether).
for (int i = 0; i < 10; i++) { // i want to put in an array all the arrays from the methods so i start the counting from 0 until 10.Until the 10 will be saved the pin and after 10 will be saving the array age
Allmethodtogether[i] = new Vehcost();
Allmethodtogether[i+10] = new AllAge();
} //finished //Now i want to display those arrays and i am trying this .
int y; // i create a variable to save my results from the method
y=worklin1.Vehcost(int[] pin); // i take the result from the method Vehcost
System.out.println("Appear all array"+y ); //i want to appear the array.Did i create and an array with objects?
int k; // i do the same thing as the other
k=worklin1.Allage(int[] age);
System.out.println("Appear all array"+k);
} // end main
public static int Vehcost(int[] pin ) { //starting first method 1
int cost = 0;
for(int i =0; i < pin.length; i++) {
cost += pin[i].getcostVehicle();
pin[i]=getname()+ cost; //i want to save to pin the names and the cost of each one
}
return pin[i]; // i want to return the array pin
}//end method 1
public static int allAge(int[] age ) { //second method
if(getage() >18 ){ //if age is >18 only then will going to save on the array
for(int i =0; i < age.length; i++) {
age += age[i].getage();
}
}
return age; // i want to return the array age
}// end method 2
}

How to change the position within the array

I have one class which is called people where I keep track of 50 people, their rank, name, age and order. Then I have a second class called rearrange where I have to change the position of the int order. So it will change up the order, like order 1 which is in position 0, will be moved to position 48th. I need to do the whole thing without using any loop.
class people {
int order[] = new int[50];
for(int j=0; j<order.length; j++) {
order[j] = "order" + j;
System.out.print(order);
}
}
class rearrange {
// In here i need to change the position of the int order, and need to do this without using any loop.
}
Shouldn't rearrange be a method of the people class? Classes are usually created for Nouns, Verbs are usually functions or methods of a class. And wouldn't it be better to have a class "Person" and make an array of 50 of them, and simply change their index to change their order?
Consider something like this:
public class Person //create Person class with the attributes you listed
{
private int rank;
private int age;
private String name;
public Person(int rank, int age, String name) //constructor
{
this.rank = rank;
this.age = age;
this.name = name;
}
}
public class MainClass
{
Person[] people = new Person[50]; //array of Persons, containing 50 elements
public static void main(String[] args)
{
for(int i = 0; i < people.length(); i++)
{
people[i] = new Person(something, something, something); //give all the people some values, you'll have to decide what values you are giving them
}
//do something with the rearrange function here
}
public static void rearrange(int target, int destination) //this is just a "swap" function
{
Person temp = people[destination];
people[destination] = people[target];
people[target] = temp;
}
}

Development of monopoly game

I seem to have a problem with a subtask. It's in danish so I put in the translated version of it:
Create a class Field, that is representing the fields of a monopoly game. Initially, Field can contain these encapsulated variables:
String name - short name of the field
int number - a number in the range[1..40]
Both variables must be initialized in a constructor, and there must only be getters, as they never will be changed after creation.
Moreover, there should be a method with the signature public String toString(), so it's easy to print what Field a player has landed on.
At first it's allowed to just call the fields Field1, Field2...
My Field class look like this:
public class Field {
String name;
int number;
public Field(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
}
In my main method I wanted to test this. So I wrote the following:
Field[] board = new Field[40]; // a board containing 40 fields
for (int i = 0; i < board.length; i++) {
board[i] = new Field("Field" + (i + 1), i + 1);
}
System.out.println("Board: " + Arrays.toString(board));
In my console I get this:
Board: [test.Field#2a139a55, test.Field#15db9742, test.Field#6d06d69c,......]
And I want this:
Board: [Field1, Field2, Field3,......]
Override Field's toString() to return the name, i.e.
public String toString() {
return name;
}
What you get (e.g. test.Field#2a139a55) is the default implementation of toString() which can be found in Object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
You missed the
Moreover, there should be a method with the signatur public String toString(),
part of your task.
Are you able to use java8? Then I would suggest this:
Field[] board = new Field[40]; // a board containing 40 fields
for(int i = 0; i < board.length; i++){
board[i] = new Field("Field" + (i + 1), i + 1);
}
String commaSeparatedName =
Arrays.stream(board) // all items as stream
.map(Field::getName) // for each take its name
.collect(Collectors.joining(", "); // join names with a comma
System.out.println("Board: [" + commaSeparatedNames +"]");

A store that sells one type of item

Okay, I don't know If I wrote a code correctly please check. So I created software for a store that sells one type of item. And each instance of my class should be an item of merchandise my store sells.
For example if my store sells neckties, I would design a necktie class:
class Necktie { …
My class must have five instance variables, including at least one of type integer, at least one of type String and one called price which must be double. Also it should have a toString method that accepts no parameters and returns a description of the item. It should have a constructor. The constructor can take however many parameters you choose, but it must set all instance variables.
• It should contain an accessor method for each instance variable.
• It should contain no unnecessary instance variables. Any information that does not need to be stored in an instance of your class should be stored as local variables.
Here is the code below. (incomplete, because I am kinda stuck..Please check if I did it correctly. If not, then please correct me.)
public class Pets {
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
String color, pattern;
int age, size;
double price;
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
age = age;
size = size;
price = price;
}
public String toString(){ //I don't get this part..
String description;
description = "red";
return description;
}
public String getColor(){
return color;
}
public String getPattern(){
return pattern;
}
public int age(){
return age;
}
public int size(){
return size;
}
public double price(){
return price;
}
}
Where you've written
age = age;
size = size;
price = price;
This is actually not setting the instance variable. You should carry on writing
this.age = age
// etc...
When you write this it tells Java that you're referring to the instance variable, not the local variable
When the main method is called, Java doesn't create an instance of Pets for you. But the rest of your code works on a Pets object, so you'll need to create one somewhere in your main. Thus, instead of:
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
it will be something like
public static void main(String[] args) {
Pets pet = new Pets(........); // creates an instance; you'll need to supply
// the arguments
System.out.print (pet.toString()); // calls toString on this instance
}
That will get past the "cannot make a static reference" error, but there are other problems as described in other answers.
Your main method tries to call a static method toString(), but your toString() method is not static (as it shouldn't be).
For testing purposes, your main method should look like this:
public static void main(String[] args) {
Pets pet = new Pets("red", "plain", 1, 2, 10.25);
System.out.println(pet.toString());
}
In your constructor:
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
this.age = age;
this.size = size;
this.price = price;
}
Your toString() method has a typo in the name. It should probably return a description of the attributes of the instance (not an actual description field). For example:
public String toString() {
StringBuilder description = new StringBuilder("Color: ")
.append(color)
.append(", Pattern: ")
.append(pattern)
.append(", Age: ")
.append(age)
.append(", Size: ")
.append(size)
.append(", Price: ")
.append(price);
return description.toString();
}
Your getters should start with get:
public int getAge(){
return age;
}
public int getSize(){
return size;
}
public double getPrice(){
return price;
}
Edit
At the OPs request:
An alternative toString() method which uses String concatenation (bad) and no special formatting:
public String toString() {
return "Color: " + color + ", Pattern: " + pattern + ", Age: " + age + ", Size: " + size + ", Price: " + price;
}

Categories

Resources