for-loop and object control - java

I'm trying to add elements to an array. The elements of the array are of a custom class called variable. In the problematic for loop, it basically adds the last element trying to be added throughout the loop. Any help would be appreciated!
import java.util.*;
public class ThiefsDilemma2{
public static void main(String[] args){
ArrayList values = new ArrayList(args.length/2);
Valuable[] array = new Valuable[args.length/2];
if(args.length%2 ==1){
int weight = Integer.parseInt(args[args.length-1]);
boolean room = true;
int tracker = 0;
//problem!!!! Adds the last element throughout the loop
for(int i = 0; i < args.length/2; i++){
array[i] = new Valuable(
Integer.parseInt(args[args.length/2+i]),
Integer.parseInt(args[i]));
}
for(int i = 0; i < args.length/2; i++){
System.out.println(array[i]);
}
while(values.size() > 0 && room){
int lightest = 100000;
double value = 0.0;
int index = 0;
int counter = 0;
for(Object p: values){
Valuable test = (Valuable)p;
//System.out.println(test);
if(test.getWeight() < lightest && !test.beenUsed()){
lightest = test.getWeight();
//System.out.println(lightest);
}
if(test.getValue() > value && !test.beenUsed()){
index = counter;
value = test.getValue();
//System.out.println(value);
}
else if(test.getValue() == value || !test.beenUsed()){
if(test.getWeight() <= test.getWeight()){
index = counter;
}
}
counter++;
}
//System.out.println(counter + " " + lightest + " " + value);
Valuable p = ((Valuable)(values.get(index)));
p.used();
if(lightest > weight){ room = false;}
else{
if(p.getWeight() <= weight){
weight -= p.getWeight();
}
System.out.println(p);
values.remove(p);
}
}
}
}
public static class Valuable{
private static double value;
private static int weight;
private static boolean used = false;
public Valuable(int top, int bottum){
value = ((double)top/(double)bottum);
weight = bottum;
//System.out.println(weight + " " + value);
}
public static double getValue(){
return value;
}
public static int getWeight(){
return weight;
}
public String toString(){
return value + " " + weight;
}
public static void used(){
used = true;
}
public static boolean beenUsed(){
return used;
}
}
}

The problem is that all data members of Valuable are static. This means that they are shared by all instances of the class:
private static double value;
private static int weight;
private static boolean used = false;
Remove the static qualifiers from the data members, and from the getter functions.

Related

Why am I getting this IndexOutOfBoundsException error?

hi so im currently trying to get past this error in my code, if anyone could explain where I went wrong, would be greatly appreciated.
public class Lab07vst100SD
{
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
}
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>();
size = s;
}
public void addData()
{
String [] name = {"Tom","Ann","Bob","Jan","Joe","Sue","Jay","Meg","Art","Deb"};
int[] age = {21,34,18,45,27,19,30,38,40,35};
double[] gpa = {1.685,3.875,2.5,4.0,2.975,3.225,3.65,2.0,3.999,2.125};
for(int i = 0; i < name.length; i++)
{
students.add(new Student(name[i], age[i], gpa[i]));
}
size = students.size();
}
public void selectionSort ()
{
for(int h = 0; h < students.size(); h++)
{
int index = h;
Student least = students.get(h);
for (int t = 0; t < size; t++) {
if (students.get(t).equals(least)) {
least = students.get(t);
index = t;
}
Student temp = students.get(h);
students.set(h, least);
students.set(t, temp);
}
}
}
public int linearSearch (String str)
{
// new arraylist
ArrayList<String> names = new ArrayList<String>();
for (int q = 0; q < size; q++) {
names.add(students.get(q).getName());
}
//comparison
for (int y = 0; y < size; y++) {
if (names.get(y).equals(str))
return y;
}
return -1;
};
public int binarySearch (String str) {
// new arraylist and variables
ArrayList<String> names = new ArrayList<String>();
Boolean found = false;
int lo = 0;
int hi = size;
int mid = (lo + hi) / 2;
//for loop for to transverse the array.
for (int m = 0; m < size; m++) {
names.add(students.get(m).getName());
}
while (lo <= hi && !found) {
if (names.get(mid).compareTo(str) == 0)
{
found = true;
return mid;
}
if (names.get(mid).compareTo(str) < 0) {
lo = mid + 1;
mid = (lo + hi) / 2;
}
else {
hi = mid -1;
mid = (lo + hi) / 2;
}
}
if (found)
return mid;
else
return -1;
}
public String toString() {
String temp = "";
for (int s = 0; s < students.size(); s++) {
temp += students.get(s);
}
return temp;
}
}
also, I should mention this uses the student class.
here
public class Student
{
private String name;
private int age;
private double gpa;
public Student (String n, int a, double g)
{
name = n;
age = a;
gpa = g;
}
public String getName() {
return name; }
public int getAge() {
return age; }
public double getGPA() {
return gpa; }
public String toString()
{
String temp = name + " " + age + " " + gpa + "\n";
return temp;
}
}
the school class calls to the student class.
this is what comes back.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at School.linearSearch(Lab07vst100SD.java:78)
at Lab07vst100SD.main(Lab07vst100SD.java:16)
I'm completely confused on why this is happening, I think it may have to do with the ArrayList, other than that, I'm not sure.
please help, and thank you
p.s. I'm new so please bear with my horrible format.
You need call addData:
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
bhs.addData(); // here
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
...
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>(); // Here, it can throw IndexOutOfBoundsException
size = s;
}
...
Please see https://www.tutorialspoint.com/java/util/arraylist_add_index.htm
The capacity of ArrayList must be initialized before ArrayList.add method
.

How to calculate only integer types in array?

import java.util.*;
class Distance {
private String name;
private int dist;
public Distance(String name, int dist) {
this.name = name;
this.dist = dist;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDist() {
return dist;
}
public void setDist(int dist) {
this.dist = dist;
}
public String toString() {
return "Distance [name=" + name + ", school street=" + dist + "]";
}
}
class DistanceComp {
public static Distance longdistance(Distance[] dim) {
Distance max = dim[0];
for (int i = 1; i < dim.length; i++) {
if (max.getDist() < dim[i].getDist())
max = dim[i];
}
return max;
}
public static Distance shortdistance(Distance[] dim) {
Distance min = dim[0];
for (int i = 1; i < dim.length; i++) {
if (min.getDist() > dim[i].getDist())
min = dim[i];
}
return min;
}
}
public class week03_01 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Distance[] dist = new Distance[3];
System.out.print(">> how many students? : ");
int num = in.nextInt();
for (int i = 0; i < num; i++) {
System.out.print(">> name and distance : ");
dist[i] = new Distance(in.next(), in.nextInt());
}
System.out.println("\na student with the longest commute to school : " + DistanceComp.longdistance(dist));
System.out.println("a student with the shortest commute to school : " + DistanceComp.shortdistance(dist));
System.out.println("school distance difference is " + );
}
}
I also want to print the "shool distance differecnce".
but it doesn't calculate. i think it has String types.
I think calculate only integer types in an array, but i don't know the code.
Or is s there any other way? Ask for advice.
In your DistanceComp class, create a method to subtract two Distances similar like you did for longdistance and shortdistance:
public static int subtractDistance(Distance dist1, Distance dist2) {
int difference = Math.abs(dist1.getDist() - dist2.getDist());
return difference;
}
Then, use that in your System.out:
System.out.println("school distance difference is " + DistanceComp.subtractDistance(DistanceComp.longdistance(dist), DistanceComp.shortdistance(dist)));
Some notes fyi:
Your code currently only works with 3 students.
Instead of using long names, assign them to a shorter-named variable. This helps with code readability.

how to make an object move around a 2d grid array on its own towards other objects in java

OK so I have recently got my program to the point where it is allmost working, however I cant seem to figure out how to make my bug object move.
I have a class called AWorld that is populated with instances of a class method Randfood (ints between 0 and 9) in randomly placed possitions within the grid. It is also passed and instance of my class ABug as an attribute that is placed into the grip according to user input. my problem is I wish to make it move towards the food objects (my ints between 0-9) and when its next to them to have its energy level increased accordingly. it needs to only move towards an object when its within a set distance from it. i.e. 3 spaces in any direction, else just move randomly. my issue is i cant seem to figure out how to do that with my current code setup.
AWorld Class:
package finalversion2;
import java.util.Arrays;
import java.util.Random;
public class AWorld {
int x[] = new int[10], y[] = new int[10];
int row = 25;
int column = 25;
char[][] map;
public static int RandFood(int min, int max) {
Random rand = new Random(); // Initializes the random function.
int RandNum = rand.nextInt((max - min) + 1) + min; //generates a random number within the max and min ranges
return RandNum; //returns the random number
}
//Constructor
//Sets up map array for the AWorld object
//uses a bug that is passed to it
public AWorld(ABug bug) {
ABug bug1 = bug;
map = new char[row][column];
for (int i = 0; i < row; i++) {
for (int x1 = 0; x1 < column; x1++) {
map[i][x1] = ' ';
}
}
for (int i = 0; i < column; i++) {
Random rand = new Random();
int x = rand.nextInt(row);
int y = rand.nextInt(column);
map[x][y] = (char) RandFood(48, 57);
map[bug1.getHPossistion()][bug1.getVPossistion()] = bug1.getSymbol(); // gets the bugs x and y possistion in the array (user defined) and puts it into the symbol variable
}
}
public void PrintWorld() {
for (int i = 0; i < row; i++) //these next two for loops print the array to the screen
{
System.out.print("|");
for (int x1 = 0; x1 < column; x1++) {
System.out.print(map[i][x1]);
}
System.out.println("|");
}
}
}
ABug:
package finalversion2;
public class ABug
{
public static void main(){
}
private String species = new String(); //instance variables (defines data of object)
private String name = new String();
private String description = new String();
private char symbol;
private int hPossistion, vPossistion, energy, iD;
public ABug(){
}
public ABug (String s, String n, String d, int h, int v, int e, int i){
this.species = s;
this.name = n;
this.description = d;
this.symbol = s.charAt(0);
this.hPossistion = h;
this.vPossistion = v;
this.energy = e;
this.iD = i;
}
//setters
public void setSpecies(String s){
this.species = s;
}
public void setName(String n){
this.name = n;
}
public void setSymbol(char symbol){
this.symbol = symbol;
}
public void setHPossistion(int x){
this.hPossistion = x;
}
public void setVPossistion(int y){
this.vPossistion = y;
}
public void setEnergy(int energy){
this.energy = energy;
}
public void setID(int i){
this.iD = i;
}
public void setDescription(String d){
this.description = d;
}
//getters
public String getSpecies(){
return this.species;
}
public String getName(){
return this.name;
}
public char getSymbol(){
return this.symbol;
}
public int getHPossistion(){
return this.hPossistion;
}
public int getVPossistion(){
return this.vPossistion;
}
public int getEnergy(){
return this.energy;
}
public int getID(){
return this.iD;
}
public String getDescription(){
return this.description;
}
public String toString(){
String BugData;
BugData = name + " " + symbol + "\n" + species + "\n" + description;
return BugData;
}
}
enum Direction:
package finalversion2;
public enum Direction {
NORTH, EAST, SOUTH, WEST;
}
now im guessing I need to redraw my map each time i wish it to move using my enum based on a boolean response, i.e. call the printworld method but randomly move the bug. but wont that reprint my random ints?
please help. im very new to java.
Cheers in advance.

"The inferred type _____ is not a valid substitute for the bounded parameter"

public class Main {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Country> cList = new ArrayList<Country>();
ArrayList choice = new ArrayList();
File inf = new File("src/countrydata.txt");
Scanner scan = new Scanner(inf).useDelimiter("[\t|\n|\r]+");
Scanner s = new Scanner(System.in);
int p = 0;
double g = 0;
while(scan.hasNext()){
cList.add(new Country(scan.next(), scan.nextInt(), scan.nextDouble()));
}
System.out.print("Would you like in sorted my name(n), population(p) or growth(g): ");
String go = s.next();
go = go.toLowerCase();
if(go.equals("n")){
choice.add(go);
}else if(go.equals("p")){
choice.add(p);
}else if(go.equals("g")){
choice.add(g);
}
MyUtil.bubbleSort(cList, choice);
My Error: (Line above) Bound mismatch: The generic method bubbleSort(List, List) of type MyUtil is not applicable for the arguments (ArrayList, ArrayList). The inferred type Country is not a valid substitute for the bounded parameter >
}
//Sort Class
public class MyUtil <E extends Comparable<E>>{
public static <E extends Comparable<E>>void bubbleSort(List<E> list, List choice){
int n = list.size();
boolean swap = true;
while(swap){
swap = false;
for(int i = 0; i < n-1; i++){
if(list.get(i).compareTo(list.get(i+1)) == 1){
swap(list, i, i+1);
swap = true;
}
}
}
}
public static <E extends Comparable<E>>void swap(List<E> list, int i, int j){
E temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
public class Country {
private String name;
private int population;
private double growth;
public Country(String name, int population, double growth){
this.name = name;
this.population = population;
this.growth = growth;
}
public String getName(){return name;}
public int getPopulation(){return population;}
public double getGrowth(){return growth;}
public String toString(){
return name + ", population of " + population + ", with an anual growth of: " + growth + ".";
}
public int compareTo(Country c, String s){
if(name.substring(0, 1).compareTo(c.getName().substring(0, 1)) > 0){
return -1;
}else if(name.substring(0, 1).compareTo(c.getName().substring(0, 1)) == 0){
return 0;
}else{
return 1;
}
}
public int compareTo(Country c, int p){
if(population < c.getPopulation()){
return -1;
}else if(population == c.getPopulation()){
return 0;
}else{
return 1;
}
}
public int compareTo(Country c, double g){
if(growth < c.getGrowth()){
return -1;
}else if(growth == c.getGrowth()){
return 0;
}else{
return 1;
}
}
}
The issue is that you've specified in the line
public static <E extends Comparable<E>>void bubbleSort(List<E> list, List choice)
that E must extend Comparable<E> and Country does not. In order to make it compile, you'd have to change
public class Country {
to
public class Country implements Comparable<Country> {
and you'll also have to implement
public int compareTo(Country c) {}
but doing it that way won't give you the flexibility to sort by multiple different dimensions.

Sorting arrays from a file and printing results

I have to read a file of data and store it into an array of integers, sort through the array and then report the highest total and the lowest total but for some reason when i run my code nothing appears, and it says that it is error free. this is the code that i have so far...
import java.io.*;
import java.util.Scanner;
public class CarbonAnalysis {
public static void main (String [] Args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
File f = new File("carbon_data.txt");
Scanner welcome = new Scanner(f);
File outputFile = new File("carbon_report.txt");
PrintStream output = new PrintStream(outputFile);
String firstLine = welcome.nextLine();
int secondLine = welcome.nextInt();
CarbonDioxideData[] Country = new CarbonDioxideData[secondLine];
for(int i = 0; i < secondLine; i++) {
Country[i] = new CarbonDioxideData();
Country[i].setCountry(welcome.next());
Country[i].setTotalCO2(welcome.nextDouble());
Country[i].setRoadCO2(welcome.nextDouble());
Country[i].setCO2PerPerson(welcome.nextDouble());
Country[i].setCarsPerPerson(welcome.nextInt());
}
int count = 0;
int count2 = 0;
CarbonDioxideData[] totalEmissions = new CarbonDioxideData[count];
CarbonDioxideData[] perPersonRoadEmissions = new CarbonDioxideData[count2];
reportDescription(output);
sortTotalEmissions(totalEmissions);
sortPerPersonRoadEmissions(perPersonRoadEmissions);
}
//prints the output of data analyzed
public static void reportDescription(PrintStream output) {
output.println("Country with the lowest total emissions: ");
output.println("Country with the highest total emissions: " );
output.println("Canada is ranked for lowest total emissions.");
output.println();
output.println("Country with the lower per-person road emissions: ");
output.println("Country with the highest per-person road emissions: ");
output.println("Canada is ranked for the lowest per-road emissions.");
}
//sorts the total Emissions from highest to lowest
public static void sortTotalEmissions(CarbonDioxideData[] totalEmissions){
for(int i = 0; i < totalEmissions.length; i++) {
double max = totalEmissions[i].getTotalCO2();
int maxPos = i;
for(int j = i; j < totalEmissions.length; j++) {
if(max < totalEmissions[j].getTotalCO2() ) {
max = totalEmissions[j].getTotalCO2();
maxPos = j;
}
}
CarbonDioxideData temp = totalEmissions[maxPos];
totalEmissions[maxPos] = totalEmissions[i];
totalEmissions[i] = temp;
}
}
//sorts the per person road Emissions from highest to lowest
public static void sortPerPersonRoadEmissions(CarbonDioxideData[] perPersonRoadEmissions){
for(int i = 0; i < perPersonRoadEmissions.length; i++) {
int max = perPersonRoadEmissions[i].getCarsPerPerson();
int maxPos = i;
for(int j = i; j < perPersonRoadEmissions.length; j++) {
if(max < perPersonRoadEmissions[j].getCarsPerPerson() ) {
max = perPersonRoadEmissions[j].getCarsPerPerson();
maxPos = j;
}
}
CarbonDioxideData temp = perPersonRoadEmissions[maxPos];
perPersonRoadEmissions[maxPos] = perPersonRoadEmissions[i];
perPersonRoadEmissions[i] = temp;
}
}
}
The code that was given to me to help:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
Your program always ouputs a constant String in the file since there is no variable in reportDescription.
Secondly to properly sort you array, CarbonDioxideData should implement Comparable. Then you can call
Arrays.sort like this :
Arrays.sort(perPersonRoadEmissions)
and then retrieve the highest/value :
perPersonRoadEmissions[0] / perPersonRoadEmissions[perPersonRoadEmissions.length-1]
To display the information you have to call output after sorting and change the signature to accept variable for highest and lowest value.
Arrays.sort(totalEmissions);
Arrays.sort(perPersonRoadEmissions)
reportDescription(output,totalEmissions[0],totalEmissions[totalEmissions.length-1],perPersonRoadEmissions[0],perPersonRoadEmissions[perPersonRoadEmissions.length-1]);
As an alternative you can also simply pass the arrays as parameters and retrieve min max in the body of reportDescription :
reportDescription(output,totalEmissions,perPersonRoadEmissions);
How to change the content of reportDescription and implementing compareTo is left to the OP.

Categories

Resources