Illegal start of expression in Java - 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.

Related

How to print, sort and get temps above 90

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.

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

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?

How to add up output of the same method multiple time (Sepearate files)

I'm having a problem adding up the method output and putting it into another method and then printing it. My error is that it keeps printing out the first run of the program. Is there a way to record the multiple runs of the method and put it into a double?
public static void main(String[] args)
{
AnnualUse[] fills = {new AnnualUse (1, 1, 9000, 9420, 16.0, 3.11),
new AnnualUse (2, 30, 9420, 9840, 16.0, 3.08),
new AnnualUse (3, 60, 9840, 10240, 15.23, 3.06)};
String [] oP = new String [3];
int diMin=0;
int diM=0;
double MPin=0;
double MPax=0;
double Primin=0;
double Primax=0;
double roundoff1=0;
double roundoff2=0;
int minDist = Integer.MAX_VALUE;
int maxDist = Integer.MIN_VALUE;
double minMPG = Double.MAX_VALUE;
double maxMPG = Double.MIN_VALUE;
double minPri = Double.MAX_VALUE;
double maxPri = Double.MIN_VALUE;
for (int index=0; index<fills.length; index++)
{
fills[index].calcDistance();
fills[index].calcMPG();
fills[index].calctotalCost();
fills[index].totalDist();
fills[index].totalMPG();
fills[index].totalcost();
}
for (int i = 0; i < fills.length; i++) {
if (fills[i].getDist() < minDist){
minDist = fills[i].getDist();
diMin = minDist ;
}
if (fills[i].getDist() > maxDist) {
maxDist = fills[i].getDist();
diM = maxDist;
}
if (fills[i].getMPG() <minMPG) {
minMPG = fills[i].getMPG();
MPin = minMPG;
}
if (fills[i].getMPG() > maxMPG) {
maxMPG = fills[i].getMPG();
MPax = maxMPG;
roundoff1= Math.round(MPax * 100.0) / 100.0;
}
if (fills[i].getMoolah() < minPri) {
minPri = fills[i].getMoolah();
Primin = minPri;
roundoff2= roundoff2= Math.round(Primin * 100.0) / 100.0;
}
if (fills[i].getMoolah() > maxPri) {
maxPri = fills[i].getMoolah();
Primax = maxPri;
}
}
System.out.println("Fill Up Days Start Miles End Miles Distance Gallons Used MPG Price Cost");
for ( int index=0; index< oP.length; index++)
{
System.out.printf("%3d %8d %10d %10d %9d %13.1f %8.2f %7.2f %8.2f %n" ,
fills[index].getFill(),fills[index].getDay(),
fills[index].getStart(),fills[index].getEnd(),
fills[index].getDist(), fills[index].getUseofG(),
fills[index].getMPG(), fills[index].getCost(),
fills[index].getMoolah());
}
System.out.println();
System.out.println("Minimum:"+" "+diMin+" "+MPin+" "+roundoff2);
System.out.println("Maximum:"+" "+diM+" "+roundoff1+" "+Primax);
System.out.print("Totals:");
for (int index=0; index<1;index++)
System.out.printf( "%20d %20.2f %10.2f", fills[index].getTotal1(),fills[index].getTotal2(),fills[index].total3());
}
first bit of data, from the file I noticed that it's printing out the first run through but I have no idea why it is not adding the values.This is basically how most of the program is. Sorry for not knowing how to explain most of what is going on, I only know the processes actions and don't know to descriptively describe step by step.
class AnnualUse
{
private int counter,day,ender1, starter1, differance,total1 ;
private double amount, cost,MPG,Moolah, minDist,
maxDist,minMPG,maxMPG,minPrice,maxPrice,total2,total3;
AnnualUse (int numberofFills,int days,int starter,int ender,double useofg, double costofg)
{
counter=numberofFills;
day= days;
starter1=starter;
ender1=ender;
amount=useofg;
cost=costofg;
}
public void calcDistance()
{
differance=ender1 - starter1;
}
public int getDist()
{
return differance;
}
public void calcMPG()
{
MPG=differance / amount;
}
public double getMPG()
{
return MPG;
}
public void calctotalCost()
{
Moolah= amount * cost;
}
public double getMoolah()
{
return Moolah;
}
public int getFill()
{
return counter;
}
public int getDay()
{
return day;
}
public int getStart()
{
return starter1;
}
public int getEnd()
{
return ender1;
}
public double getUseofG()
{
return amount;
}
public double getCost()
{
return cost;
}
public void totalDist()
{
total1=+ differance ;
}
public int getTotal1()
{
return total1;
}
public void totalMPG()
{
total2=+MPG;
}
public double getTotal2()
{
return total2;
}
public void totalcost()
{
total3=+Moolah;
}
public double total3()
{
return total3;
}
}
There is too much here for me to give you a specific answer.
It might be worth it for you to clean up the code as much as you can (format it, tidy it, fix as much as you can, etc) and then post it on Code Review for more detailed feedback.
https://codereview.stackexchange.com/
I'm not going to go through all your code for you but you seem to be asking about totals and averages. To calculate those you just need to loop through your values:
double total1 = 0;
double total2 = 0;
for (MyClass mc: theListOfObjects) {
total1 += mc.getFirstTotal();
total2 += mc.getSecondTotal();
}
System.out.println("Totals: "+total1+", "+total2);
System.out.println("Mean: "+(total1/theListOfObjects.size())+", "+(total2/theListOfObjects.size()));
Instead of having separate methods to trying adding the total I just needed to make a variable and then add up all of the inputs.
int total1= fills[0].getDist()+fills[1].getDist()+fills[2].getDist();

Collections.sort compile error - incompatible types

I have been developing an implementation of the neighbourhood algorithm in Java for a physics project I am working on. I'm brand new to Java so I apologize for any idiocy that results.
I have been getting the error
''
incompatible types
found : void
required: java.util.List<VoronoiPoint>
'' on line 22 from the Java compiler in attempting to compile the program shown below. I cannot figure out why the variable ''thelist'' somehow turns into a void when I declared it to be of type List<VoronoiPoint>. If anybody can explain to me what is going on it would be much appreciated!
import java.lang.Double;
import java.util.*;
public class VoronoiTiling
{
public static void main(String args[])
{
Integer n = 10; //Number of dimensions of model parameter space
Integer ns = 20; //Number of points per iteration
Integer nr = 4; //Number of cells to populate
Integer iterations = 5; //Number of iterations
List<VoronoiPoint> thelist = VoronoiList.startlist(ns,n);
//System.out.println(thelist);
//System.out.println(thelist.get(1).misfit);
for (Integer i=0 ; i<thelist.size() ; i++)
{
thelist.get(i).setmisfit();
}
List<VoronoiPoint> orderedlist = Collections.sort(thelist);
Double distance = EuclidianDistance((thelist.get(1)).location,(thelist.get(2)).location);
System.out.println(distance);
}
public static Double EuclidianDistance(Double[] point1, Double[] point2)
{
Double distance=0.0;
for (int i = 0; i < point1.length; i++)
{
distance = distance + Math.pow((point1[i]-point2[i]),2);
}
return Math.sqrt(distance);
}
}
The other classes I used are here:
The VoronoiList class:
import java.util.*;
public class VoronoiList
{
public static List<VoronoiPoint> startlist(Integer ns, Integer n)
{
List<VoronoiPoint> thestartlist = new ArrayList<VoronoiPoint>();
for (int i = 0; i < ns; i++)
{
thestartlist.add(new VoronoiPoint(0.,n));
}
return thestartlist;
}
}
The VoronoiPoint class:
import java.util.Random;
public class VoronoiPoint implements Comparable<VoronoiPoint>
{
Double[] location;
private Random generator = new Random();
Double misfit = -1.;
//***************************************************************
public VoronoiPoint(Double misfit, Integer n)
{
location = new Double[n];
ParameterBoundaries boundaries = new ParameterBoundaries(n);
for(int i = 0; i < n; i++)
{
location[i] = boundaries.getboundaries(2*i)+2*generator.nextDouble();
}
}
//***************************************************************
//public Double[] getlocation()
//{
//return location;
//}
public void setlocationi(Integer i, Double j)
{
location[i] = j;
}
//***************************************************************
public void setmisfit()
{
Integer n = location.length;
Double tempmisfit = 0.0;
for(Integer i = 0; i < n; i++)
{
tempmisfit = tempmisfit + Math.pow((location[i]),2);
}
misfit = Math.sqrt(tempmisfit); // Temporarily just distance to centre
}
//public Double getmisfit()
//{
//return misfit;
//}
public int compareTo(VoronoiPoint b)
{
if (this.misfit<b.misfit) return -1;
else if (this.misfit==b.misfit) return 0;
return 1;
}
}
And the parameter boundaries class:
public class ParameterBoundaries
{
private Double[] boundaries; /*Set to 2n where n is dimensions of parameter space,
* it just makes it easier*/
public ParameterBoundaries(Integer n)
{
boundaries = new Double[2*n];
for(Integer i = 0; i<n; i++)
{
boundaries[2*i] = -1.0;
boundaries[2*i+1] = 1.0;
}
}
public Double getboundaries(Integer i)
{
return boundaries[i];
}
}
Collections.sort(..) sorts the original list. It doesn't return a new list. (Its return type is void)
Your code is wrong. Collections.sort() is an in-place sort function; it modifies the given list argument and returns nothing (void).

Categories

Resources