Find High and Low Temp (JAVA) 1st Homework - java

I cant seem to figure it out. I need to ask the user for 3 floats, got it. Having trouble with the output of the high and low part. Any help would be awesome!
package temp;
import java.util.Scanner;
/**
*
* #author Pherman
*/
public class Temp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float temp1;
float temp2;
float temp3;
float highTemp;
float lowTemp;
System.out.print("Please enter your first temperature");
temp1=scan.nextFloat();
System.out.print("Please enter your second temperature");
temp2=scan.nextFloat();
System.out.print("Please enter your third temperature");
temp3=scan.nextFloat();
}
}

Here is a tip for you.
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
float highTemp = Math.max(temp1, Math.max(temp2, temp3); // high
float lowTemp = Math.min(temp1, Math.min(temp2, temp3); // low
float middleTemp = (temp1 + temp2 + temp3) - highTemp - lowTemp; // middle
In this approach, there is no need to use if, switch, array or to sort.

I would use an array, and Arrays.sort(float[]) like so
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float[] temp = new float[3];
for (int i = 0; i < temp.length; ) {
System.out.printf("Please enter your temperature #%d ", i);
if (scan.hasNextFloat()) {
temp[i] = scan.nextFloat();
i++;
} else {
scan.next();
}
}
java.util.Arrays.sort(temp);
System.out.println("Low = " + temp[0]);
System.out.println("High = " + temp[temp.length - 1]);
}

Using Collections to min/max
List<Float> myList = new ArrayList<Float>();
System.out.print("Please enter your first temperature");
myList.add(scan.nextFloat());
System.out.print("Please enter your second temperature");
myList.add(scan.nextFloat());
System.out.print("Please enter your third temperature");
myList.add(scan.nextFloat());
System.out.println(Collections.min(myList));
System.out.println(Collections.max(myList));
You can also use a loop to get your input instead of using System.out.print

Initialize highTemp and lowTemp whenever you can and update their values when necessary.
Use the if keyword.

Related

Trying to figure out how to pass array object data to a separate method

I wanted to write a program that records bar inventory as I'm a bartender. I can't figure out how to pass the liquorCost and liquorCount data to the GetCostTotal() method below the main() method. I'm absolutely sure it's something fairly straightforward that I'm doing incorrectly but I just can't figure it out. Any help is appreciated.
My Liquor class is separate and I can post that if necessary but I don't think it's the class that's giving me the problem, it's retrieving the data input from the array to the separate method.
package inventory;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (liquorCost * liquorCount);
}
return costTotal;
}
}
try this
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(inv);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (inv[i].getLiquorCost() * inv[i].getLiquorCount());
}
return costTotal;
}
Lets understand what went wrong here.Take a look at how you are trying to call the GetCostTotal() method.
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
This is incorrect. The syntax/way you are calling the method is actually used when we what to define a method. Like you did:
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {}
Your call should be like:
double costTotal = GetCostTotal(inv);
Here, we are passing only inv because the data for liquorCost and liquorCount is available inside "each" element of array inv.
Now you can accept this argument in GetCostTotal method. Here as you are iterating using a for loop, you can read the data you needed as inv[i].getLiquorCost() and inv[i].getLiquorCount().
I suggest you can read more on defining a method and calling a method in java.

Java program will not recognize sentinel value

My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)

why does my scanner(system.in) run twice

I am new to java, been self teaching for the last week. I cannot find the reason why the if else statement runs twice. here is the whole code, I know is simple but still trying to learn.
package tickets;
import java.util.Scanner;
public class tickets {
public static void main(String[] args) {
//program designed to ask how many visitors
//are in a party of people and work out
//the total cost of the entry tickets.
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
//adding code that would give a percentage discount for
//4 adults or more
{
if ( adult1.nextInt() >= 4
{
double adult2 =( adult1.nextInt() * percentage);
}else {
double adult2 = (adult * adult1.nextInt());
System.out.println("please enter the amount of consessions");
Scanner consession1 = new Scanner (System.in);
double consession2 = (consession *consession1.nextInt());
System.out.println("please enter the amount of children");
Scanner child1 = new Scanner (System.in);
double child2 = (child * child1.nextInt());
System.out.println( "total"+" " + (adult2 +consession2 + child2) );
System.out.println("hope you enjoy your visit today!");
//woop woop it works!!!!!!!!!!
}
}
}
}
The reason why your program asked for two inputs was because adult1 is the name of your scanner and in your if statement the condition was if the user input is >= 4 then take an Integer input again from the user and multiply that with percentage and store it in adult2, instead this should be done as follows
public static void main(String[] args)
{
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
double adult2 = 0.0 // you dont need to redeclare below
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
// remove this unneccessary bracket {
int num = adult1.nextInt();
if ( num >= 4)
{
adult2 =( num * percentage);
}
else
{
adult2 = (adult * num);
}
System.out.println("Adult2 is " + adult2);
}
Store the int from the scanner and use that value in your ifs and calculations. You're calling nextInt() more than once and each time you get another int.
After you enter the if or else you will wait for more input of the integer type stopping the program.

After making new object,i want to make a function that will ask to input the needed arguments into the object

I'm learning java and just started using objects.
I made a class called Polynom ,and declared a few function that i can do on that given polinom.
Now i want to build a function (or a constructor) that as soon as i declare new Polynom ( Polynom Polynom = new Polynom(); ) , I want to console to ask for input for the polinom.
This is the code snipped i use to "input" the polinom.
System.out.println("Please enter the higest rank of your polynom");
int rank = Scanner.nextInt();
Polynom.setRank( rank );
for(int i = 0 ; i < rank+1 ; i++ ){
System.out.println("Please enter the coefficient of x^" + i);
double coefficient = Scanner.nextDouble();
Polynom.setCoef(coefficient, i);
}
And i am having trouble figuring out how to aplly this as soon as i declare a new polinom.
I think maybe in the contractor call a function that will do it,but i cant figure it out.
I have just started using objects and classes ,so please no complicated staff.
This is the code of my work till now
import java.util.Scanner;
public class Polynom {
static Scanner Scanner = new Scanner(System.in);
double[] coefficients;
public void setRank(int rank){
coefficients = new double[rank+1];
}
public double compute(double vlaue){
double result = 0;
for(int i = 0 ; i < coefficients.length ; i++){
result = result + (coefficients[i] * Math.pow(vlaue, i));
}
return result;
}
public void setCoef(double coefficient,int power){
coefficients[power] = coefficient;
}
public static void main(String[] args){
Polynom Polynom = new Polynom();
System.out.println("Welcome to the polynom vlaue calculaor");
System.out.println();
System.out.println("Please enter the higest rank of your polynom");
int rank = Scanner.nextInt();
Polynom.setRank( rank );
for(int i = 0 ; i < rank+1 ; i++ ){
System.out.println("Please enter the coefficient of x^" + i);
double coefficient = Scanner.nextDouble();
Polynom.setCoef(coefficient, i);
}
System.out.println("Please enter the number to calculate from");
double from = Scanner.nextDouble();
System.out.println("Please enter the number to calculate to");
double to = Scanner.nextDouble();
System.out.println("Please enter the number of each jump");
double jump = Scanner.nextDouble();
for(double i = from ; i < to ; i = i+jump){
System.out.println("for x = "+i+" The value is = "+Polynom.compute(i));
}
}
}
this might work:
import java.util.Scanner;
class Polynomial
{
double[] cofficients;
public Polynomial(Scanner sc)
{
readpoly(sc);
}
public void readpoly(Scanner sc)
{
if(sc==null)
return;
System.out.println("Please enter the higest rank of your polynom");
int rank = sc.nextInt();
cofficients=new double[rank+1];
for(int i = 0 ; i < rank+1 ; i++ )
{
System.out.println("Please enter the coefficient of x^" + i);
cofficients[i]=sc.nextDouble();
}
}
}
then you can simply create the object like this :
Scanner scanner=new Scanner(System.in);
Polynomial p=new Polynomial(scanner);
and the input is taken from console.
that way you can use the same scanner multiple times(to read multiple polynomials) without having to store a whole unrelated object in the Polynomial class.
and I advise you not to name variables by class names(or any other name used before).
It sounds like you just need to pass the information in the constructor? Something like this:
class Polynom {
private int rank;
private double[] coeffs;
public Polynom(double[] coeffs) {
this.rank = coeffs.length - 1;
this.coeffs = coeffs;
}
}
Polynom mypoly = new Polynom(new double[]{1.0, 2.0, 3.0});
However, if you do it this way, you'll need to store the inputs temporarily while the user is entering them, then create the Polynom in a single operation once you have all the coefficients.

In Java how do i find the max and min from a text file?

#rayryeng has been very helpful to me in my most recent attempt at correcting this file. Since my question has now slightly changed, I've decided to create a new question. I have the following code and I am trying to make it find my maximum and minimum based on the list from the txt file. The text file looks like this:
6
88
77
92
82
84
72
The top number should not be calculated in the sum and average which is why I have put a -6 and -1 in my code (as seen below).
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Please enter the name of your data file: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = -6;
int numStudents = -1;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
sum += fileToRead.nextDouble();
} else {
fileToRead.next();
}
}
{
fileToRead.close();
}
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println("Minimum = " + Math.min(sum,sum));
System.out.println("Maximum = " + Math.max(sum,sum));
System.out.println("Average score: " + sum/numStudents);
System.out.println();
System.out.println("Number of scores by letter grade: ");
System.out.println();
System.out.println("There are " + numStudents + " scores");
}
}
I know that the sum,sum is wrong, but I needed something to fill in there so that I would remember to get it filled.
I've already tried searching through these posts as well as many others for help:
How to find min and max, Finding min/max
but I continue to get errors. Today is my very first day doing Java, so I have little to no clue where to go from here :-/
Final changes to code
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Please enter the name of your data file: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = -6;
int numStudents = -1;
double maxVal = 0, minVal = 0; //NEW
boolean bFirstTime = true; //NEW
double currVal; //NEW
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
currVal = fileToRead.nextDouble(); //NEW
//NEW
if (bFirstTime) {
maxVal = currVal;
minVal = currVal;
bFirstTime = false;
} else {
maxVal = Math.max(maxVal,currVal);
minVal = Math.min(minVal, currVal);
}
sum += currVal;
} else {
fileToRead.next();
}
}
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println("Minimum = " + minVal);
System.out.println("Maximum = " + maxVal);
System.out.println("Average score: " + sum/numStudents);
System.out.println();
System.out.println("Number of scores by letter grade: ");
System.out.println();
System.out.println("There are " + numStudents + " scores");
}
}
Math.min(x,y) returns the minimum of x and y. Math.max(x,y) returns the maximum of x and y. You should create two double variables called maxVal and minVal. In your loop, as you are getting each double value, use Math.min() and Math.max() to compare the current double value to maxVal and minVal. For example:
// While there is still stuff in the file...
double sum = -6;
int numStudents = -1;
double maxVal, minVal; //NEW
boolean bFirstTime = true; //NEW
double currVal; //NEW
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
currVal = fileToRead.nextDouble(); //NEW
//NEW
if (bFirstTime) {
maxVal = currVal;
minVal = currVal;
bFirstTime = false;
} else {
maxVal = Math.max(maxVal,currVal);
minVal = Math.min(minVal, currVal)
}
sum += currVal;
} else {
fileToRead.next();
}
}
You could try writing to an array list and using the collections class.
ArrayList<type> list = new ArrayList<type>"();
while (fileToRead.hasNext()) {
list.add(fileToRead.nextDouble());
}
int max = Collections.max(list);
int min = Collections.min(list);
How to find min and max:
Have two variables. Call them min and max.
Set min with the biggest number you can find.
If min and max are Integer, then you already have MAX_VALUE and MIN_VALUE sets.
Set max with the smallest number around.
Then for every number you find, do:
max = Math.max(max, number);
min = Math.min(min, number);

Categories