Issue adding elements to an ArrayList from a different class - java

Is it possible to do such a thing? Say I wanted to add the values I gave values to in CountriesTest and add them to the ArrayList in Countries. Also how could I reference aCountries to print for option 2, seeing that I created it inside option 1 I can't access it anywhere else.
Here is my interface
public interface CountriesInterface
{
public String largestPop();
public String largestArea();
public String popDensity();
}
Here is the Countries class
import java.util.*;
public class Countries implements CountriesInterface
{
private final List<CountriesInterface> theCountries = new ArrayList<>();
private String cName;
private String finalPopName;
private String finalAreaName;
private String finalDensityName;
private int cPop = 0;
private int cArea = 0;
private int popDensity = 0;
private int popCounter = 0;
private int areaCounter = 0;
private int densityCounter = 0;
public Countries(String cName, int cPop, int cArea, int popDensity)
{
this.cName = cName;
this.cPop = cPop;
this.cArea = cArea;
this.popDensity = popDensity;
}
public String largestPop()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cPop > popCounter)
{
popCounter = cPop;
finalPopName = cName;
}
}
return finalPopName;
}
public String largestArea()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cArea > areaCounter)
{
areaCounter = cArea;
finalAreaName = cName;
}
}
return finalAreaName;
}
public String popDensity()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(popDensity > densityCounter)
{
densityCounter = popDensity;
finalDensityName = cName;
}
}
return finalDensityName;
}
}
Here is the CountriesTest class
import java.util.*;
public class CountriesTest
{
public static void main(String[] args)
{
int population = 0;
int area = 0;
int density = 0;
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1. Enter a country \n2. Print countries with the largest population, area, and population density \n3. Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter name of country: ");
String input1 = myScanner.nextLine();
System.out.print("Enter area of country in square kilometers: ");
String input2 = myScanner.nextLine();
population = Integer.parseInt(input2);
System.out.print("Enter population of country: ");
String input3 = myScanner.nextLine();
area = Integer.parseInt(input3);
density = population/area;
Countries aCountries = new Countries(input1, population, area, density);
}
else if(choice == 2)
{
System.out.println("The country with the largest population: " );
System.out.println("The country with the largest area: " );
System.out.println("The country with the largest population density is: " );
}
else if(choice == 3)
{
done = true;
}
else
System.out.println("Invalid Choice");
}
while (!done);
System.exit(0);
}
}

OK, there's some mix-up in your code.
You are using the "Countries" class at the same time for an individual Country AND the list of countries. I won't recommand it, but at least you should make "static" members and methods which are for the list of countries. Or you could declare List theCountries = new ArrayList<>(); inside the main method instead.
You are never adding the new "Countries" object to the list of countries. So, if you've declared theCountries in the main method, just uste "theCountries.add(aCountries)" right after the "new Countries(...)".
your seach methods (like largestPop) won't work because they are never searching through the content of the "theCountries" ArrayList. (the "i" variable is just iterating through the indices, but never actually used to get a countent from this ArrayList).
and btw, System.exit(0) is not needed (it's implied)

Related

Reading from keyboard to build a relationship between objects

I want to create an object named "Course", and get the information from the keyboard. The last attribute called the "pre", which means the prerequisite courses of this course. I want to input the whole information in one line and extract the information for each attribute. But I got the problem with"pre". I run the program and the output of course.pre is null. I do not know why. Here is my Course class code:
`import java.util.HashSet;
public class Course{
private String name;
private int isFall;
private int NumPre;
private HashSet<Course> pre;
public Course(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String setName (String n){
return name = n;
}
// 1 - fall 0 - both -1 - spring
public void setType(String isFall) {
if(isFall.equals("F") || isFall.equals("f")){
this.isFall = 1;
}else if(isFall.equals("S") || isFall.equals("s")){
this.isFall = -1;
}else if(isFall.equals("B") || isFall.equals("b")){
this.isFall = 0;
}
}
public int getType(){
return isFall;
}
public void SetNumPre(int n) {
this.NumPre = n;
}
public int getNumPre() {
return NumPre;
}
public void addPre(Course c) {
pre.add(c);
}
public HashSet<Course> getPre() {
return pre;
}
}
`
And here is my main method here:
import java.util.*;
public class TimeToGraduate {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
//System.out.print("Input first two integers here: ");
String globalInfo = scanner.nextLine();
String[] numOfCourse = globalInfo.split(" ");//[0] num of total course [1] max num per semester
int totalNum = Integer.parseInt(numOfCourse[0]);
int maxPre = Integer.parseInt(numOfCourse[1]);
Course courses[] = new Course[totalNum];
//System.out.print("Please input course list here: ");
String coursesList = scanner.nextLine();
String[] nameOfCourse = coursesList.split(" ");
for(int i = 0;i < totalNum; i++){
courses[i] = new Course(nameOfCourse[i]);
}
//System.out.print("Please input course info here: ");
for(int i = 0;i < totalNum; i++){
String courseInfo = scanner.nextLine();
String[] infoOfCourse = courseInfo.split(" ");
courses[i].setName(infoOfCourse[0]);
courses[i].setType(infoOfCourse[1]);
courses[i].SetNumPre(Integer.parseInt(infoOfCourse[2]));
if(courses[i].getNumPre() > 0){
for(int j = 3; j < 3+(courses[i].getNumPre()); j++){
for(int k = 0; k < totalNum; k++){
if(infoOfCourse[j] == courses[k].getName()){
courses[i].addPre(courses[k]);
}
}
}
}
}
scanner.close();
for(int m = 0; m < totalNum; m++){
System.out.print(courses[m].getName()+" ");
System.out.print(courses[m].getType()+" ");
System.out.print(courses[m].getNumPre()+" ");
System.out.print(courses[m].getPre()+" ");
System.out.println();
}
}
}
Notice that you did not initilize the pre attribute. That is why it is null.
It would be a good practise if you initilize the pre inside a constructor for the Course class. Otherwise, do it when you start filling the Course attributes.
Update:
Your constructor should be like this:
public Course() { this.pre = new HashSet()}
As you can see the constructor does not have any arguements, because you will be filling its attribute from the main function.
You can define a constructor with arguments too:
public Course(String name, HashSet<Course> pre)
{ this.name = name; this.pre = pre; }
But you will need to initilize pre and name when you call it from the main:
...
HashSet hs = new HashSet();
course[i] = new Course('course_name', hs);
....

Values not printed out when using Comparator to sort ArrayList

I'm working on a program where I'm inputting values(String and int) into arrays, putting those values into an objects which go into an array list to be sorted by the the int value. When I run the program though, it prints out:
Sorted List Entries:
Item Name:null---Quant:0
Item Name:null---Quant:0
Item Name:null---Quant:0 //etc..
I'm trying to learn on my own here but I'm not sure what to do.
My main class:
import java.io.*;
import java.util.*;
public class InputItem
{
public static void main(String args[])
{
String again;
String names[] = new String[100];
int quant[] = new int[100];
int row=0;
do{
System.out.println("Please input assignment name:");
Scanner newName = new Scanner(System.in);
String name = newNamet.next();
names[row] =name;
System.out.println("Please input assignment quant:");
Scanner quantI = new Scanner(System.in);
int quantity = quantI.nextInt();
quant[row] = quantity;
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
Scanner input = new Scanner(System.in);
again = input.next();
row++;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work.add(new Items((names[row]),(quant[row])));
}
Collections.sort(work, new MyComp());
System.out.println("Sorted List Entries: ");
for(Items e:work)
{
System.out.println(e);
}
}
}
Class with Comparator:
import java.util.*;
class MyComp implements Comparator<Items>
{
#Override
public int compare(Items e1, Items e2)
{
if((e1).getQuant()< (e2).getQuant())
{
return 1;
}
else
{
return -1;
}
}
}
public class Items
{
private String name;
private int quant;
public Items(String n, int q)
{
this.name = n;
this.quant = q;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getQuant()
{
return quant;
}
public void setQuant(int quant)
{
this.quant = quant;
}
public String toString()
{
return "Item Name:" + this.name+"---Quant:" +this.quant;
}
}
The problem is here...
for (int count = 0; count < row; count++) {
work.add(new Items((names[row]), (quant[row])));
}
You're using row, which was defined in the previous section of code to keep track of which element you were updating, but is now pointing to the next element in the array (or an empty element). This basically means you are constantly adding the same (empty) values to your Items
Instead, you should be using count
for (int count = 0; count < row; count++) {
work.add(new Items((names[count]), (quant[count])));
}

Sorting a class array in Java?

I'm making a number guessing game for a school project in Java, which I'm extremely bad at. I've got everything to work with classes and the guessing part, but now I'm going to create a top players list and sort it and I have no idea how.
This is the code I use for guessing and creating objects of the player.
public static void spela() {
int nummer= ((int) (1+Math.random()*100));
Scanner input = new Scanner(System.in);
Scanner s_input = new Scanner(System.in);
boolean ratt = false;
int forsok = 1;
int gissning;
String namn;
while(ratt==false) {
System.out.println("Gissa nummer: ");
gissning = input.nextInt();
if(gissning == nummer) {
System.out.println("Grattis du gissade rätt! Tog: " + forsok + " försök att gissa rätt!");
System.out.println("Skriv in namn: ");
namn = s_input.nextLine();
for(int i=0;i<cr;i++) {
if(namn.equals(allaspelare[i].namn)) {
allaspelare[i].setpoang(forsok);
ratt=true;
menu();
}
}
allaspelare[cr] = new spelare(namn);
allaspelare[cr].setpoang(forsok);
cr++;
ratt=true;
menu();
}
if(gissning > nummer) {
System.out.println("Du gissade: " + gissning + " och det var för mycket!");
}
if(gissning < nummer) {
System.out.println("Du gissade: " + gissning + " och det var för lite!");
}
forsok++;
}
}
this is the "spelare" class:
public class spelare {
int[] poang = new int[100];
int antal;
String namn;
public spelare(String innamn) {
namn = innamn;
}
public void setpoang(int inpoang) {
poang[antal] = inpoang;
antal++;
}
}
as you see one player can have multiple scores so that's the problem I can't get it right in my mind how I'm going to sort it so the output if I wan't to get out the score chart will come like:
testplayer1: 9
testplayer2: 11
testplayer3: 34
So basically I need help to code a method that goes through the class and sort it and output it as above! Any help/sources is extremely appreciated!
And commented code would be extremely appreciated so I can learn!
EDIT:
I've been searching for hours, and the only thing that I found was this:
public static void sortera(int[] lista, int plats) {
int i;
if (lista.length < 2) return;
int temp;
for(int n=1; n<lista.length; n++) {
temp=lista[n];
i = n - 1;
while(i >=0 && lista[i] > temp) {
lista[i+1] = lista[i];
}
lista[i+1] = temp;
}
allaspelare[plats].poang = lista;
}
And this is how I called it:
case 5:
sortera(allaspelare[0].poang, 0);
break;
but this doesn't do anything..
The structure you use is simply bad. Instead you should use pairs of names and scores. This way multiple scorepairs with the same name exist, but you can easily sort them.
public class Score implements Comparable<Score>{
private int score;
private String name;
public Score(String name , int score){
this.score = score;
this.name = name;
}
//getters and setters as required
public int compareTo(Score s){
return score - s.score;
}
}
This aswell allows you to directly compare Scoreobjects to eachother. This way a list of Score objects can easily be sorted via Collections.sort(someList).

Variables used in my method are showing errors and are unresolved

So, i was using some variables in my methods but I get errors and I dont know how to fix this heres my code from my first class:
import java.util.Scanner;
public class Gerbilfood {
public static void main(String[] args) {
Gerbil[] gerbil;
Scanner scanner = new Scanner(System.in);
System.out.println("Please input how many types of food items the gerbils eat as an integer");
String n0 = scanner.nextLine();
int n1 = Integer.parseInt(n0);
String[] food = new String[n1];
for (int i = 0; i < n1; i++) {
System.out.println("Please enter a food name");
String n2 = scanner.nextLine();
food[i] = n2;
int[] maximum = new int[n1];
System.out.println("Please enter maximum amount of food per day");
String n33 = scanner.nextLine();
int n3 = Integer.parseInt(n33);
maximum[i] = n3;
}
System.out.println("Please enter in the number of gerbils in the lab");
String n73 = scanner.nextLine();
int n4 = Integer.parseInt(n73);
gerbil = new Gerbil[n4];
int[] combo = new int[n4];
String[] ids = new String[n4];
for (int i = 0; i < n4; i++) {
Gerbil g = new Gerbil(n1);
System.out.println("Please enter in the lab id for each gerbil");
String n5 = scanner.nextLine();
g.setId(n5);
//ids[i] = n5;
//String[] names = new String[n4];
System.out.println("Please enter in the name of each gerbil");
String n6 = scanner.nextLine(); // gerbil name
g.setName(n6);
String[] amountfood = new String[n1];
for (int j = 0; j < n1; j++) {
System.out.println("how much of" + food[j] + "did the gerbil eat");
String n8 = scanner.nextLine();
amountfood[i] = n8;
}
String[] bite = new String[n4];
System.out.println("Does this Gerbil bite? Enter True or False");
String n77 = scanner.nextLine();
bite[i] = n77;
String[]escape = new String[n4];
System.out.println("Does this Gerbil escape? Enter True or False");
String n89 = scanner.nextLine();
escape[i] = n89;
}
System.out.println("What information would you like to know?");
String n55 = scanner.nextLine();
String n33 = "search";
String n34 = "average";
String n35 = "restart";
String n36 = "quit";
if(n55.equalsIgnoreCase(n34)) {
System.out.println(averagefood());
} else {
if(n55.equalsIgnoreCase(n33)) {
System.out.println("Please type the lab id of the gerbil you wish to search for");
String n87 = scanner.nextLine();
System.out.println();
} else {
if (n55.equalsIgnoreCase(n35)) {
//go back to beginning of program
} else {
if (n55.equalsIgnoreCase(n36)) {
System.exit(0);
} else {
System.out.println("ERROR");
}
}
}
}
}
public static int averagefood(int n4, int n3, int n8) {
for (int i = 0; i < n4; i++) {
long percent = Math.round(n8 * 100.0 / n3);
return averagefood(newName, newId, percent);
}
}
public static int searchForGerbil() {
n87 = setId;
return 0;
// return (new Gerbil[i]
and heres the code from my second class:
public class Gerbil {
private String id;
private String name;
private int[] amountfood;
//private int numbergerbils;
//private int maxfood;
private boolean escape;
private boolean bite;
public Gerbil(String n5, String n6, int numOfFood, boolean newEscape, boolean newBite) {
id = n5;
name = n6;
amountfood = new int[numOfFood];
escape = newEscape;
bite = newBite;
}
public Gerbil(int numOfFood) {
amountfood = new int[numOfFood];
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String newId) {
id = newId;
}
public void setName(String newName) {
name = newName;
}
}
it says next to System.out.println(averagefood()); The method
averagefood(int, int, int) in the type Gerbilfood is not applicable
for the arguments ()
If you check your code your function definition requires three arguments and you have not passed any.
getName cannot be resolved to a variable
This is a function in class Gerbil and hence needs to be called as follows:
Gerbil gb = new Gerbil();
gb.getName();
Syntax error on token "return", Name expected after this token - getId
cannot be resolved to a variable - newId cannot be resolved to a
variable - newName cannot be resolved to a variable it says that next
to return averagefood(newName, newId, percent);
None of these variables have been defined in class Gerbilfood. What values are you expecting to pass using these variables?

What is wrong with this Company Class OOP program?

The point is to write a program that finds an employee by searching by their id number, and by printing out all the information of all the employees and by printing out the information of a single employee. I need help with that (the search) and if printing a single employee alone is correct? Thanks!
Class Employee code:
public class Employee {
private String name;
private int id;
private int salary;
private boolean bonus;
public Employee(String n, int i, int s, boolean b) {
name = n;
id = i;
salary = s;
bonus = b;
}
public void computeSalary(int s, boolean b) {
if (b == true)
salary += 2000;
}
public void printInfo() {
System.out.print("Name: "+name+" ID: "+id+" Salary: "+salary+" Bonus: "+bonus+" ");
}
Class EmployeeApp class code:
import java.util.Scanner;
public class EmployeeApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the name: ");
String n = in.nextLine();
System.out.print("Enter the ID: ");
int g = in.nextInt();
System.out.print("Enter the salary: ");
int s = in.nextInt(); in.nextLine();
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
Employee e = new Employee(n, g, s, b);
e.computeSalary(s, b);
e.printInfo();
}
}
public class Company{
private Employee[] e = new Employee[4];
public void printAllEmployees() {
for(int i = 0; i < e.length; i++)
e[i].printInfo();
}
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (Employee.id == i)
temp = Employee;
}
return temp;
}
public void printAnEmployee(Employee e) {
e.printInfo();
}
}
put employees in a structure that will enable simple searching latter, like the following:
private Map<Integer, Employee> e = new HashMap<Integer, Employee>();
public void printAllEmployees() {
for( Integer key : e.keySet() )
System.out.println(e.get( key ));
}
public Employee searchEmployee(int i) {
return e.get(i);
}
I do not know how the code that you gave us works for even for an user because you have a minor issues in your classes.
First, it is a good practice to have setter and getter in your Employee because for safety is good to encapsulate a object , so how to construct them plz refer to this tutorial
http://www.tutorialspoint.com/java/java_encapsulation.htm
Second, in your EmployeeApp class
when you ask this
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
is not clear what kind of input user has to enter, so it is good to change first line to
System.out.print("true or false for bonus? \nplease enter true or false");
Third, it is good to put your company class in different file, and some minor issue in your Company class as follow
Note: Employee is a class and e is an array with Employee type
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (**Employee.id** == i)
**temp = Employee;**
}
return temp;
}
change to
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (e[i].getId() == i) {
temp = e[i];
}
}
return temp;
}
At the end, if you need to add more employee, you need to put it in a while loop. Hence, while loop is going to be ok till for example an user push X.

Categories

Resources