Having trouble with java class methods - java

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 ...

Related

Combination of counter and user input using Thread in Java?

I am a student and am studying threads recently. What I am trying to do is to implement MVC pattern that manages functionalities such as start counting, stop counting, reverse counting and etc...
My final goal is that, I need to get an user input whilst the counter is counting from 1, and if I input 2 (assuming that option 2 is stopping the counter), the counter should stops counting.
For example:
Counting...
1
2
3
(If I press 2 here)
Counter stopped running!
Because this is the homework from my college, I cannot upload here the code I implemented.
What I did was,
MVC pattern:
Controller class= gets model and view with Controller constructor. This class also provides service() method that uses switch case to make user to input to select the options to run the functionality for counting (eg) case1: startCounting() case2: stopCounting(), and etc...)
View class = provides options using System.out.println and displayMenu() function.
Model class = implements the functionalities such as startCounting(), stopCounting and etc...
I now need to add threads for this implementation in order to interact the user input with this counting process.
Can I please get any hints? For example, which class should I extend the Thread and in what way should I implement run() menthod?
Skeleton code:
CountController class
public class CounterController {
private Counter model;
private CounterView view;
public CounterController(Counter model, CounterView view) {
this.model = model;
this.view = view;
}
}
Model Class
public class Counter {
private int count = 0;
private boolean counting = false;
private Integer ceiling = null;
private Integer floor = null;
private boolean reverse = false;
public void startCounting() {
counting = true;
while (counting && checkLimits()) {
try {
Thread.sleep(1000);
count = reverse ? count - 1 : count + 1;
// You should replace this print with something observable so the View can handle it
System.err.println(count);
} catch (InterruptedException ignored) {}
}
}
public void stopCounting() {
counting = false;
}
public void setReverse(boolean reverse) {
this.reverse = reverse;
}
public void setCeiling(Integer ceiling) {
this.ceiling = ceiling;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public int getCount() {
return count;
}
public void resetCount() {
count = 0;
}
private boolean checkLimits() {
if (null != ceiling && count >= ceiling) {
return false;
}
if (null != floor && count <= floor) {
return false;
}
return true;
}
}
View Class
public class CounterView {
private Counter model;
public CounterView(Counter model) {
this.model = model;
}
public void launch() {
}
}
ViewUntil Class
class ViewUtils {
static int displayMenu(String header, String[] options, String prompt) {
System.out.println("\n" + header);
for (int i = 0; i < options.length; i++) {
System.out.println((i+1) + ". " + options[i]);
}
while (true) {
Integer response = getInt(prompt, true);
int selection = response != null ? response : -1;
if (selection > 0 && selection <= options.length) {
return selection;
} else {
System.out.println("Invalid menu selection");
}
}
}
static String getString(String prompt, boolean allowBlank) {
Scanner s = new Scanner(System.in);
String response;
do {
System.out.println(prompt);
response = s.nextLine();
if (!allowBlank && "".equals(response)) {
response = null;
System.out.println("Blank entry is not allowed here.");
}
} while (null == response);
return response;
}
static Integer getInt(String prompt, boolean allowBlank) {
int response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
try {
response = Integer.parseInt(str);
return response;
} catch (NumberFormatException e) {
System.out.println("Invalid input - number required");
}
} while (true);
}
static Boolean getBoolean(String prompt, boolean allowBlank) {
prompt = prompt + "(y/n) ";
Boolean response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
if ("y".equals(str.toLowerCase())) {
return true;
}
if ("n".equals((str.toLowerCase()))) {
return false;
}
System.out.println("Invalid input - must be y or n");
} while (true);
}
}
Main Class
public class MainDriver {
public static void main(String[] args) {
Counter model = new Counter();
CounterView view = new CounterView(model);
CounterController controller = new CounterController(model, view);
controller.service();
}
}
Using "volatile" to coerce the thread Counter to check for the newest setting values in memory and not in its "cache".
public class Counter {
private int count = 0;
private volatile boolean counting = false;
private volatile Integer ceiling = null;
private volatile Integer floor = null;
private boolean reverse = false;
...
}

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;
}

Set up while statement to print out methods?

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

NumberVerify: missing return statement

import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
if((num%2)==0)
{
boolean yes = true;
return true;
}
}
public static boolean isEven( int num )
{
if((num%2)!=0)
{
boolean yes = false;
return false;
}
}
}
The error messages say "missing return statements" on the }'s.
I tried adding
return true;
after the set of braces nested by
if((num%2)==0)
and did something similar with the
if((num%2!=0)
nest, although with
return false;
That only caused the isOdd to pop up as true and isEven to pop up as false regardless of the inputted number itself.
Here is the runner program.
import static java.lang.System.*;
import java.util.Scanner;
public class NumberVerifyRunner
{
public static void main ( String[] args )
{
//add in input
System.out.println("5 is odd :: " + NumberVerify.isOdd(5));
System.out.println("5 is even :: " + NumberVerify.isEven(5));
System.out.println("0 is odd :: " + NumberVerify.isOdd(0));
System.out.println("0 is even :: " + NumberVerify.isEven(0));
System.out.println("2 is odd :: " + NumberVerify.isOdd(2));
System.out.println("2 is even :: " + NumberVerify.isEven(2));
//add in more test cases
}
}
How do I fix the missing return statements in the NumberVerify class?
You need to return a value if the 'if' clause is not satisfied.
All code blocks need to return a value. This solution should work well.
public static boolean isOdd(int num) {
if ((num % 2) == 0) {
return true;
} else {
return false;
}
}
public static boolean isEven(int num) {
if ((num % 2) != 0) {
return false;
} else {
return true;
}
}
Try adding return false after the first if statement and return true after the second.
Also you could just return the result of num%2==0 without the if statement due to the fact that num%2==0 is a boolean value. So you could also delete the if statements and do return( num%2)==0;
For the other one do return (num%2 )!=0;
isOdd and isEven must return boolean for all branches.
This will work
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
return numr%2 == 1;
}
public static boolean isEven( int num )
{
return num % 2 == 0;
}
}
In java your return statement is the last statement. In your case just change whit following code
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd(int num)
{
if(num%2 == 0)
{
return true;
}
return false;
}
public static boolean isEven( int num )
{
if(num%2 !=0 )
{
return true;
}
return false;
}
}
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
if((num%2)!=0)
{
boolean yes = true;
}
return yes;
}
public static boolean isEven( int num )
{
if((num%2)==0)
{
boolean yes = true;
}
return yes;
}
}
Your code have the return statement is out of the scope.
Method signature have return the boolean value but you put return statement if() control scope only so you change the public scope(current method scope).
Your All code path will not return values:
Consider your code :
public static boolean isOdd( int num )//Assume num as 7
{
if((num%2)==0)// 7 % 2 will be 1 , condition fails
{
boolean yes = true;
return true;// this statement won't be executed
}
// you have no return statement here
}
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
boolean isOddNumber = (num %2 ) !=0
return isOddNumber;
}
public static boolean isEven( int num )
{
boolean isEvenNumber = (num %2 )==0
return isEvenNumber;
}
}
you give a return to a if and forgot the else. In your method isOdd() the return is only in the if not in the method. you may change your code like this.
public static boolean isOdd( int num )
{
if((num%2)==0)
{
boolean yes = true;
return true;
} else {// you must add the else
return true;// return a boolean value here.true or false,it's up to you.
}
// Or add a return below without add the else.
return ture;// true or false,it's up to you.
}
public static boolean isEven( int num )
{
if((num%2)!=0)
{
boolean yes = false;
return false;
} else {// you must add the else
return true;// return a boolean value here.true or false,it's up to you.
}
// Or add a return below without add the else.
return ture;// true or false,it's up to you.
}

How to return the value of a method where the method name is given by a string?

I need to return the value of a method and also I need to print the name of the method including the object by which it is called. For example:
public class FindMethod {
public void accessor(String m){
String amount = "getamount()" ;
String str="";
if(m.equals("Receive(int)"))
str+= "LS."+amount;
System.out.println(str);
}
public static void main(String[] args)
{
FindMethod fm = new FindMethod();
fm.accessor("Receive(int)");
}
}
Result: LS.getamount()
The above program is printing the method name as a string including the object where LS is the object and getamount() is the method of another class LoanApprovalSystem().
But I need to print the integer value that will be returned by the result LS.getamount(). But I have returned LS.getamount() as a string. I am not sure how to return the actual value of LS.getamount() from the string.
Can any one give me some idea that, how can I return the value of the method getamount() which is given by a string?? I mean can I use the string LS.getamount() as a reference to call the method getamount() from the class LoanApprovalSystem()??
The class LoanApprovalSystem() is given below:
public class LoanApprovalSystem {
private static int amount;
private static String risklevel ;
private static boolean approve;
private static boolean message;
private static String result ;
public LoanApprovalSystem(){
}
void initialize(){
amount=0;
risklevel=null;
approve=false;
message=false;
}
public void Receive(int req){
amount = req;
}
public void Asses(int req){
if (req > 1000 && req <= 5000)
{
risklevel = "low";
approve = true;
}
else if (req > 5000 && req <= 10000)
{
risklevel = "high";
}
else
risklevel = " ";
}
public void Approval(int req){
if ((req > 10000) || ((req <= 10000) & getrisklevel() =="high"))
{
approve = false;
}
else if (amount <= 5000 && getrisklevel() == "low")
{
approve = true;
}
}
public void Sendmessage(String risklevel){
if(risklevel == "low")
{
message=true;
//System.out.println(message);
//System.out.println("Loan approved");
}
else
message=false;
}
public void Reply(boolean message, boolean approve){
if(message == true || approve == true)
{
result = ("Loan Approved");
//System.out.println("Loan Approved");
}
else
{
result = ("Loan Rejected");
//System.out.println("Loan Rejected");
}
}
public int getamount(){
return (amount);
}
public String getrisklevel(){
return(risklevel);
}
public boolean getapprove(){
return (approve);
}
public boolean getmessage(){
return(message);
}
public String getresult(){
return (result);
}
public String toString(){
String str = "";
str += "(" +result+ ").";
return str;
}
public static void main(String[] args){
LoanApprovalSystem LS = new LoanApprovalSystem();
TestdataGeneration testdata = new TestdataGeneration();
LS.initialize();
//for(int data:testdata.Testdata())
{
LS.Receive(testdata.thirddata());
LS.Asses(LS.getamount());
LS.Approval(LS.getamount());
LS.Sendmessage(LS.getrisklevel());
LS.Reply(LS.getmessage(), LS.getapprove());
System.out.println("Final state: "+LS);
}
}
}
Use reflection:
http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html
Class<?> c = Class.forName("className");
Method method = c.getDeclaredMethod ("methodName", parameterTypes)
Object o = method.invoke (objectToInvokeOn, paramList)
But usually you don't use reflection. Only if there is no other way to do.
Look for use and danger of reflection here https://softwareengineering.stackexchange.com/questions/123956/why-should-i-use-reflection

Categories

Resources