I am struggling with an actually very easy task, which is print out items from an item array like:
arr[3,4,2,5]
0 items (0 kg)
0 items (1 kg)
0 items (2 kg)
and so on.
This is what I have done, but my program will not print anything :( Heeelp me please.
import java.util.ArrayList;
import java.util.Arrays;
public class Suitcase {
private ArrayList<Item> items = new ArrayList<>();
private final int maxWeight;
private int[] arr = new int[items.size()];
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
int itemsWeight = 0;
for(Item i: items){
itemsWeight += i.getWeight();
}
if(itemsWeight + item.getWeight() <= this.maxWeight){
items.add(item);
}
}
public void array() {
for(Item item: items){
int index = item.getWeight();
this.arr[index] += 1;
}
}
public String toString() {
String returnValue = "";
for(int i = 0; i < arr.length; i++){
returnValue = arr[i] + " items " + i + " kg";
}
return returnValue;
}
}
public class Item {
private int weight;
private String name;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public String toString() {
return this.name + "(" + String.valueOf(this.weight) + ")";
}
}
Here is my main class, but it will not print anything:
public class Main {
public static void main(String[] args) {
Item book = new Item("Lord of the rings", 2);
Item phone = new Item("Nokia 3210", 1);
Item brick = new Item("brick", 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase.toString());
suitcase.addItem(book);
System.out.println(suitcase);
suitcase.addItem(phone);
System.out.println(suitcase);
suitcase.addItem(brick);
System.out.println(suitcase);
}
}
Notes:
You do not need to call suitcase.toString() while printing the suitcase object. When System.out.println(suitcase); is implicitly gets converted into System.out.println(suitcase.toString());.
You can make your design simpler by having a variable to keep track of the total weight in the suitcase. Also, create a variable in Item to keep track of item's count in the suitcase.
You do not need int[] arr. It is simply adding unwanted complexity. Remove it.
It is better to use enhanced for loop if you can do so.
Given below is the code incorporating the points mentioned above:
import java.util.ArrayList;
class Suitcase {
private ArrayList<Item> items = new ArrayList<>();
private final int maxWeight;
private int totalWeight;
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
if (totalWeight + item.getWeight() <= maxWeight) {
int index = items.indexOf(item);
if (index == -1) {// It means the item does not exist in the suitcase
items.add(item);
}
// If the item already exists, do not add it's entry again; just update its
// count and the totalWeight of the suitcase
totalWeight += item.getWeight();
item.setCount(item.getCount() + 1);
System.out.println(item.getName() + " was added in the suitcase");
} else {
System.out.println(item.getName() + " can not be accommodated in the suitcase.");
}
}
public String toString() {
String returnValue = "";
for (Item item : items) {
returnValue += "No. of " + item.getName() + " in the suitcase = " + item.getCount()
+ ", its total weight = " + item.getCount() * item.getWeight() + "kg\n";
}
if (returnValue.isEmpty()) {
returnValue = "The suitcase is empty.";
} else {
returnValue += "Total weight of the suitcase = " + totalWeight + "kg";
}
return returnValue;
}
}
class Item {
private int weight;
private String name;
private int count;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Item [weight=" + weight + ", name=" + name + ", count=" + count + "]";
}
}
public class Main {
public static void main(String[] args) {
Item book = new Item("Lord of the rings", 2);
Item phone = new Item("Nokia 3210", 1);
Item brick = new Item("brick", 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase);
suitcase.addItem(book);
suitcase.addItem(phone);
suitcase.addItem(brick);
suitcase.addItem(phone);
suitcase.addItem(book);
System.out.println(suitcase);
}
}
Output:
The suitcase is empty.
Lord of the rings was added in the suitcase
Nokia 3210 was added in the suitcase
brick can not be accommodated in the suitcase.
Nokia 3210 was added in the suitcase
Lord of the rings can not be accommodated in the suitcase.
No. of Lord of the rings in the suitcase = 1, its total weight = 2kg
No. of Nokia 3210 in the suitcase = 2, its total weight = 2kg
Total weight of the suitcase = 4kg
Make sure to change your "toString()" function, currently it is only printing the last value, change it to:
public String toString(){
String returnValue ="";
for(int i = 0; i<arr.length;i++ ){
returnValue += arr[i] + " items " +i+" kg"; //notice its '+='
}
return returnValue;
}
You initialize your arr with value 0. Note that the initial size of new ArrayList() is 0. Take a look at this example:
import java.util.ArrayList;
class Main {
private static ArrayList<Object> items = new ArrayList();
private static int[] arr = new int[items.size()];
public static void main(String[] args) {
System.out.println(items.size()); # => 0
System.out.println(arr.length); # => 0
}
}
As a result when you call System.out.println(suitcase) the for loop in Suitcase's toString() method iterates over exactly 0 elements - therefore not outputting anything.
Related
I'm having some issues with how I should approach this problem.
I have a Boat class which contains a toString() and getters and setters.
PowerBoat class which extends functionality and overrides toString() method from it's superclass.
SailBoat class which extends functionality and overrides toString() method from it's superclass.
In my test class I am adding different PowerBoats, SailBoats in a ArrayList of type of Boat.
I need to find the most expensive boat and print a toString() information about that boat.
public class Boat {
String color;
int length;
public Boat(){
color = "white";
length = 20;
}
public Boat(String color, int length){
setColor(color);
setLength(length);
}
public String getColor() {
return color;
}
public boolean setColor(String color) {
switch (color){
case "white" : this.color = color;
case "red" : this.color = color;
case "blue" : this.color = color;
case "yellow" : this.color = color;
return true;
}
return false;
}
public int getLength() {
return length;
}
public boolean setLength(int length) {
if(length >= 20 && length <= 50) {
this.length = length;
return true;
}
return false;
}
#Override
public String toString() {
return "Boat{" +
"color='" + color + '\'' +
", length=" + length +
'}';
}
}
public class PowerBoat extends Boat {
int engineSize;
public PowerBoat(){
super();
setEngineSize(5);
}
public PowerBoat(String color, int length, int engineSize){
super(color, length);
setEngineSize(engineSize);
}
public boolean setEngineSize(int engineSize){
if(engineSize >= 5 && engineSize <= 350){
this.engineSize = engineSize;
return true;
}
return false;
}
public int getEngineSize() {
return engineSize;
}
public int calcPrice(){
return 5000 + length + 300 + engineSize * 20;
}
#Override
public String toString() {
return super.toString() +
"engineSize= " + engineSize +
'}' + " Price " + calcPrice();
}
}
public class SailBoat extends Boat {
int numSails = 0;
public SailBoat(){
numSails = 1;
}
public SailBoat(String color, int length, int numSails){
super(color, length);
setNumSails(numSails);
}
public int getNumSails() {
return numSails;
}
public boolean setNumSails(int numSails) {
if(numSails >= 1 && numSails <= 4){
this.numSails = numSails;
return true;
}
return false;
}
public int calcPrice(){
return length * 1000 + numSails * 2000;
}
#Override
public String toString() {
return super.toString() +
"numSails= " + numSails +
'}' + " price " + calcPrice();
}
}
public class Inventory {
public static void main(String[] args){
ArrayList<Boat> list = new ArrayList();
Boat powerBoat = new PowerBoat("blue", 46, 60);
Boat powerBoat1 = new PowerBoat("yellow", 42, 55);
Boat sailBoat = new SailBoat("white", 32, 1);
Boat sailBoat1 = new SailBoat("red", 24, 2);
list.add(powerBoat);
list.add(powerBoat1);
list.add(sailBoat);
list.add(sailBoat1);
int sumSailBoat = 0;
int sumPowerBoat = 0;
int largest = Integer.MIN_VALUE;
for(Boat b : list){
if (b instanceof SailBoat){
sumSailBoat+= ((SailBoat) b).calcPrice();
if (((SailBoat) b).calcPrice() > largest){
if(b instanceof SailBoat) {
largest = ((SailBoat) b).calcPrice();
}
}
}
if (b instanceof PowerBoat){
sumPowerBoat+= ((PowerBoat) b).calcPrice();
if(((PowerBoat) b).calcPrice() > largest){
if(b instanceof PowerBoat){
largest = ((PowerBoat) b).calcPrice();
}
}
}
}
int totalSum = sumSailBoat + sumPowerBoat;
System.out.println("Total price of sail boats is " + sumSailBoat);
System.out.println("Total price of sail boats is " + sumPowerBoat);
System.out.println("Total price of sail and power boats is " + totalSum);
System.out.println("Most expensive boat is " + largest);
}
}
I managed to find the largest price but how can I print the toString information about that Boat?
If you know the type you can use:
System.out.println("My PowerBoat " + ((PowerBoat) b));
System.out.println("My SailBoat " + ((SailBoat) b));
If you already found the object you need to print store it in a variable and just call toString on it.
Boat b = //whichever one you found here from the arraylist
System.out.println(b.toString())
Since classes in java use dynamic binding, even if your reference is of the superclass, the contents of the method should still be the same.
[teach-me] You seem to have some misconceptions on OO design and java method calls. Please talk to your teachers or read some OO/Java books. Start with the concept of abstract and final in Java - that should give you some idea how methods are called and how inheritance can be used.
That being said, you need to do 2 things.
(1) To answer your question, in addition to int largest, also keep Boat mostExpensiveBoat, update it at the same time you update largest. Then at the end print mostExpensiveBoat.toString().
(2) You need to make calcPrice() an abstract method of Boat. Then when you call b.calcPrice(), the method that matches the type of object b refers to will "magically" be invoked. No need check instanceof or to cast.
It will be better, to make calcPrice() part of Boat interface:
abstract class Boat {
String color;
int length;
public Boat(){
color = "white";
length = 20;
}
public Boat(String color, int length){
setColor(color);
setLength(length);
}
public String getColor() {
return color;
}
public boolean setColor(String color) {
switch (color){
case "white" : this.color = color;
case "red" : this.color = color;
case "blue" : this.color = color;
case "yellow" : this.color = color;
return true;
}
return false;
}
public int getLength() {
return length;
}
public boolean setLength(int length) {
if(length >= 20 && length <= 50) {
this.length = length;
return true;
}
return false;
}
public abstract int calcPrice();
#Override
public String toString() {
return "Boat{" +
"color='" + color + '\'' +
", length=" + length +
'}';
}
}
Then you can make search in this way:
int sumSailBoat = 0;
int sumPowerBoat = 0;
int largest = Integer.MIN_VALUE;
Boat boatWithLargestPrice = null;
for (Boat b : list) {
int boatPrice = b.calcPrice();
if (boatPrice > largest) {
largest = boatPrice;
boatWithLargestPrice = b;
}
if (b instanceof SailBoat) {
sumSailBoat += boatPrice;
} else {
sumPowerBoat += boatPrice;
}
}
int totalSum = sumSailBoat + sumPowerBoat;
System.out.println("Total price of sail boats is " + sumSailBoat);
System.out.println("Total price of power boats is " + sumPowerBoat);
System.out.println("Total price of sail and power boats is " + totalSum);
System.out.println("Most expensive boat is " + boatWithLargestPrice + " with price " + largest);
By making your Boat class abstract you can require all Boats to implement calcPrice. Then you can just treat all Boats the same.
public abstract class Boat {
final String color;
final int length;
public Boat(String color, int length) {
this.color = color;
this.length = length;
}
public abstract int calcPrice();
#Override
public String toString() {
return "Boat{" +
"color='" + color + '\'' +
", length=" + length +
'}';
}
}
public class PowerBoat extends Boat {
final int engineSize;
public PowerBoat(String color, int length, int engineSize) {
super(color, length);
this.engineSize = engineSize;
}
#Override
public int calcPrice() {
return 5000 + length + 300 + engineSize * 20;
}
#Override
public String toString() {
return super.toString() +
"engineSize= " + engineSize +
'}' + " Price " + calcPrice();
}
}
public class SailBoat extends Boat {
final int numSails;
public SailBoat(String color, int length, int numSails) {
super(color, length);
this.numSails = numSails;
}
#Override
public int calcPrice() {
return length * 1000 + numSails * 2000;
}
#Override
public String toString() {
return super.toString() +
"numSails= " + numSails +
'}' + " price " + calcPrice();
}
}
public void test() {
ArrayList<Boat> list = new ArrayList();
list.add(new PowerBoat("blue", 46, 60));
list.add(new PowerBoat("yellow", 42, 55));
list.add(new SailBoat("white", 32, 1));
list.add(new SailBoat("red", 24, 2));
Boat mostExpensiveBoat = null;
int totalSum = 0;
for (Boat boat : list) {
totalSum += boat.calcPrice();
if(mostExpensiveBoat == null || boat.calcPrice() > mostExpensiveBoat.calcPrice() ) {
mostExpensiveBoat = boat;
}
}
System.out.println("Total price of sail and power boats is " + totalSum);
System.out.println("Most expensive boat is " + mostExpensiveBoat);
}
I need to write a function to College department :
Add function adds additional lecturer.
Action returns false if there is no place to add additional lecturer, and at the same true if the lecturer was successfully added.
What I had written so far:
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
The function does not work properly, It always returns true (because that the Max Lecturer always bigger than sum).
main:
public class main {
public static void main(String[]args){
Lecturer[] L1 = new Lecturer[]{new Lecturer("David",3,"Banana",1001)};
Lecturer[] L2 = new Lecturer[]{new Lecturer("Yossi",5,"apple",1002)};
Lecturer[] L3 = new Lecturer[]{new Lecturer("Y",2,"t",1003)};
College myCollege = new College("College1",20,L1,3);
//System.out.println(myCollege);
//myCollege.allLecturer=L2;
//System.out.println(myCollege);
myCollege.newLecturer(L1);
myCollege.newLecturer(L2);
myCollege.newLecturer(L3);
}
}
class College (Function here):
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
// constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer,
int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name) {
this.name = Name;
}
public College(Lecturer[] AllLecturer) {
this.allLecturer = AllLecturer;
}
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
#Override
public String toString() {
String lecturers = "";
for (Lecturer lecturer : allLecturer) {
lecturers += lecturer;
}
return "[Name College: " + name + "] " + " [num Of Lecturer: "
+ numOfLecturer + "]" + " [all Lecturer: " + lecturers + "]"
+ " [max Lecturer " + maxLecturer + "]";
}
}
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
// constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
public Lecturer(String Name) {
this.name = Name;
}
#Override
public String toString() {
return "[name: " + name + "] " + " [num Of Times Pen Falls: "
+ numOfTimesPenFalls + "] " + " [favorite Ice Cream: "
+ favoriteIceCream + "] " + " [auto Number: " + autoNumber
+ "]";
}
}
And finally how can I print it?
Like this gives a compiler error:
myCollege.newLecturer("David",2,"Apple",1004);
thank you.
You're new; you need a lot of help.
Start by learning and following Java coding standards. Variable names should start with lower case. Classes start with upper. Deviations from that make your code hard to read.
Your method is wrong. You need something like this inside that class:
private static final int MAX_LECTURERS = 3;
private int numLecturers = 0;
private Lecturer [] lecturers = new Lecturer[MAX_LECTURERS];
public boolean addLecturer(Lecturer lecturer) {
boolean addedLecturer = false;
if (this.numLecturers < MAX_LECTURERS) {
this.lecturers[numLecturers++] = lecturer;
addedLecturer = true;
}
return addedLecturer;
}
Here's how you use this method:
Lecturer newLecturer = new Lecturer("foo", 1, "bar", 3);
college.addLecturer(newLecturer);
Please stop with all that array nonsense. The array is inside the College class.
The sum variable in your code is a local variable, its scope is only at the function level. This means the sum always get initialized to 0 and increased to 1 every time the function newLecturer() is called. That's why sum always smaller than MAX_LECTURER (1<3).
You need to use class variable numLecturers like in duffymo answer above.
I'm creating a scoring system using a treeMap and I want to only display the top 3 results. When the player inputs the 4th result (if it's bigger than the current smallest value) how do I make it delete the smallest value and replace it with the new value. My code so far so sorting the scores:
Map<Integer, String> treeMap = new TreeMap<Integer, String>(new MyCopr());
treeMap.put(name1val, name1);
treeMap.put(name2val, name2);
treeMap.put(name3val, name3);
treeMap.put(tempval, tempname);
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
playername1.append("Key : " + entry.getKey() + " Value : "
+ entry.getValue() + "\n");
}
}
class MyCopr implements Comparator<Integer> {
#Override
public int compare(Integer lhs, Integer rhs) {
return rhs.compareTo(lhs);
}
}
From here what can I do to replace the smallest value? Thanks.
I would use a set of scores (like this) -
private static int MAX_SCORES = 3;
private SortedSet<Score> scores = new TreeSet<Score>();
public Set<Score> getScores() {
return scores;
}
public void addScore(String name, int score) {
scores.add(new Score(name, score));
while (scores.size() > MAX_SCORES) {
scores.remove(scores.first());
}
}
private class Score implements Comparable<Score> {
private String name;
private int score;
private Score(String name, int score) {
this.name = name;
this.score = score;
}
public int compareTo(Score obj) {
if (this == obj) {
return 0;
}
if (this.score < obj.score) {
return -1;
} else if (this.score > obj.score) {
return 1;
}
return name.compareTo(obj.name);
}
public String toString() {
return name + " - score = " + score;
}
}
And then use it like so ...
System.out.println(obj.getScores());
obj.addScore("Player 1", 1);
obj.addScore("Player 2", 2);
obj.addScore("Player 3", 3);
System.out.println(obj.getScores());
obj.addScore("Player 4", 4);
System.out.println(obj.getScores());
Which yields this (when I run it) -
[]
[Player 1 - score = 1, Player 2 - score = 2, Player 3 - score = 3]
[Player 2 - score = 2, Player 3 - score = 3, Player 4 - score = 4]
I have searched and found a few responses that didn't seem to help and I am stuck with an nullPointerException error. Below is my code the error is in my logResponse() method, any help is much appreciated.
import java.util.*;
public class Survey21 {
private Scanner in = new Scanner(System.in);
private String surveyTitle;
private static int rID;
private static int respondentID;
private int[][] responses;
//Constructors
// Default Constructor
Survey21() {
surveyTitle = "Customer Survey";
}
// Overloaded Constructor 1
Survey21(String title, int rID) {
surveyTitle = title;
rID = 0;
generateRespondentId();
}
Survey21(int[][] surveyArray) {
responses = surveyArray; // store responses
}
public static int getrID() {
return rID;
}
public static void setRespondentID(int respondentID) {
respondentID = rID;
}
public String getTitle() {
return surveyTitle;
}
public void setTitle(String title) {
surveyTitle = title;
}
public static int generateRespondentId() {
rID = ++respondentID;
return rID;
}
// displays name of survey and entire grid of results
public void displaySurveyResults() {
System.out.printf("%s\n\n", getTitle());
logResponse();
}
// dispalys question number and results for that question so far
public void displayQuestionStats(int questionNumber) {
}
// enter questions and store in an array of Strings
public void enterQuestions() {
/*String[] questions = {
"How would you rate your online shopping experience?",
"How satisfied was you with the purchase price?",
"Overall how was the online checkout experience?",
"How likely are you to recommend your friends and family to our store?",
"How concerned are you with online credit card security?",
"How likely are you to prefer a retail location compared to an online store?",
};*/
String questions[] = new String[10];
for (int i = 0; i < questions.length; i++) {
System.out.println("Please enter a question!");
questions[i] = in.nextLine();
}
/*TEST TEST***
System.out.print(questions[0] + "\n");
System.out.print(questions[1] + "\n");
System.out.print(questions[2] + "\n");
System.out.print(questions[3] + "\n");
System.out.print(questions[4] + "\n");
System.out.print(questions[5] + "\n");
System.out.print(questions[6] + "\n");
System.out.print(questions[7] + "\n");
System.out.print(questions[8] + "\n");
System.out.print(questions[9] + "\n");
*/
}
**// enters the response in the correct grid
public void logResponse() {
System.out.println("The responses are:\n");
System.out.print(" "); // align column heads
// create a column heading for each question
for (int qNumber = 0; qNumber < responses[0].length; qNumber++) {
System.out.printf("Question number %d ", qNumber + 1);
System.out.println("Response"); // column heading
}
for (int response = 0; response < responses.length; response++) {
System.out.printf("Response %2d", response + 1);
for (int qNumber : responses[response])// output responses
{
System.out.printf("%8d", qNumber);
}
}
}**
}
Probably you want the length of your array and not the length of your first element:
for (int qNumber = 0; qNumber < responses.length; qNumber++) {
System.out.printf("Question number %d ", qNumber + 1);
System.out.println("Response"); // column heading
}
I didn't initialize my array properly I did
private int[][] responses;
and it should have been
private int[][] responses = new int[5][11];
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.