I'm trying to avoid using two files and instead, just make it into one file all together.
So i made a single class in a .java file, this is how it looks:
import javax.swing.JOptionPane;
public class Raindrop {
double [] rainfallStats;
public double getTotalRainfall() {
double totalRainfall;
for ( int index = 0; index < rainfallStats.length; index++) {
totalRainfall = totalRainfall + rainfallStats[ index ];
}
return totalRainfall;
}
public double getAverageRainfall() {
return getTotalRainfall() / rainfallStats.length;
}
public double getMostRainMonth () {
double mostRain = rainfallStats [ 0 ];
int mostRainMonth;
for( int index = 0; index < rainfallStats.length; index++ ) {
if ( rainfallStats[ index ] > mostRain ) {
mostRain = rainfallStats [ index ];
mostRainMonth = index + 1;
}
}
return mostRainMonth;
}
public double getLeastRainMonth () {
double leastRain = rainfallStats [ 0 ];
int leastRainMonth;
for( int index = 0; index < rainfallStats.length; index++ ) {
if ( rainfallStats[ index ] > leastRain ) {
leastRain = rainfallStats [ index ];
leastRainMonth = index + 1;
}
}
return leastRainMonth;
}
public Rainfall ( double [] rainfallStatsGiven) {
rainfallStats = new double [ rainfallStatsGiven.length ];
for (int index = 0; index < rainfallStatsGiven; index++) {
rainfallStats[ index ] = rainfallStatsGiven [ index ];
}
}
public static void fillArrayWithUserInput ( double [] arrayGiven ) {
String userInputString;
double userMonthlyRainfallFigure;
for ( int index = 0; index < arrayGiven.length; index++ ){
userInputString = JOptionPane.showInputDialog(
"Please enter rainfall figures for month " + (index + 1) );
userMonthlyRainfallFigure = Double.parseDouble( userInputString );
arrayGiven [ index ] = userMonthlyRainfallFigure;
}
}
public static void main(String[] args) {
final int MONTH_IN_A_YEAR = 12;
double [] rainfallStats = new double [12];
String userOutputString;
fillArrayWithUserInput( rainfallStats );
Rainfall rainfallData = new Rainfall( rainfallStats );
userOutputString = String.format (
"Total rainfall: %f\nAverage monthly rainfall" + ":"
+ "%f\nMonth with most rain: %f\nMonth with least rain: %f",
rainfallData.getTotalRainfall(),
rainfallData.getAverageRainfall(),
rainfallData.getMostRainMonth(),
rainfallData.getLeastRainMonth() );
JOptionPane.showMessageDialog(null, userOutputString );
System.exit( 0 );
}
}
I get the error:
Raindrop.java:45: error: invalid method declaration; return type required
public Rainfall ( double [] rainfallStatsGiven) {
^
1 error
I try changing public Rainfall into a methoed but it couldnt figure out how to do it, would like any suggestion on how to make this work. I couldnt figure out how to nest the class ethier , and i couldnt figure out how to make the public class into anything else that would work.
I was able to look through my code again and found many errors and fixed them which,in the process, fixed my problem because there were many more problem, so i was able to get what I wanted.
Heres the revised one if anyone also want to look at:
import javax.swing.JOptionPane;
public class Rainfall {
double [] rainfallStats;
public double getTotalRainfall() {
double totalRainfall =0;
for ( int index = 0; index < rainfallStats.length; index++) {
totalRainfall = totalRainfall + rainfallStats[ index ];
}
return totalRainfall;
}
public double getAverageRainfall() {
return getTotalRainfall() / rainfallStats.length;
}
public double getMostRainMonth () {
double mostRain = rainfallStats [ 0 ];
int mostRainMonth = 1;
for( int index = 0; index < rainfallStats.length; index++ ) {
if ( rainfallStats[ index ] > mostRain ) {
mostRain = rainfallStats [ index ];
mostRainMonth = index + 1;
}
}
return mostRainMonth;
}
public double getLeastRainMonth () {
double leastRain = rainfallStats [ 0 ];
int leastRainMonth =1;
for( int index = 0; index < rainfallStats.length; index++ ) {
if ( rainfallStats[ index ] < leastRain ) {
leastRain = rainfallStats [ index ];
leastRainMonth = index + 1;
}
}
return leastRainMonth;
}
public Rainfall ( double [] rainfallStatsGiven) {
rainfallStats = new double [ rainfallStatsGiven.length ];
for (int index = 0; index < rainfallStatsGiven.length; index++) {
rainfallStats[ index ] = rainfallStatsGiven [ index ];
}
}
public static void fillArrayWithUserInput ( double [] arrayGiven ) {
String userInputString;
double userMonthlyRainfallFigure;
for ( int index = 0; index < arrayGiven.length; index++ ){
userInputString = JOptionPane.showInputDialog("Please enter rainfall figures for month " + (index + 1) );
userMonthlyRainfallFigure = Double.parseDouble( userInputString );
arrayGiven [ index ] = userMonthlyRainfallFigure;
}
}
public static void main(String[] args) {
final int MONTH_IN_A_YEAR = 12;
double [] rainfallStats = new double [12];
String userOutputString;
fillArrayWithUserInput( rainfallStats );
Rainfall rainfallData = new Rainfall( rainfallStats );
userOutputString = String.format ( "Total rainfall: %f\nAverage monthly rainfall"+
":+ %f\nMonth with most rain: %f\nMonth with least rain: %f",
rainfallData.getTotalRainfall(),
rainfallData.getAverageRainfall(),
rainfallData.getMostRainMonth(),
rainfallData.getLeastRainMonth() );
JOptionPane.showMessageDialog(null, userOutputString );
System.exit( 0 );
}
}
Related
I don't know what it wrong with my code. Im supposed to put in an input file and sort the numbers from lowest to greatest. When i run the program it returns:Sorted array of 25 ints from P4input.txt after insertInOrder:
31 5 8 8 19 23 25 27 27 31 69 70 71 75 90 98 103 103 109 140 145 145 153 157 162
I don't know why the first number is out of order.
/* Project4.java InsertInOrder with bSearch optimization to compute insertion index */
import java.util.*;
import java.io.*;
public class Project4
{
static final int INITIAL_CAPACITY = 5;
public static void main( String args[] ) throws Exception
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED INPUT FILE NAME ON THE COMMAND LINE
if (args.length < 1 )
{
System.out.println("\nusage: C:\\> java Project4 <input filename>\n\n"); // i.e. C:\> java Project4 P4input.txt
System.exit(0);
}
// LOAD FILE INTO ARR USING INSERINORDER
Scanner infile = new Scanner( new File( args[0] ) );
int[] arr = new int[INITIAL_CAPACITY];
int count= 0;
while (infile.hasNextInt())
{
if ( count==arr.length )
arr = upSizeArr(arr);
insertInOrder( arr, count++, infile.nextInt() );
}
infile.close();
arr=trimArr(arr,count); // Now count == .length
System.out.println( "Sorted array of " + arr.length + " ints from " + args[0] + " after insertInOrder:" );
printArray( arr ); // we trimmed it thus count == length so we don't bother to pass in count
} // END MAIN
// ############################################################################################################
// USE AS IS - DO NOT MODIFY
static void printArray( int[] arr )
{
for( int i=0 ; i<arr.length ;++i )
System.out.print(arr[i] + " " );
System.out.println();
}
// USE AS IS - DO NOT MODIFY
static int[] upSizeArr( int[] fullArr )
{
int[] upSizedArr = new int[ fullArr.length * 2 ];
for ( int i=0; i<fullArr.length ; ++i )
upSizedArr[i] = fullArr[i];
return upSizedArr;
}
// USE AS IS - DO NOT MODIFY
static int[] trimArr( int[] oldArr, int count )
{
int[] trimmedArr = new int[ count ];
for ( int i=0; i<count ; ++i )
trimmedArr[i] = oldArr[i];
return trimmedArr;
}
// ############################################################################################################
static void insertInOrder( int[] arr, int count, int key )
{
int index=bSearch( arr, count, key ); // LEAVE THIS HERE
if (arr[arr.length - 1] == 0)
{
for (int i = count; i >= index + 1; i--)
{
arr[i] = arr[i - 1];
}
arr[index]=key; // LEAVE THIS HERE
}
}
static int bSearch(int[] a, int count, int key)
{
int hi = count-1;
int lo = 0;
int mid = 0;
if(hi == -1)
{
return lo;
}
else
{
mid = (hi+lo)/2;
}
while (lo <= hi)
{
if (key==a[mid])
{
return (mid+1);
}
else if (key < a[mid])
{
hi = mid-1;
mid = (hi+lo)/2;
}
else
{
lo = mid +1;
mid = (hi+lo)/2;
}
}
return (mid +1);
}
} // END PROJECT4
I have successfully compiled this java program (which generates 100 random numbers between 0 and 25, puts them in an array, and sorts them into two different arrays based on whether each is even or odd), although it does not run. I suspect I have made a mistake with one of the while loops, although I don't know for sure. Also, I struggled to get the code in properly formatted in the question, so the tabs are somewhat off, but it is still mostly legible. Here is the .java text:
public class Assignment8
{
public static void main( String [] args )
{
int storage [] = new int[100];
int j = 0;
while ( storage.length < 100 ) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
j++;
}
int oddArray[] = OddNumbers( storage );
int evenArray[] = EvenNumbers( storage );
int currentNumber = 0;
System.out.println( "The odd numbers are: " + "\n" );
while ( currentNumber <= 99 ) {
System.out.println( oddArray[currentNumber] + "\n" );
currentNumber++;
}
System.out.println( "\n" + "The even numbers are: " + "\n" );
currentNumber = 0;
while ( currentNumber <= 99 ) {
System.out.println( evenArray[currentNumber] + "\n" );
currentNumber++;
}
}
public static int[] OddNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int oddArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return oddArray;
}
public static int[] EvenNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int evenArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 == 0 ) {
evenArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return evenArray;
}
}
storage.length does not change throughout the program's execution, as the array is already allocated. You first while loop is thus wrong, as 100 is not less than 100, it will never execute. Instead, you could use a simple for loop:
for (int j = 0; j < storage.length; ++j) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
}
although it does not run
Yes it does. It's just that the execution can get stuck in the infinite loops in the OddNumbers and EvenNumbers methods.
Take a closer look at this:
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
}
else {
continue;
}
The problem is that when storage[currentNumber] is even,
the program executes the else branch with the continue statement,
and since currentNumber hasn't changed, and so storage[currentNumber] hasn't changed either, it's still even, and the else branch will be executed again, and again, and again, forever. EvenNumber has the same problem too.
Here's a fix for OddNumbers:
public static int[] OddNumbers(int[] storage) {
int[] oddArray = new int[storage.length];
int oddIndex = 0;
for (int num : storage) {
if (num % 2 != 0) {
oddArray[oddIndex++] = num;
}
}
return Arrays.copyOf(oddArray, oddIndex);
}
An extra touch I did in this method is the Arrays.copyOf call,
chopping off the excess elements of the array that would be otherwise 0.
Then when you print the content of this array in main, write like this:
System.out.println("The odd numbers are: " + "\n");
for (int num : oddArray) {
System.out.println(num);
}
Follow the same pattern to fix EvenNumbers.
As #Mureinik pointed out,
the loop in main populating storage is also broken.
And you have several other coding issues,
for example the random number generation is particularly ugly and using an obsolete technique.
The complete improved implementation:
import java.util.Arrays;
import java.util.Random;
public class Assignment8 {
public static void main(String[] args) {
Random random = new Random();
int[] storage = new int[100];
for (int i = 0; i < storage.length; i++) {
storage[i] = random.nextInt(25);
}
System.out.println("The odd numbers are: " + "\n");
int oddArray[] = OddNumbers(storage);
for (int num : oddArray) {
System.out.println(num);
}
System.out.println("\n" + "The even numbers are: " + "\n");
int evenArray[] = EvenNumbers(storage);
for (int num : evenArray) {
System.out.println(num);
}
}
public static int[] OddNumbers(int[] storage) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 != 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
public static int[] EvenNumbers(int storage[]) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 == 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
}
I used this code to calculate the max value and the median element in an array of integers, but when I call the methods in my client class, both of these two methods produce an output of zero. The name of the array is "grades" and it is made of randomly generated integers
import java.util.*;
public class StudentGrades {
private int [] grades;
//Constructor
public StudentGrades ( int students)
{
Random number = new Random();
grades = new int[students];
for (int i = 0 ; i < students ; i++)
{
grades[i] = number.nextInt(99) + 1;
}
}
double median;
public void median()
{
Arrays.sort(grades) ;
double median ;
if (grades.length % 2 == 0)
{
int indexA = (grades.length - 1 ) /2;
int indexB = (grades.length)/2;
median = ((double) (grades[indexA] + grades[indexB]))/2;
}
else
{
int medIndex = (grades.length-1) / 2;
median = grades[ medIndex ];
}
}
public double getMedian()
{
return median;
}
int max;
public int getHighest()
{
for(int i = 0 ; i < grades.length - 1 ; i++)
{
int max = 0;
if(grades[i] > max)
{
max = grades[i];
}
}
return max;
}
In my driver, I simply had to prove that the method worked correctly, so it's:
System.out.println(" The highest grade is" + grades.getHighest());
System.out.println("The median grade is" + grades.getMedian());
Few mistakes.
1.) Might be calling getMedian(), whereas the logic is inside median() method.
2.) Inside method, getHighest(),
a.) No need to loop the array, since array is already sorted. So i have commented the code.
Just get the value at last index of array.
public class Test {
static int max;
static double median;
static int[] grades = { 2, 3, 4, 5, 62, 34 };
public static void main(String args[]) {
Arrays.sort(grades);
median();
getHighest();
System.out.println(median);
System.out.println(max);
}
public static void median() {
if (grades.length % 2 == 0) {
int indexA = (grades.length - 1) / 2;
int indexB = (grades.length) / 2;
median = ((double) (grades[indexA] + grades[indexB])) / 2;
} else {
int medIndex = (grades.length - 1) / 2;
median = grades[medIndex];
}
}
public double getMedian() {
return median;
}
public static int getHighest() {
/* for (int i = 0 ; i < grades.length ; i++) {
if (grades[i] > max) {
max = grades[i];
}
}*/
max = grades[grades.length - 1];
return max;
}
Output
4.5
62
I wrote a program about calculating the average of raining in a year and give me the highest and the lowest amount but I am getting an error and I couldn't fix it.
This is my main code : `
public class Rainfall {
//field
private double [] rain;
public void Rainfall (double [] array) {
rain = new double [array.length] ;
for (int i=0; i < array.length ; i++)
rain [i] = array [i];
}
//Methods
public double getTotal() {
double total = 0;
for ( double r : rain)
total +=r;
return total;
}
public double getAverage () {
double a = getTotal () / rain.length;
return a;
}
public double getHighest () {
double highest = rain [0];
for (int i=0 ; i < rain.length; i++) {
if (rain [i] > highest) ;
highest = rain [i];
}
return highest;
}
public double getLowest () {
double lowest = rain [0];
for ( int i=0; i <rain.length; i++) {
if (rain [i] < lowest) ;
lowest = rain [i];
}
return lowest;
}
}
`
and this is the demo :
`
import java.util.Scanner;
import java.text.DecimalFormat;
public class RainFallDemo {
public static void main (String [] args ) throws NullPointerException
{
final int year1 = 12;
double [] rains = new double [year1];
getData (rains) ;
Rainfall rainfallData = new Rainfall ();
DecimalFormat values = new DecimalFormat ("#0.00") ;
System.out.println("The total rain is" + values.format(rainfallData.getTotal()));
System.out.println("The average is " + values.format (rainfallData.getAverage()));
System.out.println("The highest rain is " + values.format (rainfallData.getHighest()));
System.out.println("The lowest is " + values.format (rainfallData.getLowest()));
}
public static void getData (double [] array) {
Scanner keyboard = new Scanner (System.in) ;
for ( int i=0 ; i < array.length; i++)
{
System.out.println ("what was the amont of rain for month " + (i + 1) + "?");
array [i] = keyboard.nextDouble ();
while (array[i] < 0 )
{
System.out.print ( " Invalid input. You entered a negative number. Enter a" +
"value that is greater than zero");
array [i] = keyboard.nextDouble ();
}
}
}
}`
I was getting the wrong lowest and wrong highest and The program has to show which month had the lowest and highest in the output but but I can't figure out the code!!
Remove the semicolon at the end of your if lines. That is causing the if to execute an empty statement when it is true. Then the next line is always executed no matter what.
I was given an example on how to alphabetically sort my Actor objects in an array.
public class AlphaSortingExchange
{
public static void main(String[ ] args)
{
String[ ] names = {"joe", "slim", "ed", "george"};
sortStringExchange (names);
for ( int k = 0; k < 4; k++ )
System.out.println( names [ k ] );
}
public static void sortStringExchange( String x [ ] )
{
int i, j;
String temp;
for ( i = 0; i < x.length - 1; i++ )
{
for ( j = i + 1; j < x.length; j++ )
{
if ( x [ i ].compareToIgnoreCase( x [ j ] ) > 0 )
{ // ascending sort
temp = x [ i ];
x [ i ] = x [ j ]; // swapping
x [ j ] = temp;
}
}
}
}
}
I am only allowed to follow this sort of format in sorting my array. NetBeans is not liking the "compareToIgnoreCase" statement in my code, giving the error
"cannot find symbol: method compareToIgnoreCase(Actors) location class
Actors"
. Below is my sorting function.
public static void sortActors(Actors actors[]) {
int i, j;
Actors temp;
for (i = 0; i < actors.length - 1; i++)
{
for (j = i + 1; j < actors.length; j++)
{
if (actors[i].compareToIgnoreCase(actors[j]) > 0)
{
temp = actors[i];
actors[i] = actors[j];
actors[j] = temp;
}
}
}
}
This is my object array and an example of an object in the array. Like I said before, I can only use compareToIgnoreCase. I am at a loss at how to use this function
private static void createActorsList() {
Actors[] actors = new Actors[Constants.NUMBER_OF_ACTORS];
Actors ladyViolet = new Actors();
ladyViolet.setName("Lady Violet");
ladyViolet.setDialogue("dialogue");
ladyViolet.setHappiness(0);
ladyViolet.setHealth(100);
actors[Constants.VIOLET] = ladyViolet;
}
Any help or solution would be much appreciated!
Thanks in advance!
Your Actor class doesn't have a compareToIgnoreCase method. You probably mean to call the method on one of the class's fields, e.g.,
if (actors[i].getName().compareToIgnoreCase(actors[j].getName()) > 0)
If the method needs to be on the Actor class, you'd have to write your own implementation:
public int compareToIgnoreCase(Actor actor) {
return this.name.compareToIgnoreCase(actor.name);
}