I have to be able to convert some variables in my class. I have a boolean variable, WaGa (Stands for Workstation/Gaming computer), and if it's true, I want to convert String WorGam
I have to do this through service and support methods, and I keep trying, but I constenly fail. It just prints out what's in the driver. HELP.
public class Graphics
//instance data
{
private int Ram;
private String Brand;
private int Res;
private int BiWi;
private int BaCl;
private boolean K4;
private boolean WaGa;
private String WorGam;
//boolean WaGa, boolean K4, int BaCl, int BiWi, int Res, String Brand, int Ram
public Graphics (int R, String B, int Re, int Bi, int Ba, boolean K4, boolean Wa, String Wor ) // constructor
{
Ram = R;
Brand = B;
Res = Re;
BiWi = Bi;
BaCl = Ba;
K4 = K4;
WaGa = Wa;
Wor = WorGam;
}
public int get_Ram() //Accessor Method - there are 3 of them
{
return Ram;
}
public String get_Brand() //Accessor Method - there are 3 of them
{
return Brand;
}
public int get_Res() //Accessor Method - there are 3 of them
{
return Res;
}
public int get_BiWi() //Accessor Method - there are 3 of them
{
return BiWi;
}
public int get_BaCl()
{
return BaCl;
}
public boolean get_K4()
{
return K4;
}
public String WorGam(boolean WaGa)
{
String WorGam;
if ( WaGa == true) {
return WorGam = "Workstation";
} else {
return WorGam = "True";
}
}
public String toString()
{
return ("Ram" + " " + Ram + ". " + "Brand:" + " " + Brand + ". " + "Resolution" + " " + Res + ". " + "Processer" + " " + BiWi + "." + " " + "Base Clock" + " " + BaCl+ " " + "K4?" + " " + K4+ " " +WorGam);
}
}
public class Graphicse_Driver
{
public static void main(String [] args)
{
Graphics unique=new Graphics(4, "Nvinda", 6, 7, 9, false, false, "sdf" );
System.out.println(unique);
You may need to reread you code to make sure there aren't any other mistakes in your code, but this is the root of your problem.
In order to access the WarGam getter, you need to call:
System.out.println(unique.WarGam());
When you do System.out.println(unique), you are trying to print out the entire Graphics object instead of just the WarGam string.
You then should change your WarGam() method to look like the following:
public String WorGam()
{
if (WaGa) {
return "Workstation";
}
return "Gaming";
}
Here is a more in depth explanation of the changes:
WaGa is a private variable of your Graphics class. Since the WarGam() method is in the same Graphics class, it already had access to the WaGa variable, so you do not need to pass it in.
if(WaGa == true) is just a wordier way of writing if(WaGa).
Instead of creating a String WorGam variable, you can just return the string you want directly.
The else surrounding the second return is unnessary since that code will only be hit if the first return is skipped.
After these changes, the private String WarGam variable is really not necessary either.
public String worGam(boolean waGa) {
if (waGa)
return "Workstation";
else
return "Gaming";
}
You need to correct your worGam() function:
public String worGam(boolean waGa) {
if (waGa == true)
return "Workstation";
else
return "True";
}
And the main() function:
public static void main(String [] args) {
Graphics unique = new Graphics(4, "Nnn", 6, 7, 9, false, false, "xxx");
System.out.println(unique.WorGam(false));
}
Related
Below is the commented line, where I'm getting an unreachable error:
public class HotelRoom{
private int rNo;
private int dRented;
private String rType;
private String occName;
**type of accomodation is checked below**
if(rType=="king"){ this.rType=rType; }
else if(rType=="queen"){ this.rType=rType;}
else if(rType=="suite"){ this.rType=rType;}
else{this.rType = "queen"; } }
**accessor**
public int getRoomNumber(){ return rNo; }
public int getDaysRented(){ return dRented; }
**mutator**
public String getRoomType(){ return rType; }
public String getOccupantName(){return occName; }
**setting the value of occupant based on the conditions**
public boolean setOccupant(String guestName, int days){
if(this.occName!=null){ return false; }
this.occName=guestName; this.dRented = days; return true; }
advance method
public void advanceDay(){
this.dRented = this.dRented - 1;
if(this.dRented <= 0){ this.occName = null; this.dRented = 0;}}
toString method:
public String toString(){String out = "";
if(occName!=null){out = "Rented"; return out;}
else{ out ="Free"; return out;}
Error line -"unreachable error":
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
public static void main (String[] args){
HotelRoom r1 = new HotelRoom(007,"king");
System.out.println(r1);
}
}
The method toString (that I report here reformatted for readable reasons):
public String toString() {
String out = "";
if (occName != null) {
out = "Rented";
return out; // Exit here
} else {
out ="Free";
return out; // or exit here
}
// Never reachable
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
the last row is never reachable because you return from the previous if block and also in the else block, so there is no chance to reach the last line.
I suppose that you like the following behaviour:
public String toString() {
String out = "";
if (occName != null) {
// Just set out variable
out = "Rented";
} else {
// Just set out variable
out ="Free";
}
// Return a complete string using the previous out variable
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
A tip: format always your code so that it is more human readable. A code that is easy to read is also a code that is easy to study to find errors.
Im working on a school project where I have to implement recursion with arrays and I have done everything but im getting a null error when I am running it. The error points to the Recursion class on Line:
result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination;
I tried tracing the recursion method to see if it would actually make sense and its looks solid but i'm still getting a null error.
Recursion Class:
import java.io.*;
public class Recursion
{
public String toString(Packet[] packetList, int n)
{
String result = "";
if (n < 0)
{
return result;
}
result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination; // Uncomment if you want the values from last-to-first (last index to 0 index)
result += toString(packetList, n-1);
//result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination; // Uncomment if you want the values from first-to-last (0 index to last index)
return result;
}
}
Packet Class
public class Packet
{
public int idNumber;
public double weight;
public String Destination;
public Packet(int id, double w, String D)
{
idNumber = id;
weight = w;
Destination = D;
}
public boolean isHeavy()
{
if (weight > 10)
return true;
else
return false;
}
public String toString()
{
return idNumber + " " + weight + " " + Destination;
}
public double getWeight()
{
return weight;
}
public String getDestination()
{
return Destination;
}
}
Test Class
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class TestPackages
{
public static void main (String[] args) throws IOException
{
Packet[] packetList = new Packet[100];
int idNumber;
double weight;
String Destination;
Scanner fileInput;
fileInput = new Scanner (new File("packetData.txt"));
int counter = 0;
while (fileInput.hasNextLine())
{
idNumber = fileInput.nextInt();
weight = fileInput.nextDouble();
Destination = fileInput.nextLine();
Packet myPacket = new Packet (idNumber, weight, Destination);
packetList[counter++] = myPacket;
}
Recursion recursion = new Recursion();
System.out.println(recursion.toString(packetList, packetList.length - 1));
recursion.displayHeavyPackages(packetList, packetList.length - 1);
recursion.displayPacketsToDest(packetList, packetList.length - 1, "CT");
recursion.countPacketsToDest(packetList, packetList.length - 1, "CT");
}
}
It looks like you are sending the length of the array to your toString() function, but it might not have the 100 elements initialized, try sending your ´counter´ instead :
System.out.println(recursion.toString(packetList, counter-1))
Please verify that packetData.txt has exactly 100 lines otherwise the program will throw a null pointer Exception.
The displayHeavyPackage method should validate if n==0 to avoid Array Index Out Bound exception
displayHeavyPackage
public void displayHeavyPackages(Packet[] packetList, int n) {
if (packetList[n].isHeavy() == true && n>0) {
System.out.println(packetList[n]); displayHeavyPackages(packetList, n-1);
} else if (packetList[n].isHeavy() == true && n==0){
System.out.println(packetList[n]);
}
}
My final suggestion is try to debug your code, it will help a lot to clarify the root cause of the exceptions.
I have to write a PhonePlan object that will represent the type of plan that a customer has for his/her phone. So the object must keep track of the minutesAllowed (int), minutes used (int), dataAllowed (int), data used (int) and planType (boolean):
public class PhonePlan {
int minutesAllowed;
int minutesUsed;
int dataAllowed;
int dataUsed;
boolean planType;
}
I needed to write a constructor which has minutesAllowed, dataAllowed, and the planType as arguments which I did:
public PhonePlan (int ma, int da, boolean pt){
this.minutesAllowed = ma;
this.planType = pt;
this.dataAllowed = da;
}
And finally I have to write a string method that displays the plan depending on the type of plan.
I also have to test my code with the following test program;
public class PlanTestProgram {
public static void main(String args[]) {
System.out.println(new PhonePlan(200, 2500000, false));
System.out.println(new PhonePlan(250, 500000, true));
System.out.println(new PhonePlan(300, 5000000, false));
System.out.println(new PhonePlan(60, 1000000, false));
System.out.println(new PhonePlan(30, 0, true));
}
The first element being the minutesAllowed, the second one being the amount of dataAllowed and the third one is stating if planType is true of false.
I tried many different things but I am not able to construct a toString() method that take into account if my planType is either true or false...
My Attempt:
public String toString(){
return ( "Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) Monthly Plan with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
}
You can easily update return in your suggested (attempt) toString method, by using the shorthand if/else, into the following:
return ("Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) " + ((PlanType)? "Monthly": "Annual") + " Plan with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
Metod toString() should never be used to showcase the value of the object properties. For the overrides you can use commons library
public String toString() {
return new ToStringBuilder(this).
append("minutesAllowed", minutesAllowed).
append("minutesUsed", minutesUsed).
append("dataAllowed", dataAllowed).
append("dataUsed", dataUsed).
append("planType", planType).
toString();
}
you could implement the toString method as described in the following code
public class PhonePlan {
int minutesAllowed;
int minutesUsed;
int dataAllowed;
int dataUsed;
boolean planType;
public PhonePlan (int ma, int da, boolean pt){
this.minutesAllowed = ma;
this.planType = pt;
this.dataAllowed = da;
}
#Override
public String toString() {
return planType ? getPlanTypeBasedString("Weekly Plan") : getPlanTypeBasedString("Monthly Plan");
}
public String getPlanTypeBasedString(String planType){
return ( "Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) "+planType+" with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
}
I'm making a class for a game I'm making and cannot figure out how to return the highest 'reward' to a user:
What I'm trying to get it to do is return the reward based on the player's kills. If he has 38 kills, it should return only 300. Not 150 aswell.
class EnumTest {
private static int playerKills = 38;
private enum KillReward {
BEGINNER(10, 150),
JUNIOR(25, 300),
EXPERT(50, 500),
CHAMPION(100, 1000);
private KillReward(int kills, int reward) {
this.kills = kills;
this.reward = reward;
}
private int kills, reward;
private int getKillsNeeded() {
return kills;
}
private int getKillReward() {
return reward;
}
}
public static void main (String[] args) {
for (KillReward k : KillReward.values()) {
if (playerKills > k.getKillsNeeded()) {
System.out.println("Kills: " + playerKills + "; Reward: " + k.getKillReward());
}
}
}
}
There are a couple ways of doing this.
One easy way is assign the reward to a variable. At the end of that loop the reward variable below will be the highest kill reward that was applicable
public static void main (String[] args) {
KillReward reward = null;
for (KillReward k : KillReward.values()) {
if (playerKills > k.getKillsNeeded()) {
reward = k;
}
}
System.out.println("Kills: " + playerKills + "; Reward: " + k.getKillReward());
}
Note that this relies on the enum being listed in order which can sometimes be fragile. For example, if a new KillReward enum is added after CHAMPION but has a lower killsNeeded value, then it will not return the proper value.
A better solution would be to create a Comparator and use it to sort the enum values by killsNeeded first, thus ensuring that they are always in order. If you also sort it in descending order, then you can also break from your loop once you hit the first applicable one.
class EnumTest {
private enum KillReward {
BEGINNER(10, 150), JUNIOR(25, 300), EXPERT(50, 500), CHAMPION(100, 1000);
// Sort KillRewards once at initialization
private static final List<KillReward> sortedKillRewards = new ArrayList<KillReward>();
static {
for (KillReward k : values())
sortedKillRewards.add(k);
Collections.sort(sortedKillRewards, new Comparator<KillReward>() {
#Override
public int compare(KillReward o1, KillReward o2) {
return (o1.kills - o2.kills) * -1; // multiplying by -1 makes it
// descending
}
});
}
private KillReward(int kills, int reward) {
this.kills = kills;
this.reward = reward;
}
private int kills, reward;
private int getKillsNeeded() {
return kills;
}
private int getKillReward() {
return reward;
}
public static KillReward forKills(int killCount) {
for (KillReward k : sortedKillRewards)
if (killCount >= k.kills)
return k;
// must not have enough kills for any reward
return null;
}
}
public static void main(String[] args) {
int kills = 9;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
kills = 10;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
kills = 38;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
}
}
public class Fan {
public static void main(String[] args){
Fan fan1 = new Fan();
fan1.setSpeed(FAST);
fan1.setRadius(10);
fan1.setColor("yellow");
fan1.setOn(true);
System.out.println(fan1.toString());
}
// fan speed variables
final static int SLOW = 1;
final static int MEDIUM = 2;
final static int FAST = 3;
// Other fan variables
private int speed;
private boolean on; // true means on
private double radius; // radius of fan
String color;
// No-arg constructor
public void Fan(){
speed = SLOW;
on = false;
radius = 5;
color = "blue";
}
// Mutator methods
public void setSpeed(int newSpeed){
if(newSpeed < 0)
System.out.println("Illegal speed!");
else
speed = newSpeed;
}
public void setOn(boolean newOn){
on = newOn;
}
public void setRadius(int newRadius){
if(newRadius < 0)
System.out.println("Illegal radius!");
else
radius = newRadius;
}
public void setColor(String newColor){
color = newColor;
}
// Accessor methods
public int getSpeed(){
return speed;
}
public boolean getOn(){
return on;
}
public double getRadius(){
return radius;
}
public String getColor(){
return color;
}
// toString method to output Fan data
public String toString(){
if(on = false)
return "Fan is off.";
else
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
}
}
The above piece of code is simple but I was wondering how the toString method uses the on variable even though I didn't supply parameters for that method. Also, why do we not need to invoke get methods in the main class and only need to invoke the set methods? (please explain how each method invokes one another until the final output)
Thanks a lot!
As far as you are in this class body you can access everything (except for static can not access non-static). That means that you can easily set and get variables like that:
var = <value>;
System.out.println(var);
However nobody stops you from using the accessor methods - getter and setters. It is just not required.
One final note:
if(on = false)
This will always fail - it does assignment to false and then checks the newly assigned value (which is false). You need to check for equality here. Like that:
if(on == false)
Or even better:
if(!on)
I just copied-pasted your code into a new file and compiled it. It compiled and ran. The output was
$ java Fan
Fan Properties:
Fan speed: 3
Color: yellow
Radius: 10.0
This is because the comparison in your toString method is wrong. It should be as following:
public String toString(){
if(on)
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
else
return "Fan is off.";
}