i do not understand a line of programming code - java

This is my code for the class where I declared all the methods that will be called in the main class. I am having difficulties writing the getAverageValue code since I do not know how.
import java.util.Random;
public class MyCalculator
{
private int min;
private int max;
private int sum;
private int average;
public int[] generatedRandomData()
{
int inputData[] = new int[10];
Random generatedRandom = new Random();
for(int i=0; i<10; i++)
{
inputData[i] = generatedRandom.nextInt(100);
}
return inputData;
}
public int getMaxValue (int[] inputData)
{
int max;
max = inputData[0];
for (int i = 1; i <inputData.length; i++)
{
if(max < inputData[i])
max = inputData[i];
}
return max;
}
public int getMinValue (int[] inputData)
{
int min;
min =inputData[0];
for (int i = 1; i <inputData.length; i++)
{
if(min > inputData[i])
min = inputData[i];
}
return min;
}
public int getSumValue (int[] inputData)
{
int sum;
sum =inputData[0];
for (int i = 1; i <inputData.length; i++)
{
sum+=inputData[i];
}
return sum;
}
public float getAverageValue (int[] inputData, int getSumValue)
{
int average= 0;
for (int i = 1; i <inputData.length; i++)
{
average = getSumValue/inputData.length;
}
return average;
}
}
While this is my code for my main class:
public class MyApp
{
public static void main (String[] args)
{
MyCalculator calculator = new MyCalculator();
int [] inputData = calculator.generatedRandomData();
System.out.println("The generated values are: ");
for (int value: inputData)
System.out.print(value + ", ");
System.out.println();
System.out.println();
System.out.println("Max Value: " + calculator.getMaxValue(inputData));
System.out.println("Min Value: " + calculator.getMinValue(inputData));
System.out.println("Sum Value: " + calculator.getSumValue(inputData));
System.out.println("Avg Value: " + calculator.getAverageValue(calculator.getSumValue(inputData), inputData.length));
}
}
When compiling this code, I get the following error:
incompatible types: int cannot be converted to int[]
System.out.println("Avg Value: " + calculator.getAverageValue(calculator.getSumValue(inputData), inputData.length));
^
Note: Some messages have been simplified;

This is your original statement:
System.out.println("Avg Value: " + calculator.getAverageValue(calculator.getSumValue(inputData), inputData.length));
If we split that apart to only do one thing at a time, we get:
sum = calculator.getSumValue(inputData);
len = inputData.length;
average = calculator.getAverageValue(sum, len);
text = "Avg Value: " + average;
System.out.println(text);
Both accomplish the same thing, but split apart, it is just so very verbose.

The signature of getAverageValue is
public float getAverageValue (int[] inputData, int getSumValue)
i.e. the method expects the input data as int[] array and then the value of the sum.
You are calling it as
calculator.getAverageValue(calculator.getSumValue(inputData), inputData.length)
i.e. with the value of the sum (which is an int - the "incompatible type" your compiler is complaining about) and the number of inputs.
Correct would be:
calculator.getAverageValue(inputData, calculator.getSumValue(inputData))
As a side note: Your implementation probably does not what you think it does. See Integer division: How do you produce a double? and think about whether you really need a loop there.

The correct code:
System.out.println("Avg Value: " +
calculator.getAverageValue(inputData, calculator.getSumValue(inputData)));

Related

When compiling program I get the error 'void' type not allowed here

I'm trying to create a program that asks for 10 integers and puts those numbers into an array of negative, positive, and odd arrays. In the end, I want the program to print out 3 rows of numbers that separate the users 10 numbers into "odd", "even", and negative". When I run this I get "error: 'void' type not allowed here"
import java.util.Scanner;
public class ArrayPractice{
private static void showArray(int[] nums)
{
for (int i=0; i<nums.length;i++)
{
if(nums[i]!=0)
{
System.out.println(nums[i] + " ");
}
}
}
public static void main(String[] args){
int evenArray[] = new int[10];
int evenCount = 0;
int oddArray[] = new int[10];
int oddCount = 0;
int negArray[] = new int[10];
int negCount = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i<10; i++)
{
System.out.println("Number? " + (i + 1));
int answer = input.nextInt();
if(answer<0)
{
negArray[negCount++] = answer;
}
else
{
if (answer % 2 == 0)
{
evenArray[evenCount++] = answer;
}
else
{
oddArray[oddCount++] = answer;
}
}
}
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
}
}
showArray is void, it does not return anything. And, on inspection, it prints in the method itself. So this
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
should just be
showArray(evenArray);
showArray(oddArray);
showArray(negArray);

How to format arrays in a different method?

How would I format my array as this? I've tried many different methods but I can't seem to get it to work.
I want it to return something like this
"Avg of 1 2 3 4 5 is 3.00"
public class AverageNumber {
private static int[] n = new int[5];
private static double total = 0;
public static void main(String[] a) {
AverageNumber object = new AverageNumber();
object.Dialogue();
}
private void Dialogue() {
int count = 1;
System.out.println("Skriv inn 5 tall" + count++);
for(int i=0; i<n.length; i++){
n[i] = Konsoll.readInt("Tall");
total = total + n[i];
}
double avg = total / n.length;
System.out.println("Avg of " + formatArray() + " is " + avg);
}
private static double formatArray() {
//Return all numbers
}
}
formatArray method should return String, like this :
private static String formatArray() {
String s = "";
for(int i = 0 ; i < n.length ; i++)
s+= String.valueOf(n[i])+" ";
return s;
}

Basic arraylist using Fibonacci sequence

I want this program to take an array list "max" that the size is created by the user. Then the program uses the Fibonacci sequence to store all the Fibonacci numbers in the arraylist that are less than the arraylist "max" which is created by the user input.
import java.util.*;
import javax.swing.*;
public class FibonacciArrayList {
public static ArrayList<Integer> Fibonacci (Integer Max){
ArrayList<Integer> A = new ArrayList<Integer>();
int n0;
int n1;
int n2;
for(int i= 0; i = max; i++){
n2= n1 + n0;
system.out.println(n2);
n0=n1;
n1=n2;
return A;
}
public static void main (String[] arg){
Integer max;
String Title = "Fibonacci ArryList";
String data = JOptionPane.showInputDialog(null, "Enter the upper bound", Title, 1);
max = new Integer(data);
ArrayList<Integer> A = Fibonacci(max);
System.out.println("There are " + A.size()+ " Fibonacci numbers less than "+max);
}
}
Modified and simplified the logic to the Fibonacci function. Comments have been added to help you understand the changes.
public static ArrayList<Integer> Fibonacci (Integer max) { //Instead of 'Max' use 'max'
ArrayList<Integer> A = new ArrayList<Integer>();
//Initialize value of n0, n1 and n2
int n0=0;
int n1=1;
int n2=1;
//Handling the base conditions
if(max == 0) return A;
if(max == 1) {
A.add(n0);
return A;
}
//Add first 2 elements in the array
A.add(n0);
A.add(n1);
//A 'while' loop will be more suitable to what you want to achieve
while(n2 < max) {
A.add(n2); //Instead of printing the values, add them into ArrayList A
n0=n1;
n1=n2;
n2 = n1 + n0;
} //Add a closing bracket for the 'for' loop
return A;
}
Try this code.
import java.util.*;
import javax.swing.*;
public class FibonacciArrayList {
public static ArrayList<Integer> Fibonacci (int Max){
ArrayList<Integer> A = new ArrayList<Integer>();
int n0=0;
int n1=1;
int n2;
if(Max==0){
}
else if(Max==1)
{
System.out.println(n0);
A.add(n0);
}
else if(Max==2)
{
System.out.println(n0);
System.out.println(n1);
A.add(n0);
A.add(n1);
}
else{
System.out.println(n0);
System.out.println(n1);
A.add(n0);
A.add(n1);
for(int i= 2; i <=Max; i++){
n2= n1 + n0;
A.add(n2);
System.out.println(n2);
n0=n1;
n1=n2;
}
}
return A;
}
public static void main (String[] arg){
int max;
String Title = "Fibonacci ArryList";
String data = JOptionPane.showInputDialog(null, "Enter the upper bound", Title, 1);
max = Integer.parseInt(data);
ArrayList<Integer> A = Fibonacci(max);
System.out.println("There are " + A.size()+ " Fibonacci numbers less than "+max);
}
}

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

Sorting arrays from a file and printing results

I have to read a file of data and store it into an array of integers, sort through the array and then report the highest total and the lowest total but for some reason when i run my code nothing appears, and it says that it is error free. this is the code that i have so far...
import java.io.*;
import java.util.Scanner;
public class CarbonAnalysis {
public static void main (String [] Args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
File f = new File("carbon_data.txt");
Scanner welcome = new Scanner(f);
File outputFile = new File("carbon_report.txt");
PrintStream output = new PrintStream(outputFile);
String firstLine = welcome.nextLine();
int secondLine = welcome.nextInt();
CarbonDioxideData[] Country = new CarbonDioxideData[secondLine];
for(int i = 0; i < secondLine; i++) {
Country[i] = new CarbonDioxideData();
Country[i].setCountry(welcome.next());
Country[i].setTotalCO2(welcome.nextDouble());
Country[i].setRoadCO2(welcome.nextDouble());
Country[i].setCO2PerPerson(welcome.nextDouble());
Country[i].setCarsPerPerson(welcome.nextInt());
}
int count = 0;
int count2 = 0;
CarbonDioxideData[] totalEmissions = new CarbonDioxideData[count];
CarbonDioxideData[] perPersonRoadEmissions = new CarbonDioxideData[count2];
reportDescription(output);
sortTotalEmissions(totalEmissions);
sortPerPersonRoadEmissions(perPersonRoadEmissions);
}
//prints the output of data analyzed
public static void reportDescription(PrintStream output) {
output.println("Country with the lowest total emissions: ");
output.println("Country with the highest total emissions: " );
output.println("Canada is ranked for lowest total emissions.");
output.println();
output.println("Country with the lower per-person road emissions: ");
output.println("Country with the highest per-person road emissions: ");
output.println("Canada is ranked for the lowest per-road emissions.");
}
//sorts the total Emissions from highest to lowest
public static void sortTotalEmissions(CarbonDioxideData[] totalEmissions){
for(int i = 0; i < totalEmissions.length; i++) {
double max = totalEmissions[i].getTotalCO2();
int maxPos = i;
for(int j = i; j < totalEmissions.length; j++) {
if(max < totalEmissions[j].getTotalCO2() ) {
max = totalEmissions[j].getTotalCO2();
maxPos = j;
}
}
CarbonDioxideData temp = totalEmissions[maxPos];
totalEmissions[maxPos] = totalEmissions[i];
totalEmissions[i] = temp;
}
}
//sorts the per person road Emissions from highest to lowest
public static void sortPerPersonRoadEmissions(CarbonDioxideData[] perPersonRoadEmissions){
for(int i = 0; i < perPersonRoadEmissions.length; i++) {
int max = perPersonRoadEmissions[i].getCarsPerPerson();
int maxPos = i;
for(int j = i; j < perPersonRoadEmissions.length; j++) {
if(max < perPersonRoadEmissions[j].getCarsPerPerson() ) {
max = perPersonRoadEmissions[j].getCarsPerPerson();
maxPos = j;
}
}
CarbonDioxideData temp = perPersonRoadEmissions[maxPos];
perPersonRoadEmissions[maxPos] = perPersonRoadEmissions[i];
perPersonRoadEmissions[i] = temp;
}
}
}
The code that was given to me to help:
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;
}
}
Your program always ouputs a constant String in the file since there is no variable in reportDescription.
Secondly to properly sort you array, CarbonDioxideData should implement Comparable. Then you can call
Arrays.sort like this :
Arrays.sort(perPersonRoadEmissions)
and then retrieve the highest/value :
perPersonRoadEmissions[0] / perPersonRoadEmissions[perPersonRoadEmissions.length-1]
To display the information you have to call output after sorting and change the signature to accept variable for highest and lowest value.
Arrays.sort(totalEmissions);
Arrays.sort(perPersonRoadEmissions)
reportDescription(output,totalEmissions[0],totalEmissions[totalEmissions.length-1],perPersonRoadEmissions[0],perPersonRoadEmissions[perPersonRoadEmissions.length-1]);
As an alternative you can also simply pass the arrays as parameters and retrieve min max in the body of reportDescription :
reportDescription(output,totalEmissions,perPersonRoadEmissions);
How to change the content of reportDescription and implementing compareTo is left to the OP.

Categories

Resources