Checking temperature conditions - java

How could I set appropriate temperature within these three conditions at least at 98°C, 99°C, 1°C & 2°C etc?
package boiling.freezing;
import java.util.Scanner;
public class BoilingFreezing {
public static void main(String[] args) {
System.out.println("Give the temperature : ");
Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();
if (temp >= 100){
System.out.println("The water is boiling!");
}
else if (temp <= 0){
System.out.println("The water is freezing!");
}
else{
System.out.println("The water is at normal_state!");
}
}
}

I'm going to offer you a pattern, not a simple if-elseif-else block.
You might want to have an interface Temperature
interface Temperature {
/** Returns true if the temperature matches the criteria. */
boolean within(final int temperature);
/** Returns an appropriate, descriptive, message. */
String message();
}
You can then implement this interface to meet your multiple criteria
class BoilingTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature > 99;
}
public String message() {
return "Water boiling";
}
}
class FreezingTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature < 1; // Should be 3 degree! But anyway.
}
public String message() {
return "Water freezing";
}
}
You can use this pattern to write custom temperature handlers
class YourCustomTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature > 6 && temperature < 40;
}
public String message() {
return "Your custom message";
}
}
You need to maintain a list of those concrete implementations and loop them to check which matches.
final List<Temperature> temperatures = new ArrayList<>(6);
temperatures.add(new BoilingTemperature());
temperatures.add(new FreezingTemperature());
temperatures.add(new YourCustomTemperature());
...
And then
public static void main(String[] args) {
System.out.println("Give the temperature : ");
final Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();
for (final Temperature t : temperatures) {
if (t.within(temp)) {
System.out.println(t.message());
}
}
}

Based on LppEdd's answer if you are using Java 8+ you can make use of java predicate
java.util.function.Predicate was introduced that behaves as an assignment target in lambda expressions and
functional interfaces. The functional method of Predicate is
test(Object) .

Related

User input and object creation inside method

I have a Java Class named Real
public class Real {
private long wholeNumPart;
private long decimalPart;
public Real(){
wholeNumPart =0;
decimalPart=0;
}
public Real(long wholeNumPart, long decimalPart) {
this.wholeNumPart =wholeNumPart;
this.decimalPart = decimalPart;
}
public long getWholeNumPart() {
return wholeNumPart;
}
public long getDecimalPart() {
return decimalPart;
}}
I have another class name RealApplication where I need to create two methods
createRealObject() that allows a user to input a real number and creates an object representing
that number.
2.createRealNumber() which accepts an object of type Real and returns a real number represented
by that object.
I am having difficulty creating these two methods
Here is what I've done so far
import java.util.Scanner;
public class RealApplication {
public void createRealNumber() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
long n = sc.nextLong();
//Creates Real object ( is this correct????)
Real in = new Real();
}
public long createRealNumber(Real num) {
long realNum=0;
//I do not know what to write here :(
return realNum;
}
}
Your Real class looks good with some changes in the RealApplication class we can achieve what you want:
import java.util.Scanner;
public class RealApplication {
public static Real createRealObject() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
String n = sc.nextLine();
String[] pieces = n.split("[.,]+"); //special pattern to recognize comma and dot
long wholeNumPart;
long decimalPart;
try {
wholeNumPart = Long.valueOf(pieces[0]);
decimalPart = Long.valueOf(pieces[1]);
}
catch (NumberFormatException e) {
System.out.println("You should enter a number!");
return null;
}
Real in = new Real(wholeNumPart, decimalPart);
sc.close();
return in;
}
The important point is that I declared the both methods as static in this way you can use the methods without creating an instance of RealApplication class.
You should use "double" primitive type to store fractional numbers not "long". Now the method that returns the number equivalent of that object:
public static double createRealNumber(Real num) {
double realNum;
long wholeNumPart = num.getWholeNumPart();
long decimalPart = num.getDecimalPart();
int numOfDigits = (int)(Math.log10(decimalPart)+1);
realNum = wholeNumPart + (decimalPart / Math.pow(10,numOfDigits));
return realNum;
}
And if we write a main method:
public class Main {
public static void main(String[] args) {
Real realObj = new Real(10,2323232);
double number = RealApplication.createRealNumber(realObj);
System.out.println("Equivalent number for the object: " + number);
Real newObj = RealApplication.createRealObject();
if (newObj != null) {
System.out.println("New object's number part: " + newObj.getWholeNumPart());
System.out.println("New object's decimal part: " + newObj.getDecimalPart());
}
else{
return;
}
}
}
Because of the regex pattern we used, the inputs separated with "." and "," are allowed like 10.23 10,23 .

Object won't construct due to int error even tho they're included in the class [duplicate]

This question already has answers here:
Java error: constructor in class cannot be applied to given types
(3 answers)
Closed 4 years ago.
I have a three classes, one to demo and another to extend the first. Everything compiles when in the demo is gives me this error:
EssayDemo.java:11: error: constructor Essay in class Essay cannot be applied to given types;
Essay termPaper = new Essay();
^
required: int,int,int,int
The four ints are Grammar, Spelling, Length, and Content. I set them up but they don't construct an object properly.
This might have been easier if it weren't for the fact that I have to use two classes that I didn't write. Here are the two specific pieces of code. Here's the essayDemo.java:
/**
This program demonstrates a solution to
the Essay Class programming challenge.
*/
public class EssayDemo
{
public static void main(String[] args)
{
// Create an Essay object.
Essay termPaper = new Essay();
// Assign scores to the object.
// Grammer = 25 points, Spelling = 18 points,
// Length = 20 points, and Content = 25 points.
termPaper.setScore(25.0, 18.0, 20.0, 25.0);
// Display the score details.
System.out.println("Term paper:");
System.out.println("Grammar points: " + termPaper.getGrammar());
System.out.println("Spelling points: " + termPaper.getSpelling());
System.out.println("Length points: " + termPaper.getCorrectLength());
System.out.println("Content points: " + termPaper.getContent());
System.out.println("Total points: " + termPaper.getScore());
System.out.println("Grade: " + termPaper.getGrade());
}
}
And here's the gradedActivity.java:
/**
The GradedActivity class stores data about a graded
activity for the Essay Class programming challenge.
*/
public class GradedActivity
{
private double score; // Numeric score
/**
The setScore method sets the score field.
#param s The value to store in score.
*/
public void setScore(double s)
{
score = s;
}
/**
The getScore method returns the score.
#return The value stored in the score field.
*/
public double getScore()
{
return score;
}
/**
The getGrade method returns a letter grade
determined from the score field.
#return The letter grade.
*/
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}
Here's the code I've written to extend it:
public class Essay extends GradedActivity
{
private final int grammarPossible = 30;
private final int spellingPossible = 20;
private final int lengthPossible = 20;
private final int contentPossible = 30;
private final int overallPossible = 100;
private int grammarGrade;
private int spellingGrade;
private int lengthGrade;
private int contentGrade;
private int overallGrade;
public Essay(int grammar, int spelling, int length, int content){
setGrammarGrade(grammar);
setSpellingGrade(spelling);
setLengthGrade(length);
setContentGrade(content);
setOverallGrade();
setScore(getOverallGrade());
}
public int getGrammarGrade(){
return grammarGrade;
}
public void setGrammarGrade(int grammarGrade){
this.grammarGrade = grammarGrade;
}
public int getSpellingGrade(){
return spellingGrade;
}
public void setSpellingGrade(int spellingGrade){
this.spellingGrade = spellingGrade;
}
public int getLengthGrade(){
return lengthGrade;
}
public void setLengthGrade(int lengthGrade){
this.lengthGrade = lengthGrade;
}
public int getContentGrade(){
return contentGrade;
}
public void setContentGrade(int contentGrade){
this.contentGrade = contentGrade;
}
public int getOverallGrade(){
return overallGrade;
}
public void setOverallGrade(){
int grades = grammarGrade + spellingGrade + lengthGrade + contentGrade;
this.overallGrade = grades;
}
public int getGrammarPossible(){
return grammarPossible;
}
public int getSpellingPossible(){
return spellingPossible;
}
public int getLengthPossible(){
return lengthPossible;
}
public int getContentPossible(){
return contentPossible;
}
public int getOverallPossible(){
return overallPossible;
}
}
I have four ints in the essay method but they aren't excepted in the constructor. Everything compiles.
required: int,int,int,int
The error is telling you that your constructor requires arguments (public Essay(int grammar, int spelling, int length, int content)). Right now you are trying to construct an Essay , but are not passing any arguments to it.
You need to provide those arguments, or provide a no args constructor:
public Essay(){}
Or if you wanted to initialize them all to zero and initialize the variables later:
Essay termPaper = new Essay(0,0,0,0);

Why is return not needed in this case?

i'm new to programming and i'd like to ask that why is it that in my code i do not need to use a return function in the constructor and method?
Also why is it that after using the yearPasses function age is increased by 3 and not 1?
Apology for the lengthy code
public class Person
{
private int age;
public Person(int initialAge)
{
// Add some more code to run some checks on initialAge
if (initialAge<0)
{
System.out.println("Age is not valid, setting age to 0.");
initialAge = 0;
age = initialAge;
}
else
{
age = initialAge;
}
}
public void amIOld()
{
if (age<13)
{
System.out.println("You are young.");
}
else if (age>=13 && age<18)
{
System.out.println("You are a teenager.");
}
else
{
System.out.println("You are old.");
}
}
public void yearPasses()
{
age = age + 1;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++)
{
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++)
{
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
You don't need a return in the constructor because a constructor's job is to create an object. The new operator returns that object for you, so it doesn't need to be in the constructor itself.
Your other methods are declared with a return type of void, which means they don't return anything, so you don't need return statements in those either.
You're calling yearPasses in a loop that executes three times.
Constructors create the object, the new keyword is where the object is returned.
All your other methods are labelled as void, meaning they do not return anything.
You could add a return to your yearPasses method, that will return the new age if you want, however it depends on what you need it to do. (This is just an example of using the return)

Sorting ArrayList by specific value

Is there a way I can sort my teams arraylist by the number of points that team has, so whichever team has the highest points is first, and so on, please dont use comperator, because I don't understand how to use that, here is my code:
import java.util.*;
import java.io.*;
class team {
public int teamNum;
public int points = 0;
public team(int x) {
this.teamNum = x;
}
public team(int x,int y) {
this.teamNum = x;
this.points = y;
}
}
public class Problem9 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("Test9.txt"));
ArrayList<team> teams = new ArrayList<>();
int counter=0;
while(in.hasNextLine()) {
boolean found = false;
String[] split = in.nextLine().split(" ");
int n1 = Integer.parseInt(split[0]);
int n2 = Integer.parseInt(split[1]);
if (!(n1 == 0 && n2 == 0)) {
if (counter<1) teams.add(new team(n1));
for (int i=0; i<teams.size(); i++) {
if (teams.get(i).teamNum == n1) {
teams.get(i).points+=n2;
found = true;
}
}
if (!found) {
teams.add(new team(n1, n2));
}
}
counter++;
}
for (int k=0; k<teams.size(); k++)
System.out.println(teams.get(k).teamNum + " " + teams.get(k).points);
}
}
There are 2 ways to do sorting on a custom data type :
use Comparator
use Comparable
Using Comparable
class team implements Comparable<team> {
public int teamNum;
public int points = 0;
public team(int x) {
this.teamNum = x;
}
public team(int x,int y) {
this.teamNum = x;
this.points = y;
}
public int compareTo(team t1){
return t1.points - this.points;
}
}
Now use Collections.sort() on the arraylist, which would sort it for you.
Agreed with #sschale, you can't run away from certain methods or libraries just because you do not know how to use it and hence do not want to use it. To help you out I will give you a much simplified form of comparator implementation here:
//Place this between class team and public class Problem9
static class rankcomparator implements Comparator<Team> {
#Override //need to override
public int compare(Team lhs, Team rhs) {
return -compare(lhs.points, rhs.points); //if descending order
//return compare(lhs.points, rhs.points); //if ascending order
}
}
public static void main(String[] args) throws IOException {
//Add this code inside public class Problem9 ...
Collections.sort(teams, new rankcomparator());
}
You really need to learn how a Comparator and the Comparable interface work. I recommend this tutorial on Comparator usage and this tutorial on using natural ordering through the Comparable interface.
Concerning the issue at hand: just add a getScore method to your Team class:
int getScore(){ return this.score;}
Then call:
teams.sort(Comparator.comparing(Team::getScore));
You can reverse the order using:
teams.sort(Comparator.comparing(Team::getScore).reversed());
One last thing: it is convention that class names begin with a capital letter. You should refactor your team class to be Team.
You can also just do that without a comparator because you just have Integers to compare to each other:
teams.sort((Team t1, Team t2) -> (Integer.compare(t1.getScore(), t2.getScore())));
Collections.reverse(teams);

Java Calculator with classes

OK so i have been working on a calculator with classes(To play with classes but a function) and when ever I run it all i get back is zero no matter what I type in or say to use for the operator. Here is my code:
Main class:
import java.util.Scanner;
//numof = number of numbers in array
// numarrays = the array for user input
// finial = finial number aka the answer
public class Calculator {
public static double finial;
/**
* #return the finial
*/
public static double getFinial() {
return finial;
}
/**
* #param numof the finial to set
*/
public static void setFinial(double finial) {
finial = numof;
}
public static int numof;
/**
* #return the numof
*/
public static int getNumof() {
return numof;
}
/**
* #param numof the numof to set
*/
public static void setNumof(int numof) {
numof = numof;
}
public static double[] numarrays;
/**
* #return the numarrays
*/
public static double[] getNumarrays() {
return numarrays;
}
/**
* #param numarrays the numarrays to set
*/
public static void setNumarrays(double[] numarrays) {
numarrays = numarrays;
}
#SuppressWarnings("resource")
public static void main (String[] args) {
System.out.println("Hello and welcome to my calculator, in this calculator you can add, subtract or multiply");
System.out.println("For the next step I need to know how many numbers you would like to input? ");
int numof;
Scanner numofnums= new Scanner(System.in);
numof = numofnums.nextInt();
Calculator.setNumof(numof);
System.out.println("So next you are going to input the numbers");
double[] numarrays = new double[numof];
for (int k=0; k < numof; k++){
System.out.println("Please enter number");
Scanner input = new Scanner(System.in);
numarrays[k] = input.nextDouble();
}
Calculator.setNumarrays(numarrays);
System.out.println("Please enter what you would like to do with these numbers add,subtract,avg,multiply");
Scanner OP = new Scanner(System.in);
String OPerator= OP.next();
if (OPerator.equals ("add")){
Add.adding();
}
else if (OPerator.equals ("subtract")){
subtract.subtracting();
}
else if (OPerator.equals ("multiply")){
multiply.multiplying();
}
else if (OPerator.equals ("avg")){
avg.avging();
}
System.out.println("The answer is " + Calculator.getFinial());
}
}
here is the add class:
public class Add extends Calculator {
public static void adding() {
double finial = 0;
for (int h = 0; h < Calculator.getNumof(); h++){
finial = finial + Calculator.getNumarrays()[h];
}
Calculator.setFinial(finial);
}
}
I do have three more classes but it is just operator classes let me know if you need them
Just a quick look shows some significant basic issues. For example, in a basic setter, like:
public static void setFinial(double finial) {
finial = numof;
}
from your code, what you most likely intended was
public static void setFinial(double paramFinial) {
finial = paramFinial;
}
If your static variable and your parameter have the same name, you can't access both. The compiler will think you're talking about the parameter. Also, be careful that your setter is using the parameter paramFinial instead of the probably unintentional reference to numof.
It would be a lot easier to read the rest of your code if you would comment what finial, numof, and your other variables represent.

Categories

Resources