Right, so why does Java come up with this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from double to int
at rainfall.main(rainfall.java:38)
From this:
public class rainfall {
/**
* #param args
*/
public static void main(String[] args)
{
int[] numgroup;
numgroup = new int [12];
ConsoleReader console = new ConsoleReader();
int highest;
int lowest;
int index;
int tempVal;
int minMonth;
int minIndex;
int maxMonth;
int maxIndex;
System.out.println("Welcome to Rainfall");
// Input (index now 0-based)
for(index = 0; index < 12; index = index + 1)
{
System.out.println("Please enter the rainfall for month " + index + 1);
tempVal = console.readInt();
while (tempVal>100 || tempVal<0)
{
System.out.println("The rating must be within 0...100. Try again");
tempVal = console.readInt();
}
numgroup[index] = tempVal;
}
lowest = numgroup[0];
highest = numgroup[0];
int total = 0.0;
// Loop over data (using 1 loop)
for(index = 0; index < 12; index = index + 1)
{
int curr = numgroup[index];
if (curr < lowest) {
lowest = curr;
minIndex = index;
}
if (curr > highest) {
highest = curr;
maxIndex = index;
}
total += curr;
}
float avg = (float)total / numgroup.length;
System.out.println("The average monthly rainfall was " + avg);
// +1 to go from 0-based index to 1-based month
System.out.println("The lowest monthly rainfall was month " + minIndex + 1);
System.out.println("The highest monthly rainfall was month " + maxIndex + 1);
System.out.println("Thank you for using Rainfall");
}
private static ConsoleReader ConsoleReader() {
return null;
}
}
I guess the culprit is this line:
int total = 0.0;
should be
int total = 0;
instead.
Problem is with this line here:
int total = 0.0;
Need to change total to be of type float
Related
import java.util.Arrays;
public class Swap
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
System.out.print("What is the size of your array? ");
int myArray = console.nextInt();
int[] size = new int[myArray];
int sum = 0;
int max = 0;
int min = 100;
int temp = 0;
for (int i = 0; i < size.length; i++)
{
System.out.print("Array index " + (i) + ": ");
size[i] = console.nextInt();
sum += size[i];
if (size[i] > max) max = size [i];
if (size[i] < min) min = size [i];
}
System.out.println ("\nmaximum value is: " + max);
System.out.println ("\nminimum value is: " + min);
System.out.println (Arrays.toString(size));
temp = size[max];
size[max] = size[min];
size[min] = temp;
System.out.println (Arrays.toString(size));
}
}
I am having trouble swapping the min and max value in the array, I am able to find those values fine, and I even found a way to swap in with the temp variable, but I can't translate that into the array.
You're using max and min as array index to swap your values.That is not correct.Instead you've to keep min and max indexes,and use them to swap in the array. I suggest you to complete your code like that:
import java.util.Arrays;
public class Swap
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
System.out.print("What is the size of your array? ");
int myArray = console.nextInt();
int[] size = new int[myArray];
int sum = 0;
int max = 0;
int min = 100;
int maxIndex=0;
int minIndex=0;
int temp = 0;
for (int i = 0; i < size.length; i++)
{
System.out.print("Array index " + (i) + ": ");
size[i] = console.nextInt();
sum += size[i];
if (size[i] > max){
max = size [i];
maxIndex=i;
}
if (size[i] < min) {
min = size [i];
minIndex=i;
}
}
System.out.println ("\nmaximum value is: " + max);
System.out.println ("\nminimum value is: " + min);
System.out.println (Arrays.toString(size));
temp = size[maxIndex];
size[maxIndex] = size[minIndex];
size[minIndex] = temp;
System.out.println (Arrays.toString(size));
}
}
Only the part for max and min.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int iAtMax = -1;
int iAtMin = -1;
for (int i = 0; i < size.length; i++) {
if (iAtMax == -1 || max < size[i]) {
iAtMax = i;
max = size[i];
}
if (min <= size[i]) {
iAtMin = i;
min = size[i];
}
}
if (iAtMax != -1) {
int temp = size[iAtMax];
size[iAtMax] = size[iAtMin];
size[iAtMin] = temp;
}
You could initialize max and min so that an update in the loop always updates. Then you have to use <= max resp. >= min to update the indices. (See min above) or you can check whether there already is a max and min.
If the array is empty (or size 1) you cannot (resp. need not) swap.
I want to be able to display the output as three lines of text at the end but I'm getting a really weird output. So for example
"The average is z"
"Min Value: x"
"Max Value: y"
But I am getting this:
Please enter the size of the array:
3
Please enter array elements:
10
The average is 3.
Min Value: 0
Please enter array elements:
20
The average is 10.
Max Value: 20
Min Value: 0
Please enter array elements:
30
The average is 20.
Max Value: 20
Max Value: 30
package arrays;
import java.util.Scanner;
public class AssignmentArrays {
public static void main (String[] args) {
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter the size of the array: ");
int size = inputs.nextInt();
int[] Array = new int[size];
for (int i = 0; i < size;) {
System.out.println("Please enter array elements: ");
int value = inputs.nextInt();
if (value >=100 || value <=0) {
System.out.println("Only values greater than 0 and less than 100 can be accepted.");
}
else {
Array[i] = value;
i++;
average(Array);
getMaxValue(Array);
getMinValue(Array);
}
}
}
public static int average(int[] Array)
{
int sum = 0;
int average;
for (int i = 0; i < Array.length; i++)
sum = sum+Array[i];
{
average=sum/Array.length;
System.out.println("The average is " +average +".");
return average;
}
}
public static int getMaxValue(int[] Array) {
int maxValue = Array[0];
for (int i = 1; i < Array.length; i++){
if (Array[i] > maxValue){
maxValue = Array[i];
System.out.println("Max Value: " + maxValue);
}
}
return maxValue;
}
public static int getMinValue(int[] Array) {
int minValue = Array[0];
for (int i = 1; i < Array.length; i++){
if (Array[i] < minValue) {
minValue = Array[i];
System.out.println("Min Value: " + minValue);
}
}
return minValue;
}
}
Thank you for all your help! I have finished my assignment.
example output: https://i.stack.imgur.com/Doy2d.png :)
package arrays;
import java.util.Scanner;
public class Array_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter the size of the array: ");
int size = inputs.nextInt();
int[] Array = new int[size];
for (int i = 0; i < size;) {
System.out.println("Please enter array elements: ");
int value = inputs.nextInt();
if (value >=100 || value <=0) {
System.out.println("Only values greater than 0 and less than 100 can be accepted.");
}
else {
Array[i] = value;
i++;
}
}
Average(Array);
int max;
max = Max(Array);
System.out.println("The maximum is " +max + ".");
int min;
min = Min(Array);
System.out.println("The minimum is " +min + ".");
}
public static void Average(int[] Array) {
int sum = 0;
int average;
for (int i = 0; i < Array.length; i++)
sum = sum+Array[i];
average=sum/Array.length;
System.out.println("The average is " +average +".");}
public static int Max(int[]Array) {
int max= Array[0];
for (int i = 1; i < Array.length; i++) {
if (Array[i] > max) {
max = Array[i];
}
}
return max;
}
public static int Min(int[]Array) {
int min = Array[0];
for (int i = 1; i < Array.length; i++) {
if (Array[i] < min) {
min = Array[i];
}
}
return min;
does anyone knows how to calculate the average in a loop. Every time I calculated the average I received 0 or 1. I know that I need use average = (sum) / (salary_annually); but I can't get it to work. Thanks in advance.
import java.util.Scanner;
public class midterm
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
int average=0;
int count = 0;
int salary_annually = 0;
for(int employee =1; employee <= 2; employee++)
{
System.out.println("Employee: " + employee);
for(int year=1; year <= 2; year++)
{
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually ;
if (min >= salary_annually)
{
min = salary_annually;
}
if (max <=salary_annually)
{
max = salary_annually;
}
average = (sum) / (salary_annually);
}
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
I'm guessing the problem here is that you are using integer division. Since the sum and salary_annually are both integers division works slightly different. There is not remainder because dividing two integers gives an int.
For example 1/2 is not .5 as you might expect but instead it is 0. Any fractional number is dropped when doing integer math. As another example 9/5 is not 1.8 but instead 1.
If you want the average then you can either declare sum or salary_annually as a double and declare the average as a double as well.
Change
average = (sum) / (salary_annually);
To
double average=0;// Declare it as `double` rather than `int`
average = (sum) / 2.0;
average is calculated by: average = sum / count;
you need to increment your count variable, otherwise you will always get and ArithmeticException / by zero
The Average is calculated by average = sum / count where average should be of type double.
You did declare the variable count, but didn't use it.
import java.util.Scanner;
public class Calulate {
/**
* #param args
*/
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
double average = 0;
int count = 2;
int salary_annually = 0;
for (int employee = 1; employee <= 2; employee++) {
System.out.println("Employee: " + employee);
for (int year = 1; year <= count; year++) {
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually;
if (min >= salary_annually) {
min = salary_annually;
}
if (max <= salary_annually) {
max = salary_annually;
}
}
average = sum / count;
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
I just found that when I calculate the average for the second user, I get a different result. For example, if I add this number for the first user 10,10,10,20,20. I get 14.0 which is correct. But when I enter the same number for the second user I get 28.0? any ideas?
import java.util.Scanner;
public class midterm
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
double average=0;
int count = 0;
int salary_annually = 0;
for(int employee =1; employee <= 2; employee++)
{
System.out.println("Employee: " + employee);
for(int year=1; year <= 5; year++)
{
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually ;
average = (sum) / 5.0;
if (min >= salary_annually)
{
min = salary_annually;
}
if (max <=salary_annually)
{
max = salary_annually;
}
}
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
sum = 0; // this before 2nd loop
int max = Integer.MIN_VALUE; // these too.
int min = Integer.MAX_VALUE;
for(int year=1; year <= 5; year++)
{
.
.
.
}
average = (sum) / 5.0; // this after 2nd loop
In your solution you are calculating average 5 times inside the loop! and you only get advantage from the fifth time! must be after the loop. average = (sum) / 5.0; after the loop.
You need to zero sum at the end of the loop. As it is, now it just keeps increasing and increasing as the old value is kept in memory, when coming to the next iteration.
I am creating a program that calculates rainfall for the year etc. I had the first block of code below working with the user input, perfectly. However, I am trying to change the program now, so that the array values are specified (I'm basically trying to eliminate the user input).
Why isn't the second block of code working? I am getting errors at the bottom for r.getTotalRainFall, r.getAverageRainFall etc.
Please note that I had to introduce the array thisYear (this is required).
CODE BLOCK #1:
import java.util.*;
public class Rainfall {
Scanner in = new Scanner(System.in);
int month = 12;
double total = 0;
double average;
double months[];
public Rainfall() {
months = new double[12];
}
public void enterMonthData() {
for (int n = 1; n <= month; n++) {
System.out.print("Enter the rainfall (in inches) for month #" + n + ": ");
months[n - 1] = in.nextDouble();
// Input Validation - Cannot accept a negative number
while (months[n - 1] < 0) {
System.out.print("Rainfall must be at least 0. Please enter a new value.");
months[n - 1] = in.nextDouble();
}
}
}
public double getTotalRainFall() {
total = 0;
for (int i = 0; i < 12; i++) {
total = total + months[i];
}
return total;
}
public double getAverageRainFall() {
average = total / 12;
return average;
}
/**
* Returns the index of the month with the highest rainfall.
*/
public int getHighestMonth() {
int highest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] > months[highest]) {
highest = i;
}
}
return highest;
}
/**
* Returns the index of the month with the lowest rainfall.
*/
public int getLowestMonth() {
int lowest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] < months[lowest]) {
lowest = i;
}
}
return lowest;
}
public static void main(String[]args) {
Rainfall r = new Rainfall();
r.enterMonthData();
System.out.println("The total rainfall for this year is " + r.getTotalRainFall());
System.out.println("The average rainfall for this year is " + r.getAverageRainFall());
int lowest = r.getLowestMonth();
int highest = r.getHighestMonth();
System.out.println("The month with the highest amount of rain is " + (highest+1) + " with " + r.months[highest] + " inches");
System.out.println("The month with the lowest amount of rain is " + (lowest+1) + " with " + r.months[lowest] + " inches");
}
}
CODE BLOCK #2:
package rain;
public class Rain {
int month = 12;
double total = 0;
double average;
double getRainAt[];
public Rain {
getRainAt = new double[12];
}
double getTotalRainFall() {
total = 0;
for (int i = 0; i < 12; i++) {
total = total + getRainAt[i];
}
return total;
}
double getAverageRainFall() {
average = total / 12;
return average;
}
int getHighestMonth() {
int high = 0;
for (int i = 0; i < 12; i++) {
if (getRainAt[i] > getRainAt[high]) {
high = i;
}
}
return high;
}
int getLowestMonth() {
int low = 0;
for (int i = 0; i < 12; i++) {
if (getRainAt[i] < getRainAt[low]) {
low = i;
}
}
return low;
}
public static void main(String[] args) {
// Create an array of rainfall figures.
double[] thisYear = {1.6, 2.1, 1.7, 3.5, 2.6, 3.7,
3.9, 2.6, 2.9, 4.3, 2.4, 3.7 };
int high; // The high month
int low; // The low month
// Create a RainFall object initialized with the figures
// stored in the thisYear array.
Rainfall r = new Rainfall(thisYear);
// Display the statistics.
System.out.println("The total rainfall for this year is " +
r.getTotalRainFall();
System.out.println("The average rainfall for this year is " +
r.getAverageRainFall());
high = r.getHighestMonth();
System.out.println("The month with the highest amount of rain " +
"is " + (high+1) + " with " + r.getRainAt(high) +
" inches.");
low = r.getLowestMonth();
System.out.println("The month with the lowest amount of rain " +
"is " + (low+1) + " with " + r.getRainAt(low) +
" inches.");
}
}
}
I have re-factored the 2 classes
now Rain class only contains the main method whereas all the other logic is contained in the Rainfall class
Rainfall class has a method - getRainAt() to get rain base don the given month
in Rainfall class has a constructor that takes a double array as an argument so it has to be instantiated with this argument provided.
take a look at the classes now and see if this fits your requirement.
import java.util.*;
public class Rainfall {
Scanner in = new Scanner(System.in);
int month = 12;
double total = 0;
double average;
double months[];
public Rainfall(double newmonths[]){
months = newmonths;
}
public void enterMonthData() {
for (int n = 1; n <= month; n++) {
System.out.print("Enter the rainfall (in inches) for month #" + n
+ ": ");
months[n - 1] = in.nextDouble();
// Input Validation - Cannot accept a negative number
while (months[n - 1] < 0) {
System.out
.print("Rainfall must be at least 0. Please enter a new value.");
months[n - 1] = in.nextDouble();
}
}
}
public double getTotalRainFall() {
total = 0;
for (int i = 0; i < 12; i++) {
total = total + months[i];
}
return total;
}
public double getAverageRainFall() {
average = total / 12;
return average;
}
/**
* get rain given the month number
*/
public double getRainAt(int month){
double rainValue = 0;
for (int i = 0; i < months.length; i++) {
if(month == i){
rainValue = months[i];
break;
}
}
return rainValue;
}
/**
* Returns the index of the month with the highest rainfall.
*/
public int getHighestMonth() {
int highest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] > months[highest]) {
highest = i;
}
}
return highest;
}
/**
* Returns the index of the month with the lowest rainfall.
*/
public int getLowestMonth() {
int lowest = 0;
for (int i = 0; i < 12; i++) {
if (months[i] < months[lowest]) {
lowest = i;
}
}
return lowest;
}
}
Rain class only has the main method now
public class Rain {
public static void main(String[] args) {
// Create an array of rainfall figures.
double[] thisYear = { 1.6, 2.1, 1.7, 3.5, 2.6, 3.7, 3.9, 2.6, 2.9, 4.3,
2.4, 3.7 };
int high; // The high month
int low; // The low month
// Create a RainFall object initialized with the figures
// stored in the thisYear array.
Rainfall r = new Rainfall(thisYear);
// Display the statistics.
System.out.println("The total rainfall for this year is "
+ r.getTotalRainFall());
System.out.println("The average rainfall for this year is "
+ r.getAverageRainFall());
high = r.getHighestMonth();
System.out.println("The month with the highest amount of rain " + "is "
+ (high + 1) + " with " + r.getRainAt(high) + " inches.");
low = r.getLowestMonth();
System.out.println("The month with the lowest amount of rain " + "is "
+ (low + 1) + " with " + r.getRainAt(low) + " inches.");
}
}
hope this helps
I'm not sure if this was just a copying error, but in the second block you've called the class Rain, but then you declared r as Rainfall.
Not sure why you are creating a getRainAt class just to initialise it, try using the Rain class constructor to do this.
Replace this:
public class getRainAt {
public getRainAt() {
getRainAt = new double[12];
}
}
With:
public Rain() {
getRainAt = new double[12];
}
and since you are using Rain instead of Rainfall now, in the main method it should be:
Rain r = new Rain();