How to print, sort and get temps above 90 - java

Place code to print elements from arr_param
Place code to sort elements in arr_param in ascending order of fahrenheit temperature
Place code to print out elements from arr_param with temperatures > 90 deg. F
There is a private class to do the conversions from F to C to K.
public class Temperature {
public Temperature(double p_fahren) {
fahrenTemp = p_fahren;
}
public void setFahrenheit(double p_fahren) {
fahrenTemp = p_fahren;
}
public double getFahrenheit() {
return fahrenTemp;
}
public double getCelsius() {
double celsius_temp;
celsius_temp = (5.0 / 9.0) * (fahrenTemp - 32.0);
return celsius_temp;
}
public double getKelvin() {
double kelvin_temp = ((5.0 / 9.0) * (fahrenTemp - 32.0)) + 273.0;
return kelvin_temp;
}
public String toString() {
String ret_val = "";
ret_val = String.format("%.1f F, %.1f C, %.1f K",fahrenTemp, getCelsius(), getKelvin());
return ret_val;
}
}
We are not allowed to use the Arrays Util
public class Asn5_Test_Temperature
{
public static void main(String args[])
{
Temperature arr_temps [] =
{
new Temperature(90), new Temperature(75), new Temperature(65), new Temperature(95),
new Temperature(89), new Temperature(67), new Temperature(77), new Temperature(71),
new Temperature(55), new Temperature(65), new Temperature(64), new Temperature(74),
new Temperature(91), new Temperature(86), new Temperature(78), new Temperature(73),
new Temperature(68), new Temperature(94), new Temperature(91), new Temperature(62)
};
print_array("After population", arr_temps);
sort_array(arr_temps);
print_array("After sort", arr_temps);
print_days_above_90(arr_temps);
}
public static void print_array(String message, Temperature arr_param[])
{
System.out.println("----" + message + "---");
for(Temperature oneElem : arr_param)
System.out.print(oneElem + "\t");
System.out.println();
}
public static void sort_array(Temperature arr_param[])
{
int min;
int temp = 0;
for(int i = 0; i < arr_param.length; i++)
{
min = i;
for(int j = i + 1; j < arr_param.length; j++)
{
if(arr_param[j] < arr_param[min])
{
min = j;
}
}
temp = arr_param[i];
arr_param[i] = arr_param[min];
arr_param[min] = temp;
}
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i] + " ");
}
}
public static void print_days_above_90(Temperature arr_param[])
{
System.out.println("----Days over 90 F---");
for(int i = 0; i > 90; i++)
{
System.out.print(arr_param[i] + " ");
}
}
}
The program is supposed to print out the array, then in ascending order, then only the ones that are above 90 degrees F
I am having issue getting the sort code to work and getting it to sort the temperatures over 90 degrees F. I get three errors in my code: error: bad operand types for binary operator '<' and error: incompatible types: Temperature cannot be converted to int and error: incompatible types: int cannot be converted to Temperature

For this section call the getFahrenheit method to compare:
if(arr_param[j].getFahrenheit() < arr_param[min].getFahrenheit())
{
min = j;
}
For this section.. use the toString method. The purpose of the toString method is to convert your object data to a readable String.
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i].toString() + " ");
}
I hope this helps and let me know if you have any questions.

Related

Mean, Median, and Mode - Newb - Java

We had a lab in Comsci I couldn't figure out. I did a lot of research on this site and others for help but they were over my head. What threw me off were the arrays. Anyway, thanks in advance. I already got my grade, just want to know how to do this :D
PS: I got mean, I just couldn't find the even numbered median and by mode I just gave up.
import java.util.Arrays;
import java.util.Random;
public class TextLab06st
{
public static void main(String args[])
{
System.out.println("\nTextLab06\n");
System.out.print("Enter the quantity of random numbers ===>> ");
int listSize = Expo.enterInt();
System.out.println();
Statistics intList = new Statistics(listSize);
intList.randomize();
intList.computeMean();
intList.computeMedian();
intList.computeMode();
intList.displayStats();
System.out.println();
}
}
class Statistics
{
private int list[]; // the actual array of integers
private int size; // user-entered number of integers in the array
private double mean;
private double median;
private int mode;
public Statistics(int s)
{
size = s;
list = new int[size];
mean = median = mode = 0;
}
public void randomize()
{
Random rand = new Random(12345);
for (int k = 0; k < size; k++)
list[k] = rand.nextInt(31) + 1; // range of 1..31
}
public void computeMean()
{
double total=0;
for (int f = 0; f < size; f++)
{
total = total + list[f];
}
mean = total / size;
}
public void computeMedian()
{
int total2 = 0;
Arrays.sort(list);
if (size / 2 == 1)
{
// total2 =
}
else
{
total2 = size / 2;
median = list[total2];
}
}
public void computeMode()
{
// precondition: The list array has exactly 1 mode.
}
public void displayStats()
{
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Mean: " + mean);
System.out.println("Median: " + median);
System.out.println("Mode: " + mode);
}
}
Here are two implementations for your median() and mode() methods:
public void computeMedian() {
Arrays.sort(list);
if ( (list.size & 1) == 0 ) {
// even: take the average of the two middle elements
median = (list[(size/2)-1] + list[(size/2)]) / 2;
} else {
// odd: take the middle element
median = list[size/2];
}
}
public void computeMode() {
// precondition: The list array has exactly 1 mode.
Map<Integer, Integer> values = new HashMap<Integer, Integer>();
for (int i=0; i < list.size; ++i) {
if (values.get(list[i]) == null) {
values.put(list[i], 1);
} else {
values.put(list[i], values.get(list[i])+1);
}
}
int greatestTotal = 0;
// iterate over the Map and find element with greatest occurrence
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if (pair.getValue() > greatestTotal) {
mode = pair.getKey();
greatestTotal = pair.getValue();
}
it.remove();
}
}

Create a Matrix from an ArrayList

I want to create a class that creates a Matrix via an ArrayList.
So that's what I did:
public class Matrice implements IMatrice {
ArrayList elements;
private int numLignes;
private int numColonnes;
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
public Matrice (int numLignes, int numColonnes, double valeur){
this.numLignes = numLignes;
this.numColonnes = numColonnes;
elements = new ArrayList(numLignes * numColonnes);
for(int i = 0; i < numLignes * numColonnes; i++){
elements.add(i, valeur);
}
}
}
Now that i created this, I wanted to try if it works. Then I created this toString() method:
public String toString() {
final DecimalFormat DEC_FORMAT = new DecimalFormat("0.0");
final int ESP = 8;
int num;
String sTmp;
String s = "[";
for (int i = 0 ; i < (numLignes * numColonnes) ; i++) {
//etendre i sur ESP colonnes
sTmp = "";
num = ESP - DEC_FORMAT.format(elements.get(i)).length();
for (int j = 0 ; j < num ; j++) {
sTmp = sTmp + " ";
}
sTmp = sTmp + DEC_FORMAT.format(elements.get(i));
if (i != 0 && i % numColonnes == 0) {
s = s + " ]\n[" + sTmp;
} else {
s = s + sTmp;
}
}
s = s + " ]";
return s;
}
Then this is my main to try the Matrix:
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
and i don't know why but i only get this :
[ ]
I know that a little thing is wrong but I can't find what. Could you help me?
Okay, i messed up...
The problem was in here :
elements.add(i, valeur);
i did a mistake... i mingled with the set() method.
here is the correction :
elements.add(valeur);

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

Illegal start of expression in Java

I'm new to Java. I'm getting an "illegal start of expression error". I've been searching for answers and cant find out, if I'm using the brackets incorrectly or not but I've tried it without the brackets and with them and cant seem to get past this 1 error. I could use some assistance.
Thank you :)
public class LIANGLAB1
{
public static void main(String[] argv){
gasStation A = new gasStation(3.39, 3.49);
gasStation B = new gasStation(3.19, 3.39);
A.sellregular(10); A.sellregular(10);
B.sellregular(11); B.sellregular(12);
if (A.moreprofit(B)) System.out.println("station A is more profitable");
else System.out.println("station B is more profitable");
gasStation G[] = new gasStation[10];
for(int i=0;i<10;i++) G[i] = new gasStation(3.19,3.39);
{gasStation highest =G[0];}
for (int i=1;i<10;i++)
{if (G[i].moreprofit(highest)) highest = G[i];
{System.out.println("highest total sales is" +highest.sales+ );}
//ERROR IS HERE
}
}
}
class gasStation
{
double regularprice;
double superprice;
double sales;
public gasStation(double r, double s)
{regularprice = r; superprice = s; sales = 0;}
public void sellregular(double gallons)
{sales += regularprice * gallons;}
public void sellsuper(double gallons)
{sales += superprice * gallons;}
public void gouge()
{superprice *= 2; regularprice *=2;}
public boolean moreprofit(gasStation other)
{return sales > other.sales;}
}
Learn the Java coding standards. You aren't following them. It makes your code hard to read.
Good names matter. Put more thought into naming classes, methods, and variables. Your aim should be easy understanding and readability.
This code compiles and runs fine.
public class LIANGLAB1 {
public static void main(String[] argv) {
GasStation gasStationA = new GasStation(3.39, 3.49);
GasStation gastStationB = new GasStation(3.19, 3.39);
gasStationA.sellRegular(10);
gasStationA.sellRegular(10);
gastStationB.sellRegular(11);
gastStationB.sellRegular(12);
if (gasStationA.hasMoreProfit(gastStationB)) System.out.println("station A is more profitable");
else System.out.println("station B is more profitable");
GasStation arrayOfGasStations[] = new GasStation[10];
for (int i = 0; i < 10; i++) {
arrayOfGasStations[i] = new GasStation(3.19, 3.39);
}
GasStation highest = arrayOfGasStations[0];
for (int i = 1; i < 10; i++) {
if (arrayOfGasStations[i].hasMoreProfit(highest)) {
highest = arrayOfGasStations[i];
}
}
System.out.println("highest total sales is" + highest.sales);
}
}
class GasStation {
double regularprice;
double superprice;
double sales;
public GasStation(double r, double s) {
regularprice = r;
superprice = s;
sales = 0;
}
public void sellRegular(double gallons) {
sales += regularprice * gallons;
}
public void sellSuper(double gallons) {
sales += superprice * gallons;
}
public void gouge() {
superprice *= 2;
regularprice *= 2;
}
public boolean hasMoreProfit(GasStation other) {
return sales > other.sales;
}
}
Change this
for(int i=0;i<10;i++) G[i] = new gasStation(3.19,3.39);
{gasStation highest =G[0];}
to this
for(int i=0;i<10;i++){
G[i] = new gasStation(3.19,3.39);
gasStation highest =G[0];
}
And to improve code readability, you should really consider sticking to one statement per line.
EDIT:
for (int i=1;i<10;i++)
{if (G[i].moreprofit(highest)) highest = G[i];
{System.out.println("highest total sales is" +highest.sales+ );}//ERROR IS HERE
}
}
change it to:
for (int i=1;i<10;i++){
if (G[i].moreprofit(highest))
highest = G[i];
}
System.out.println("highest total sales is" +highest.sales);
There is no reason to open curly braces for single println statements.

Having trouble calling another class that reads a txt file into an array that is sorted in the program(band operand error)

so I have a program that takes a txt file and is read in and uses the class of another java file to set up the array. I am trying use selection sort to sort the values placed into the array but it gives me bad operand types for the line: (if array[j] < array[min]). The text file used is:"Country" "Total CO2 2005 (million tonnes)" "Road CO2 (million tonnes)" "Road CO2 per person (tonnes)" "Cars per 1000 people"
10
USA 5951.13 1530.3 5.16 777
UK 2573.4 119.68 1.99 470
Italy 476.08 116.86 2 592
Germany 841.78 150.21 1.82 550
Canada 553.02 123.42 3.82 562
France 414.03 128.13 2.04 477
Russia 1575.44 114.69 0.8 178
Japan 1254.47 224.24 1.76 447
China 5100.6 228.02 0.3 17
India 1147.46 91.06 0.1 8
The program with the class being called carbonDioxide.java:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
The program I am writing calling the two above, CarbonAnalysis.java:
import java.io.*;
import java.util.*;
public class CarbonAnalysis {
public static void main(String[]args){
//CarbonDioxideData c1 = new CarbonDioxideData();
//c1.setCountry("canada");
//System.out.println(c1);
Scanner userInput = new Scanner(System.in);
String fileName ="";
File inputFile = null;
Scanner fileReader = null;
while(fileReader==null){
try{
System.out.println("Enter input file name:");
fileName= userInput.next();
inputFile = new File(fileName);
fileReader = new Scanner(inputFile);
System.out.println("Successfully opening " + fileName);
}catch(IOException err){
System.out.println("Something went wrong");
System.out.println(err);
System.out.println("Please retry");
}
}
String testLine = fileReader.nextLine();
System.out.println(testLine);
int numberOfEntries = fileReader.nextInt();
System.out.println(numberOfEntries);
CarbonDioxideData[] array = new CarbonDioxideData[numberOfEntries];
for(int i =0;i<numberOfEntries;i++){
CarbonDioxideData c1 = new CarbonDioxideData();
String country = fileReader.next();
c1.setCountry(country);
double totalCO2 = fileReader.nextDouble();
c1.setTotalCO2(totalCO2);
double roadCO2 = fileReader.nextDouble();
c1.setRoadCO2(roadCO2);
double perPerson = fileReader.nextDouble();
c1.setCO2PerPerson(perPerson);
int cars = fileReader.nextInt();
c1.setCarsPerPerson(cars);
//System.out.println(c1);
array[i]=c1;
}
printArray(array);
emissionStats(array);
}
public static void printArray(CarbonDioxideData[] a){
for(int i=0; i<a.length;i++){
System.out.println(a[i]);
}
}
public static void emissionStats(CarbonDioxideData[] array){
for (int i = 0; i < array.length - 1; i++) {
// find index of smallest remaining value
int min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j;
}
}
// swap smallest value its proper place, a[i]
swap(array, i, min);
}
}
public static void swap(CarbonDioxideData[] a, int i, int j) {
if (i != j) {
CarbonDioxideData temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
The error I am receiving when compiling:
CarbonAnalysis.java:68: error: bad operand types for binary operator '<'
if array[j] < array[min]
first type: CarbonDioxideData
Second type: CarbondDioxidedata
I am at a loss I have no idea how to get it to work. Any help appreciated
< , > binary operators can be used with primitive types.
public class CarbonDioxideData implements Comparable<CarbonDioxideData> {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
#Override
public int compareTo(CarbonDioxideData that) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == that) return EQUAL;
//Compare function according to your logic
if (this.totalCO2 == that.totalCO2) return EQUAL;
if (this.totalCO2 > that.totalCO2)
return AFTER;
else
return BEFORE;
}
}
Your comparison should be as
if (array[j].compareTo(array[min]) < 0) {
min = j;
}

Categories

Resources