Set up while statement to print out methods? - java

Not the best title but basically I want to ask the user to enter a temperature, and then displays a list of substances that will freeze at that temperature and those that boil at that temperature. I want it to be in a while loop and I want the user to be able to go until they want to stop. Heres what I have so far, my first class and then a tester
public class FreezingPoint {
private int temperature;
public double getTemperature() {
return temperature;
}
public void setTemperature() {
this.temperature = temperature;
}
public boolean isEthylFreezing() {
boolean status;
if (temperature <= -173.0)
status = true;
else
status = false;
return status;
}
public boolean isEthylBoiling() {
boolean status;
if (temperature >= 172.0)
status = true;
else
status = false;
return status;
}
public boolean isOxygenFreezing() {
boolean status;
if (temperature <= -362.0)
status = true;
else
status = false;
return status;
}
public boolean isOxygenBoiling() {
boolean status;
if (temperature >= -306.0)
status = true;
else
status = false;
return status;
}
public boolean isWaterFreezing() {
boolean status;
if (temperature <= 32)
status = true;
else
status = false;
return status;
}
public boolean isWaterBoiling() {
boolean status;
if (temperature >= 212)
status = true;
else
status = false;
return status;
}
}
and now tester class
import java.util.Scanner;
public class TestFreezingPoint {
public static void main(String[] args) {
FreezingPoint fp = new FreezingPoint();
double temperature;
Scanner sc = new Scanner(System.in);
System.out.println("please enter a temp");
temperature = sc.nextDouble();
System.out.println("Is Water Freezing?" + fp.isWaterFreezing());
}
}
My problem is that the code isn't working properly and I'm confused as to where to go from here. I know how to setup the while loop and how to make it go until I want to stop but I'm not sure on how to properly print out the list of substances that will be displayed based off the users inputted temperature
Any help appreciated, pretty new to java and been stuck on this awhile
Thanks

I think you should use a different way of testing if something boils or freezes at a given temperature. In your example you would have to add two methods for every substance and then find a way to cycle through them.
It would probably be a lot easier if you used for example a list and then use a switch() statement to only add the substances to the list that boil or freeze at the given temperature. If you make a method that does so and give it the temperature as a parameter and have it return the populated list, you could easily loop through the list and print out every element.
I made a quick example for you:
public List<String> getSubstances(int temperature){
List<String> substances = new ArrayList<String>();
switch(temperature){
case 0:
substances.add("Water");
case 100:
substances.add("Water");
}
return substances;
}
This would be a way easier solution and you can cycle through the list very easily to print it out.

I would suggest to use a class to represent the substances:
public class Substance {
private String name;
private double tempFreeze;
private double tempBoil;
public Substance(String name, double tempFreeze, double tempBoil) {
this.name = name;
this.tempFreeze = tempFreeze;
this.tempBoil = tempBoil;
}
public double getTempBoil() { return tempBoil; }
public double getTempFreeze() { return tempFreeze; }
public String getName() { return name; }
public String getState(double temp) {
if (temp <= tempFreeze) {
return "freeze";
} else if (temp >= tempBoil) {
return "boil";
}
return "liquid";
}
}
To be used like :
public static void main(String[] args) {
List<Substance> list = new ArrayList<>();
list.add(new Substance("ethyl", -173, 172));
list.add(new Substance("Oxygen", -362, -306));
list.add(new Substance("water", 32, 212));
Scanner sc = new Scanner(System.in);
do {
System.out.println("please enter a temp");
double temperature = sc.nextDouble();
sc.nextLine(); //consume return char
for (Substance s : list) {
System.out.println(s.getName() + " is in state : " + s.getState(temperature));
}
System.out.println("\nDo you want to stop ? Write 'yes' to stop");
} while (!sc.nextLine().contains("y"));
}
Execution example :
please enter a temp
125
ethyl is in state : liquid
Oxygen is in state : boil
water is in state : liquid
Do you want to stop ? Write 'yes' to stop
y

Related

How to get user input and store in custom object? JAVA

Henlo,
Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());.
But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.
All the code that is meant to run should be inside the main method in Step1.java
Here are the 3 classes used for the code (ignore comments they are just notes for me):
package SmartHomeApp;
public class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
//YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {name = value;}
public void setLocation(double value) {location = value;}
public void setSwitchedOn(boolean value) {switchedOn = value;}
public String getName() {return name;}
public double getLocation() {return location;}
public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;
public class SmartHome
{
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {return smrtDev.length;}
// can't do toString() for some reason??
public void ToString() {
for(int i=0; i<size();i++)
{
if(smrtDev[i] != null ){
System.out.println("----------");
System.out.println("-DEVICE "+(i+1)+"-");
System.out.println("----------");
System.out.println("Name: "+smrtDev[i].getName());
System.out.println("Location: "+smrtDev[i].getLocation());
System.out.println("Switched On: "+smrtDev[i].getSwitchedOn());
}
}
}
}
package SmartHomeApp;
import java.util.*;
public class Step1 {
public static void main(String args[]) {
SmartHome app = new SmartHome(loadDataFromConfig());
app.ToString();
}
public static SmartDevice[] loadDataFromConfig()
{
SmartDevice[] dev = new SmartDevice[20];
dev[0] = new SmartDevice("device 1",1.3,true);
dev[1] = new SmartDevice("device 2",2.3,false);
dev[2] = new SmartDevice("device 3",3.3,true);
dev[4] = new SmartDevice("device 5",4.3,false);
dev[19] = new SmartDevice("device 20",5.3,false);
return dev;
}
}
Some of the improvements required in your code are as follows:
Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
Enter size:
2
Name:
Light Amplification by Stimulated Emission of Radiation
Location:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:83)
Given below is a sample code incorporating the improvements mentioned above:
import java.util.Scanner;
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
// YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {
name = value;
}
public void setLocation(double value) {
location = value;
}
public void setSwitchedOn(boolean value) {
switchedOn = value;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean getSwitchedOn() {
return switchedOn;
}
#Override
public String toString() {
return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
}
}
class SmartHome {
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {
return smrtDev.length;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (SmartDevice smartDevice : smrtDev) {
sb.append(smartDevice.toString()).append("\n");
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int size = getPositiveInt(myObj, "Enter size: ");
SmartDevice[] newList = new SmartDevice[size];
for (int i = 0; i < newList.length; i++) {
System.out.print("Name: ");
String x = myObj.nextLine();
double y = getFloatingPointNumber(myObj, "Location: ");
boolean z = getBoolean(myObj, "Is on?: ");
newList[i] = new SmartDevice(x, y, z);
}
SmartHome newDevice = new SmartHome(newList);
System.out.println(newDevice);
}
static int getPositiveInt(Scanner in, String message) {
boolean valid;
int n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Integer.parseInt(in.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("This in not a positive integer. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static double getFloatingPointNumber(Scanner in, String message) {
boolean valid;
double n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Double.parseDouble(in.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("This in not a number. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static boolean getBoolean(Scanner in, String message) {
System.out.print(message);
return Boolean.parseBoolean(in.nextLine());
}
}
A sample run:
Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]
So as suggested I tried to do the following:
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size: ");
int size = myObj.nextInt();
SmartDevice[] newList = new SmartDevice[size];
for(int i =0; i<newList.length;i++) {
System.out.println("Name: ");
String x = myObj.next();
System.out.println("Location: ");
double y = myObj.nextDouble();
System.out.println("Is on?: ");
boolean z = myObj.nextBoolean();
newList[i] = new SmartDevice(x,y,z);
}
SmartHome newDevice = new SmartHome(newList);
newDevice.ToString();
}
Got it working but not sure if this is the most efficient way to do so??

How to get rid of multiple return statements in methods

This is bank customer class, that contains multiple return statement. My question is how can I get rid of those multiple return statements and I want to have only one multiple returns at the end of each method.
public class BankCustomer {
//define the attribute
private String name;
private int chequeAcctNum;
private double chequeBal;
private int savingAcctNum;
private double savingBal;
//define constractor
public BankCustomer(String n, int chqAcctNum, double chqBal
, int savAcctNum, double savBal)
{
name = n;
chequeAcctNum = chqAcctNum;
chequeBal = chqBal;
savingAcctNum = savAcctNum;
savingBal = savBal;
}
//define the methods
// Call withdraw from chequing method
public boolean withdrawChequing(double amount) {
if(chequeBal >= amount) {
chequeBal-=amount;
return true;
} else {
return false;
}
}
In my opinion, a method with multiple return statements is perfectly fine. If used correctly, it can make your code more readable. You don't need to change the method.
If you insist, here's how to reduce it to one return statement.
Create a boolean variable that stores the return value:
boolean retVal = false;
And then check the condition:
if(chequeBal >= amount) {
chequeBal-=amount;
retVal = true;
}
Then return the retVal:
return retVal;
Something like this:
public boolean withdrawChequing(double amount) {
boolean bRetVal = false;
if(chequeBal >= amount) {
chequeBal-= amount;
bRetVal = true;
}
return bRetVal;
}

Trying to use 2 objects in Java

My goal is to have 2 different objects fight each other, and show the results. My problem is I cant figure out how to set the attack and health properly so that it actually updates the way it is supposted to.
import java.util.Random;
import java.util.Scanner;
/**
*
* #author Brenton
*/
public class Fighter {
private String name;
private int attack;
private int level = 1;
private int health = 50;
private boolean isAlive = true;
private Fighter fighterTwo;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAttack() {
Random generator = new Random();
attack = generator.nextInt(10) * level + 1;
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getLevel() {
if(level >= 60)
{
level = 60;
}
return this.level;
}
public void setLevel(int level) {
this.level = level;
}
public int getHealth() {
if(this.health <= 0)
{
this.health = 0;
}
return this.health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isAlive() {
if(this.health <= 0)
{
this.isAlive = false;
}
return this.isAlive;
}
public static String getWelcome() {
String welcome = "Hello and welcome to FightClub, do you wish to fight, yes or no? ";
return welcome;
}
public String getPunch(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
String hit = "You choose to punch the other fighter and dealt " + getAttack() + " damage, your opponent now has " + this.decreaseHitPoints(fighterTwo) + " health remaining";
return hit;
}
public int decreaseHitPoints(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
int health = fighterTwo.getHealth();
int attack = getAttack();
health = health - attack;
return health;
}
public static String invalidInput() {
String invalid = "I am sorry that is not a valid input option ";
return invalid;
}
public void getWinner(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
if(this.isAlive() == false && fighterTwo.isAlive() == false)
{
System.out.println("Both fighters have fallen heroically");
}
else if(this.isAlive() == true && fighterTwo.isAlive() == false)
{
System.out.println(this.getName() + " is victorious! ");
}
else if(this.isAlive() == false && fighterTwo.isAlive() == true)
{
System.out.println(fighterTwo + " is victorious! ");
}
else
{
System.out.println("ERROR ERROR ERROR");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fighter a = new Warrior();
Fighter b = new Dragon();
System.out.print(getWelcome());
while(in.hasNextLine())
{
switch(in.nextLine())
{
case "no":
System.out.println("Wow, you are not even gonna try, you have lost!");
break;
case "yes":
System.out.println("Let the fight begin! ");
while(a.isAlive() && b.isAlive())
{
System.out.println("Do you want to punch, kick, or headbutt the other fighter? ");
switch(in.nextLine())
{
case "punch":
System.out.println(a.getPunch(b));
break;
/*case "kick":
System.out.println(a.getKick(b));
break;
case "headbutt":
System.out.println(a.getHeadbutt(b));
break;*/
default :
System.out.println(invalidInput());
break;
}
}
default:
System.out.println(invalidInput());
break;
}//end of first switch statement
}//end of first while loop
}//end of main
}
You're calculating the attack correctly. You're just not updating the state of the other fighter.
In your main() method you launch the attack with
System.out.println(a.getPunch(b));
That's just fine. a throws a Punch at b, then you print out the hit points returned from getPunch(). So let's dig deeper into getPunch() to try to find the problem.
In getPunch() you end up invoking
this.decreaseHitPoints(fighterTwo)
while constructing the return String. This seems like the right approach, so is there a problem in decreaseHitPoints()?
public int decreaseHitPoints(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
int health = fighterTwo.getHealth();
int attack = getAttack();
health = health - attack;
return health;
}
You assign the fighterTwo argument to your fighterTwo field. Not sure why, but that's not wrong per se. Then you get his health into a local variable called health. Then you get the attack into a local variable called attack. Then you subtract attack from health, and then return the calculated value. But you never update the health value on fighterTwo! So you just need one more line in your program: right before your return statement, insert
fighterTwo.setHealth(health);

Displaying error on toString method

I am working on this code where a menu pops up and you enter a choice to enter a computer or to display the computers added. However the only problem i have is when it displays it give me a null for the type of cpu and its speed. It is suppose to display like this
\nBrandName:\tDell\n
CPU:\t\tpentium3,500HZ\n
Memory:\t\t398M\n
Price:\t\t$1,390.00\n\n
but it displays like this
\nBrandName:\tDell\n
CPU:\t\tnullHZ\n
Memory:\t\t398M\n
Price:\t\t$1,390.00\n\n
here is my code there are three classes a main Assignment4 class a CPU class and a computer class, I believe my error is somewhere in my computer class.
here is my Assignment4 class
// Description: Assignment 4 class displays a menu of choices to a user
// and performs the chosen task. It will keep asking a user to
// enter the next choice until the choice of 'Q' (Quit) is entered.
import java.io.*;
import java.util.*;
public class Assignment4
{
public static void main (String[] args)
{
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
String inputInfo;
String brandName;
double price;
int memory;
String cpuType;
int cpuSpeed;
String line = new String();
// instantiate a Computer object
Computer computer1 = new Computer();
printMenu();
//Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1)
{
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1)
{
case 'A': //Add Computer
System.out.print("Please enter the computer information:\n");
System.out.print("Enter a brand name:\n");
brandName = scan.nextLine();
computer1.setBrandName(brandName);
System.out.print("Enter a computer price:\n");
price = Double.parseDouble(scan.nextLine());
computer1.setPrice(price);
System.out.print("Enter a computer memory:\n");
memory = Integer.parseInt(scan.nextLine());
computer1.setMemory(memory);
System.out.print("Enter a cpu type:\n");
cpuType = scan.nextLine();
System.out.print("Enter a cpu speed:\n");
cpuSpeed = Integer.parseInt(scan.nextLine());
computer1.setCPU(cpuType, cpuSpeed);
break;
case 'D': //Display computer
System.out.print(computer1);
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
}
/** The method printMenu displays the menu to a user**/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Computer\n" +
"D\t\tDisplay Computer\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
here is my CPU class
public class CPU
{
private String type = "?";
private int speed= 0;;
public CPU(String type, int speed)
{
this.type = type;
this.speed = speed;
}
public String getType()
{
return type;
}
public int getSpeed()
{
return speed;
}
public void setType(String type)
{
this.type = type;
}
public void setSpeed(int speed)
{
this.speed = speed;
}
public String toString()
{
String result = this.type + "," + this.speed + "HZ";
return result;
}
}
and finally my Computer class
public class Computer
{
private String brandName;
private int memory;
private double price;
CPU Cpu;
public Computer()
{
brandName = "?";
memory = 0;
price = 0.0;
CPU Cpu = new CPU("?", 0);
}
public String getBrandName()
{
return brandName;
}
public CPU getCPU()
{
return Cpu;
}
public int getMemory()
{
return memory;
}
public double getPrice()
{
return price;
}
public void setBrandName(String BrandName)
{
brandName = BrandName;
}
public void setCPU(String cpuType, int cpuSpeed)
{
CPU cpu = new CPU(cpuType, cpuSpeed);
}
public void setMemory(int memoryAmount)
{
memory = memoryAmount;
}
public void setPrice(double price)
{
this.price = price;
}
public String toString()
{
String output = "\n"+"BrandName:"+"\t"+brandName+"\n"+
"CPU:\t\t"+Cpu+"HZ\n"+
"Memory:\t\t"+memory+"M\n"+
"Price:\t\t"+"$"+price+"\n\n";
return output;
}
}
You create a new CPU variable in the method setCPU, which gets destroyed when the method ends. It should instead change the instance variable Cpu, so that the information is retained.
You have make changes here:
Computer constructor:
CPU Cpu = new CPU("?", 0); `to` Cpu = new CPU("?", 0);
Computer's setCPU(String cpuType, int cpuSpeed)
CPU cpu = new CPU(cpuType, cpuSpeed); `to`
Cpu.setType(cpuType);
Cpu.setSpeed(cpuSpeed);

Having trouble with java class methods

ok so my assignment I'm supposed to write a class that stores a temperature that the user gives and checks it with the set parameters to see if Ethy/Oxygen/Water are either freezing or boiling and then display it at the end which ones will be freezing/boiling at the temperature that they entered. I have the majority of both the class and tester completed but I'm getting several errors on my code. I'm not asking anyone to give me the answer but if you could tell me what I'm doing wrong I would greatly appreciate it. Here is my code for class:
public class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private Boolean isEthylFreezing(int temperature) {
if (temperature <= -173) {
return true;
} else {
return false;
}
}
private Boolean isEthylBoiling(int temperature) {
if (temperature >= 172) {
return true;
} else {
return false;
}
}
private Boolean isOxygenFreezing(int temperature) {
if (temperature <= -362) {
return true;
} else {
return false;
}
}
private Boolean isOxygenBoiling(int temperature) {
if (temperature >= -306) {
return true;
} else {
return false;
}
}
private Boolean isWaterFreezing(int temperature) {
if (temperature <= 32) {
return true;
} else {
return false;
}
}
private Boolean isWaterBoiling(int temperature) {
if (temperature >= 212) {
return true;
} else {
return false;
}
}
public String showTempinfo() {
if (isEthylFreezing()) {
System.out.println("Ethyl will freeze");
}
if (isEthylBoiling()) {
System.out.println("Etheyl will boil");
}
if (isOxygenFreezing()) {
System.out.println("Oxygen will freeze");
}
if (isOxygenBoiling()) {
System.out.println("Oxygen will Boil");
}
if (isWaterFreezing()) {
System.out.println("Water will freeze");
}
if (isWaterBoiling()) {
System.out.println("Water will boil");
}
}
}
and the code for my tester is below:
import java.util.Scanner;
public class FreezingBoilingTester {
public static void main(String[] args) {
int temperature;
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(0);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
temperature = scan.nextInt();
System.out.println(showTempinfo());
}
}
1) don't pass the temp inside methods, because you already have this value in member variable.
2) you can change if (condition) then true else false into return (condition) and it will be the same result, just for readability .
3) you should return boolean not Boolean wrapper until you need the wrapper.
public final class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private boolean isEthylFreezing() {
return (temperature <= -173);
}
private boolean isEthylBoiling() {
return (temperature >= 172);
}
private boolean isOxygenFreezing() {
return (temperature <= -362);
}
private boolean isOxygenBoiling() {
return (temperature >= -306);
}
private boolean isWaterFreezing() {
return (temperature <= 32) ;
}
private boolean isWaterBoiling() {
return (temperature >= 212);
}
public String showTempinfo() {
StringBuilder result = new StringBuilder();
if (isEthylFreezing()) {
result.append("Ethyl will freeze");
result.append("\n");
}
if (isEthylBoiling()) {
result.append("Etheyl will boil");
result.append("\n");
}
if (isOxygenFreezing()) {
result.append("Oxygen will freeze");
result.append("\n");
}
if (isOxygenBoiling()) {
result.append("Oxygen will Boil");
result.append("\n");
}
if (isWaterFreezing()) {
result.append("Water will freeze");
result.append("\n");
}
if (isWaterBoiling()) {
result.append("Water will boil");
result.append("\n");
}
return result.toString();
}
}
Main:
import java.util.Scanner;
public class FreezingBoilingTester
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
int temperature = scan.nextInt();
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(temperature );
System.out.println(temp1.showTempinfo());
}
}
updated:
you can use String concatenation:
String result = "";
if ( condition ) {
result += "new result";
result += "\n";
}
but this is not recommended in term of performance, because each += operation will create another String object in memory holding the new result.
The problem is that your private methods are taking in a temperature and yet, you are not passing one in for your showTempinfo() method. Try removing the input parameters and using the temp set in the class. Also, you need to somehow set the temp before you call showTempinfo().
Hope this helps.
You're not passing the input that the user is giving you into the constructor for your FreezingBoilingPoints class. You're initializing that class with 0 and then asking for a temperature from the user. There's no relationship between the temperature the user provided and the class that you're using to test it.
You need to construct your FreezingBoilingPoints object in your main method, then call showTempinfo() on it. Also, your private calc methods should use the member variable; there's no need to take it as a parameter.
You need to pass the user input, temperature, into your FreezingBoilingPoints constructor. Also, the method showTempInfo() is instance specific. For example, you need to instantiate your object, temp1, by passing the user input with the constructor and then invoke temp1.showTempInfo()
Here we go:
1) All your "is..." methods are expecting for an int parameter, however when you're calling them, you're not passing anything. Remove the int parameter from either the method implementation or the method calls
2) You're missing a closing bracket for the method isWaterBoiling;
3) You marked the method "showTempinfo" as returning String, but you are not returning anything for that method. Either add the return command or remove the "String" from the method signature.
In your showTempinfo(), you try to do isEthylFreezing().
But it can't work ... isEthylFreezing is waiting for an int ... but it gets nothing ...

Categories

Resources