The program is supposed to return
The test scores in descending order are: (Scores) The average is
(average)
The result that I am receiving is
The average is (average) The test scores in descending order are:
(Scores)
How can I fix it to receive the proper return
import java.util.Scanner;
public class Average
{
private int[] data;
private double mean;
public Average()
{
data = new int[5];
int number = 0;
int Temp = 0;
String[] Scores = new String[5];
Scanner keyboard = new Scanner(System.in);
for(int index = 0; index < data.length; index++)
{
number++;
System.out.print("Enter test score #" + number + ":");
Temp = keyboard.nextInt();
data[index] = Temp;
}
selectionSort();
calculateMean();
}
public void selectionSort()
{
int n = data.length;
for(int index = 0; index < n-1; index++)
{
int min_idx = index;
for(int j = index+1; j < n; j++)
if(data[j] >= data[min_idx])
min_idx = j;
int temp = data[min_idx];
data[min_idx] = data[index];
data[index] = temp;
}
}
public String toString()
{
String MyScore = "Your test scores in descending order are: " + "\n";
for(int index = 0; index < data.length; index++)
{
MyScore += data[index] + " ";
}
return MyScore;
}
public void calculateMean()
{
int Sum = 0;
int Mean = 0;
for(int index = 0; index < data.length; index++)
{
Sum += data[index];
}
Mean = Sum/data.length;
System.out.println("The average is " + mean);
}
}
What would I have to swap around in order to make this work?
Edit: The Average class is used in this file
public class AverageDriver
{
public static void main(String[] args)
{
Average MyScores = new Average();
System.out.print(MyScores);
}
}
You should call calculateMean() only after calling toString().
So you can either modify the constructor
selectionSort();
System.out.println(toString());
calculateMean();
or calling only selectionSort(); in the constructor, then in your main
public class AverageDriver
{
public static void main(String[] args)
{
Average myScores = new Average();
System.out.print(myScores);
myScores.calculateMean();
}
}
By the way, you should use lowercase name for variables, this will fix the error in calculateMean(): you are calling System.out.println("The average is " + mean); but the variable is Mean.
The error why it's not printing the correct average lies in this method:
public void calculateMean() {
int Sum = 0;
int Mean = 0;
for (int index = 0; index < data.length; index++) {
Sum += data[index];
}
Mean = Sum / data.length;
System.out.println("The average is " + mean);
}
You're printing out mean which is defined globally, but never initialized so it defaults to 0. In this method you have the variable Mean (capitalized) which is the variable the actual value is stored in, that's the variable you want to print.
public static void main(String[] args)
{
Average MyScores = new Average();
System.out.print(MyScores);
}
When you create the Average instance the constructor is called. In the constructor there is a call to calculateMean(), which prints
The average is (average)
When you print MyScores the override toString() is being called, which prints The test scores in descending order are: (Scores).
Take out the methods calls out of the constructor (they shouldn't be there in the first place) and call them from main
public static void main(String[] args)
{
Average myScores = new Average();
System.out.print(myScores);
myScores.selectionSort();
myScores.calculateMean();
}
Related
I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15
What the title says: I'm writing a program where it calculates and shows the sum of the digits in a number (Ex: 3782 sum = 20).
However, I'm having trouble calling the method I used to calculate it back to the main method - it gives me a "java: cannot find symbol" error.
I need to use a String for this, and cannot use int for my values.
Here's my code:
public class digitSum {
//MAIN
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole number: ");
String num = input.nextLine();
//SUM METHOD CALL
// This is the method call I'm having trouble with.
printResult(numSum(sum));
}
//SUM METHOD
static void numSum(int i, String num, int sum) {
for (i = 0; i < num.length(); i++) {
char a = num.charAt(0);
char b = num.charAt(i);
sum = a + b;
}
System.out.println("The digit-sum of" +num+ " is: " +sum);
return;
}
}
You've never defined sum variable:
int sum = 0;
printResult(numSum(0, num, sum));
Or even better - why passing accumulator and counter to the function if it's not recursive?
static void numSum(String num) {
int sum = 0;
for (int i = 0; i < num.length(); i++) {
char a = num.charAt(0);
char b = num.charAt(i);
sum = a + b;
}
System.out.println("The digit-sum of" +num+ " is: " +sum);
return;
}
Then invoke it by simply calling numSum(num).
P.S.: You also need to have printResult defined (or not - numSum is printing the result).
#chrylis -on strike- notices, that printing the result of your calculation in the caller would be even better:
static int numSum(String num) {
int sum = 0;
for (int i = 0; i < num.length(); i++) {
char a = num.charAt(0);
char b = num.charAt(i);
sum = a + b;
}
return sum;
}
And in the main method:
System.out.println(numSum(num));
import java.util.Scanner;
public class ProjectFour {
public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
}
//finding the average
public static int analyzeNumbers(int[] firstArray){
int avg;
avg=sumArray(firstArray);
avg=avg/firstArray.length;
return avg;
}
//suming the array method
public static int sumArray(int[] firstArray){
int sum = 0;
for(int x=0;x<firstArray.length;x++){
sum+=firstArray[x];
}
return sum;
}
**this is where im running into problems im kinda stumpted**
// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.
public static int aboveAvg(int[] firstArray){
int[] aboveAvg;
aboveAvg = new int[0];
int x;
for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
aboveAvg+=firstArray[x];
}
return aboveAvg;
}
}
Try using a for loop.
int sum = 0;
for(int i = 0; i < firstArray; i++) {
int getSum = firstArray.get(i);
sum + getSum;
}
int average = sum / firstArray.length;
int[] aboveAverage;
for(int c = 0; c < firstArray; c++) {
if(firstArray.get(c) > average) {
aboveAverage.add(firstArray.get(c));
}
}
This aboveAvg function is completly wrong.
public static List<Integer> aboveAvg(int[] firstArray){
List<Integer> aboveAvg = new ArrayList<Integer>();
int Avg = analyzeNumbers(firstArray);
for(int i = 0; i<firstArray.length; i++)
{
if(firstArray[i] > Avg)
{
aboveAvg.add(firstArray[i]);
}
}
return aboveAvg;
}
Check your for loop and more examples about it
+= will sum two values, won't add new element on any array.
you have to define your return value correctly.
You can use List for create arrays, it's more flexible.
Here's My Code; and I can find an array with this and I would like to calculate the mean of the values (overall) after this I would like to calculate standard deviation of this but I couldn't understand the question exactly so I dont have a method for now. Here's the question for standard deviation (Write a method that takes two parameters --a set of int values in an array and a double value representing their mean-- and computes and returns the standard deviation of the values using the given mean.)
import java.util.*;
public class Test
{
final static int N = 100;
static int limit = 0;
static int[] list;
static int i, j;
static int sum = 0;
static Scanner scan = new Scanner (System.in);
public static int[] generateArray ()
{
System.out.print ("Enter your array limit: ");
limit = scan.nextInt();
list = new int[limit];
for(i = 0; i < limit; i++)
{
list[i] = (int) (Math.random() * 2 * N - N);
}
return list;
}
public static void printArray()
{
for(j = 0; j < limit; j++)
System.out.print (list[j] + "\t");
}
public static void meanArray()
{
sum = sum + list[j]; //PROBLEM HERE
System.out.println (sum);
}
public static void main(String[] args)
{
generateArray();
printArray();
meanArray(); //PROBLEM HERE
}
}
To generate the mean value, add up all values in your list and devide them by the number of values:
public static void meanArray() {
double result = 0;
for(int i : list) {
result += i;
}
result /= list.length;
System.out.println(result);
}
This code takes a random sampling of numbers, plugs them into an array, counts the odd numbers, and then lets the user pick an integer to see if it matches. This works great now with just arrays, but I want to convert it to work with ArrayLists. What's the easiest way to do this?
import java.util.Scanner;
import java.util.Random;
public class ArrayList {
public static void main(String[] args) {
// this code creates a random array of 10 ints.
int[] array = generateRandomArray(10);
// print out the contents of array separated by the delimeter
// specified
printArray(array, ", ");
// count the odd numbers
int oddCount = countOdds(array);
System.out.println("the array has " + oddCount + " odd values");
// prompt the user for an integer value.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find in the array:");
int target = input.nextInt();
// Find the index of target in the generated array.
int index = findValue(array, target);
if (index == -1) {
// target was not found
System.out.println("value " + target + " not found");
} else {
// target was found
System.out.println("value " + target + " found at index " + index);
}
}
public static int[] generateRandomArray(int size) {
// this is the array we are going to fill up with random stuff
int[] rval = new int[size];
Random rand = new Random();
for (int i = 0; i < rval.length; i++) {
rval[i] = rand.nextInt(100);
}
return rval;
}
public static void printArray(int[] array, String delim) {
// your code goes here
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1)
System.out.print(delim);
else
System.out.print(" ");
}
}
public static int countOdds(int[] array) {
int count = 0;
// your code goes here
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 1)
count++;
}
return count;
}
public static int findValue(int[] array, int value) {
// your code goes here
for (int i = 0; i < array.length; i++)
if (array[i] == value)
return i;
return -1;
}
}
I rewrite two of your functions,maybe they will useful for you.
public static List<Integer> generateRandomList(int size) {
// this is the list we are going to fill up with random stuff
List<Integer> rval = new ArrayList<Integer>(size);
Random rand = new Random();
for (int i = 0; i < size; i++) {
rval.add(Integer.valueOf(rand.nextInt(100)));
}
return rval;
}
public static int countOdds(List<Integer> rval) {
int count = 0;
for (Integer temp : rval) {
if (temp.intValue() % 2 == 1) {
count++;
}
}
return count;
}