Combination of counter and user input using Thread in Java? - 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;
...
}

Related

View responsibilities in MVC patten in Java

This is my first time using MVC pattern (no GUI) and i have a little bit of confusion in my head. I am realizing a Menu.
Can the view ask to other classes, for example an InputData class with only static methods, to receive user's input and print some messages of errors regarding the input? (look at CASE 1) Or it is controller's job to recive input from the user? (look at CASE 2) Or maybe it is Main class's job?
Which code is better between:
controller
logInModel.logIn();
if(logInModel.getBool()) {
//do something
} else{
//do something
}
LogInModel
private final String password = "abc"
private boolean logInSuccess = false;
public void logIn(String s) {
if(s.equals("abc")) logInSuccess = true;
}
public boolean getBool {
return logInSuccess;
}
or
controller
if(logInModel.logIn()) {
//do something
} else{
//do something
}
LogInModel
private final String password = "abc"
public boolean logIn(String s) {
return s.equals("abc") ? true : false;
}
CASE 1
Controller
int intValue = view.askNumericInput(str);
View
public int askNumericInput(String str) {
return InputData.readInteg(str);
}
Here the View is asking to the InputData class to take user's input and check it. I do not know if this is allowed in the MVC pattern.
InputData
public static int readInteg(String str)
{
boolean end = false;
int value = 0;
Scanner sc = new Scanner(System.in);
do
{
System.out.print(str);
try
{
value = sc.nextInt();
end = true;
}
catch (InputMismatchException e)
{
System.out.println(/*message*/);
}
} while (!end);
return value;
}
CASE 2
Controller
try {
int i = InputData.readInteg();
} catch (InputMismatchException e) {
view.printSomething(InputData.getMsg());
}
View
public int printSomething(String s) {
System.out.println(s);
}
InputData
public int readInteg() {
Scanner sc = new Scanner(System.in);
int value = 0;
value = sc.nextInt();
return valoreLetto;
}
public String getMsg() {
return ERROR_MSG;
}
I'm confused.

How to merge two alike items within the ArrayList?

So, I have 1 superclass DessertItem. Which has 4 subclasses Candy, Cookie, Ice Cream, Sundae. The Sundae class extends the Ice Cream class. Superclass is an abstract class. I also have a separate class which does not belong to the superclass, but in the same package - Order. There is another class - DessertShop, where the main is located.
Candy, Cookie classes implement SameItem<> generic class. The generic interface SameItem<> class looks like this:
public interface SameItem<T> {
public boolean isSameAs(T other);
}
The Candy, Cookie classes have this method:
#Override
public boolean isSameAs(Candy other) {
if(this.getName() == other.getName() && this.getPricePerPound() == other.getPricePerPound()) {
return true;
}
else {
return false;
}
}
And something similar, but for the cookie class.
All the subclasses have these methods :
default constructor,
public Cookie(String n, int q, double p) {
super(n);
super.setPackaging("Box");
cookieQty = q;
pricePerDozen = p;
}
public int getCookieQty() {
return cookieQty;
}
public double getPricePerDozen() {
return pricePerDozen;
}
public void setCookieQty(int q) {
cookieQty = q;
}
public void setToppingPricePricePerDozen(double p) {
pricePerDozen = p;
}
#Override
public double calculateCost() {
double cookieCost = cookieQty * (pricePerDozen/12);
return cookieCost;
}
and toString() method
So, what my program does is gets the input from the User, asks the name of the dessert, asks the quantity, or the quantity according to the dessert, ask the unit price. Asks the payment method. And then prints the receipt. This how the Order class looks like:
import java.util.ArrayList;
import java.util.List;
public class Order extends implements Payable{
//attributes
PayType payMethod;
private ArrayList<DessertItem> OrderArray;
//Constructor
public Order() {
OrderArray = new ArrayList<>();
payMethod = PayType.CASH;
}
//methods
public ArrayList<DessertItem> getOrderList(){
return OrderArray;
}// end of getOrderList
public ArrayList<DessertItem> Add(DessertItem addDesert){
enter code here
OrderArray.add(addDesert);
/* for(DessertItem i : getOrderList()) {
if(i instanceof Candy) {
for(DessertItem j : getOrderList()) {
if(j instanceof Candy) {
if(((Candy) i).isSameAs((Candy) j)) {
*/
//this is what I have tried so far, but I am lost
}
}
}
} else if(i instanceof Cookie) {
for (DessertItem j : getOrderList()) {
if(((Cookie) i).isSameAs((Cookie)j)) {
OrderArray.add(j);
} else {
OrderArray.add(i);
}
}
}
}
return OrderArray;
}// end of Add
public int itemCount(){
int counted = OrderArray.size();
return counted;
}//end of itemCount
public double orderCost() {
double orderResult = 0;
for(int i=0; i<OrderArray.size(); i++) {
orderResult = orderResult + OrderArray.get(i).calculateCost();
}
return orderResult;
}
public double orderTax() {
double taxResult = 0;
for(int i = 0; i<OrderArray.size(); i++) {
taxResult = taxResult + OrderArray.get(i).calculateTax();
}
return taxResult;
}
public double orderTotal() {
double ordertotal = orderTax() + orderCost();
return ordertotal;
}
#Override
public PayType getType() {
// TODO Auto-generated method stub
return payMethod;
}
#Override
public void setPayType(PayType p) {
payMethod = p;
}
public String toString() {
String finalOutput = "";
finalOutput += "------------------------Receipt--------------------------\n";
for(int i = 0; i < OrderArray.size(); i++) {
finalOutput = finalOutput + OrderArray.get(i).toString();
}
finalOutput += "--------------------------------------------------\n";
String line2 = "Total Number of items in order: " + itemCount() + "\n";
String line3 = String.format("Order Subtotals:\t\t\t\t $%-6.2f", orderCost());
String line4 = String.format("[Tax: $%.2f]\n", orderTax());
String line5 = String.format("\nOrder Total:\t\t\t\t\t $%-6.2f\n", orderTotal());
String outputVar = String.format("%s\n%s%s%17s", line2, line3, line4, line5);
String ending = "----------------------------------------------------";
String payType = String.format("\nPaid for with: %s", payMethod.name());
return finalOutput + outputVar + ending + payType;
}
So, my question is, how can I combine like items into one item?

Confusion on using instanceof along with other inherited data

I have already made a posting about this program once, but I am once again stuck on a new concept that I am learning (Also as a side note; I am a CS student so please DO NOT simply hand me a solution, for my University has strict code copying rules, thank you.). There are a couple of difficulties I am having with this concept, the main one being that I am having a hard time implementing it to my purposes, despite the textbook examples making perfect sense. So just a quick explanation of what I'm doing:
I have an entity class that takes a Scanner from a driver. My other class then hands off the scanner to a superclass and its two subclasses then inherit that scanner. Each class has different data from the .txt the Scanner read through. Then those three classes send off their data to the entity to do final calculations. And that is where my problem lies, after all the data has been read. I have a method that displays a new output along with a few methods that add data from the super along with its derived classes.EDIT: I simply cannot figure out how to call the instance variable of my subclasses through the super so I can add and calculate the data.
Here are my four classes in the order; Driver, Entity, Super, Subs:
public static final String INPUT_FILE = "baseballTeam.txt";
public static void main(String[] args) {
BaseballTeam team = new BaseballTeam();
Scanner inFile = null;
try {
inFile = new Scanner(new File(INPUT_FILE));
team.loadTeam(inFile);
team.outputTeam();
} catch (FileNotFoundException e) {
System.out.println("File " + INPUT_FILE + " Not Found.");
System.exit(1);
}
}
}
public class BaseballTeam {
private String name;
private Player[] roster = new Player[25];
Player pitcher = new Pitcher();
Player batter = new Batter();
BaseballTeam() {
name = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public void loadTeam(Scanner input) {
name = input.nextLine();
for (int i = 0; i < roster.length; i++) {
if (i <= 9) {
roster[i] = new Pitcher();
}
else if ((i > 9) && (i <= 19)) {
roster[i] = new Batter();
}
else if (i > 19) {
roster[i] = new Player();
}
roster[i].loadData(input);
roster[i].generateDisplayString();
//System.out.println(roster[i].generateDisplayString()); //used sout to test for correct data
}
}
public void outputTeam() {
if ((pitcher instanceof Player) && (batter instanceof Player)) {
for (int i = 0; i < roster.length; i++) {
System.out.println(roster[i].generateDisplayString());
}
}
//How do I go about doing calculates?
public int calculateTeamWins() {
if ((pitcher instanceof ) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamSaves() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamERA() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamWHIP() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamBattingAverage() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamHomeRuns() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamRBI() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateStolenBases() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
}
public class Player {
protected String name;
protected String position;
Player(){
name = "";
position = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public String getPosition() {
return position;
}
public void setPosition(String aPosition) {
position = aPosition;
}
public void loadData(Scanner input){
do {
name = input.nextLine();
} while (name.equals(""));
position = input.next();
//System.out.println(generateDisplayString());
}
public String generateDisplayString(){
return "Name: " + name + ", Position:" + position;
}
}
public class Pitcher extends Player {
private int wins;
private int saves;
private int inningsPitched;
private int earnedRuns;
private int hits;
private int walks;
private double ERA;
private double WHIP;
Pitcher() {
super();
wins = 0;
saves = 0;
inningsPitched = 0;
earnedRuns = 0;
hits = 0;
walks = 0;
}
public int getWins() {
return wins;
}
public void setWins(int aWins) {
wins = aWins;
}
public int getSaves() {
return saves;
}
public void setSaves(int aSaves) {
saves = aSaves;
}
public int getInningsPitched() {
return inningsPitched;
}
public void setInningsPitched(int aInningsPitched) {
inningsPitched = aInningsPitched;
}
public int getEarnedRuns() {
return earnedRuns;
}
public void setEarnedRuns(int aEarnedRuns) {
earnedRuns = aEarnedRuns;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getWalks() {
return walks;
}
public void setWalks(int aWalks) {
walks = aWalks;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
wins = input.nextInt();
saves = input.nextInt();
inningsPitched = input.nextInt();
earnedRuns = input.nextInt();
hits = input.nextInt();
walks = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateERA();
calculateWHIP();
return String.format(super.generateDisplayString() + ", Wins:%1d, Saves:%1d,"
+ " ERA:%1.2f, WHIP:%1.3f ", wins, saves, ERA, WHIP);
}
public double calculateERA() {
try {
ERA = ((double)(earnedRuns * 9) / inningsPitched);
} catch (ArithmeticException e) {
ERA = 0;
}
return ERA;
}
public double calculateWHIP() {
try {
WHIP = ((double)(walks + hits) / inningsPitched);
} catch (ArithmeticException e) {
WHIP = 0;
}
return WHIP;
}
}
public class Batter extends Player {
private int atBats;
private int hits;
private int homeRuns;
private int rbi;
private int stolenBases;
private double batAvg;
Batter() {
super();
atBats = 0;
hits = 0;
homeRuns = 0;
rbi = 0;
stolenBases = 0;
}
public int getAtBats() {
return atBats;
}
public void setAtBats(int aAtBats) {
atBats = aAtBats;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getHomeRuns() {
return homeRuns;
}
public void setHomeRuns(int aHomeRuns) {
homeRuns = aHomeRuns;
}
public int getRbi() {
return rbi;
}
public void setRbi(int aRbi) {
rbi = aRbi;
}
public int getStolenBases() {
return stolenBases;
}
public void setStolenBases(int aStolenBases) {
stolenBases = aStolenBases;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
atBats = input.nextInt();
hits = input.nextInt();
homeRuns = input.nextInt();
rbi = input.nextInt();
stolenBases = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateBattingAverage();
return String.format(super.generateDisplayString() +
", Batting Average:%1.3f, Home Runs:%1d, RBI:%1d, Stolen Bases:%1d"
, batAvg, homeRuns, rbi, stolenBases);
}
public double calculateBattingAverage() {
try{
batAvg = ((double)hits/atBats);
} catch (ArithmeticException e){
batAvg = 0;
}
return batAvg;
}
}
Also, its probably easy to tell I'm still fairly new here, because I just ran all my classes together in with the code sample and I can't figure out to add the gaps, so feel free to edit if need be.
The typical usage of instanceof in the type of scenario you're describing would be
if (foo instanceof FooSubclass) {
FooSubclass fooSub = (FooSubclass) foo;
//foo and fooSub now are references to the same object, and you can use fooSub to call methods on the subclass
} else if (foo instanceof OtherSubclass) {
OtherSubclass otherSub = (OtherSubclass) foo;
//you can now use otherSub to call subclass-specific methods on foo
}
This is called "casting" or "explicitly casting" foo to FooSubclass.
the concept to call the methods of your subclasses is called polymorphism.
In your runtime the most specific available method is called provided that the method names are the same.
so you can
Superclass class = new Subclass();
class.method();
and the method provided that overwrites the method in Superclass will be called, even if it's defined in the Subclass.
Sorry for my english, I hope that helps a little bit ;-)

Java cannot find symbol error - a method from another class

I'm trying to access the method changeAll from class MarkMaker the following way:
import java.util.Scanner;
class Question10e
{
public static void main(String[] args)
{
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Enter mark 1: ");
int newm1=input.nextInt();
System.out.print("Enter mark 2: ");
int newm2=input.nextInt();
System.out.print("Enter mark 3: ");
int newm3=input.nextInt();
String linem=input.nextLine();
System.out.print("Enter a master password: ");
String masterpass = input.next();
linem=input.nextLine();
MarkMaker mm = new MarkMaker(masterpass);
Mark masterMark1 = mm.makeMark(newm1);
Mark masterMark2 = mm.makeMark(newm2);
Mark masterMark3 = mm.makeMark(newm3);
try{
System.out.println("The new mark 1 is "+masterMark1.provisional(masterpass));
System.out.println("The new mark 2 is "+masterMark2.provisional(masterpass));
System.out.println("The new mark 3 is "+masterMark3.provisional(masterpass));
System.out.println("The new master password is is "+masterMark1.returnPass());
int avg = mm.average();
System.out.println("The average is "+avg);
changeAll(5.5, 3);
}
catch(IncorrectPasswordException e){}
}
}
This is the MarkMaker class:
import java.util.*;
class MarkMaker{
private String masterPass = "";
private ArrayList<Mark> masterArr = new ArrayList<Mark>();
public MarkMaker(String masterPass)
{
this.masterPass = masterPass;
}
public Mark makeMark(int m)
{
Mark newMarkObj = new Mark(m,masterPass);
masterArr.add(newMarkObj);
return newMarkObj;
}
public ArrayList<Mark> returnMasterArr()
{
return masterArr;
}
public int average() throws IncorrectPasswordException
{
int n = 0;
for(int i=0; i<masterArr.size(); i++)
{
n = n + masterArr.get(i).provisional(masterPass);
}
int avg = n/masterArr.size();
return avg;
}
public void changeAll(double d, int x) throws IncorrectPasswordException
{
for(int i=0; i<masterArr.size(); i++)
{
double currentMark = masterArr.get(i).provisional(masterPass);
System.out.println("Current mark is: "+currentMark);
currentMark = currentMark*d;
System.out.println("Current mark is: "+currentMark);
currentMark = Math.ceil(currentMark);
System.out.println("Current mark is: "+currentMark);
}
} }
And this is the Mark class:
class Mark
{
private int value;
private String password;
boolean released;
public Mark(int value, String password)
{
this.value = value;
this.password = password;
released = false;
}
public void release(String p) throws IncorrectPasswordException
{
if(p.equals(password))
{
if(released==false)
released = true;
}
else throw new IncorrectPasswordException(p);
}
public int value() throws UnReleasedException
{
if(released==true)
return value;
else
throw new UnReleasedException();
}
public int provisional(String p) throws IncorrectPasswordException
{
if(p.equals(password))
return value;
else
throw new IncorrectPasswordException(p);
}
public void change(String p, int arg) throws IncorrectPasswordException
{
if(p.equals(password))
value = arg;
else
throw new IncorrectPasswordException(p);
}
public String returnPass()
{
return password;
}
public boolean isReleased()
{
return released;
}
public boolean equals(Mark m2) throws UnReleasedException
{
if(this.isReleased() && m2.isReleased())
{ //it throws an error, that's why i'm using the Unreleased Exception
if(this.value()==m2.value())
return true;
}
throw new UnReleasedException();
} }
The problem is that I always get a "cannot find symbol error - method changeAll(double, int), location class Question10e"
Question10e doesn't have this method. Perhaps you intended to call this on an instance of a class which does like.
mm.changeAll(5.5, 3);
changeAll is a method which belongs to the MarkMaker class rather than the current Question10e class where you are attempting to call the method:
mm.changeAll(5.5, 3);
You need to call changeAll() through a MarkMarker object. It doesn't exist in your Question10e class. So, you could do this by:
mm.changeAll(5.5, 3)
Just because changeAll() is public doesn't mean that you can call it from anywhere. It simply means that a MarkMarker object can call it from anywhere.
You need
mm.changeAll(5.5, 3);

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