I'm trying to use recursion to take the output of an Array. I've been able to create the input where the input takes the array data but no matter what I input, the array continuously returns 0.0. I did a test print of the array and it appears the data is going to the array so I'm not sure where I'm going wrong.
import java.util.Arrays;
import java.util.Scanner;
public class AverageGradeCourtney {
public static void main(String args[])
{
int i = 0;
int sum = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
double average = findAverage(newClassSize);
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
//System.out.println(average);
}
System.out.println("The average for the class is: " + average);
}
public static double findAverage(int array[])
{
if (array.length==0)
{
return 0;
}
return findAverageHelper(array,0,0);
}
public static double findAverageHelper(int[] array, int index, int sum)
{
if (index==array.length)
{
return (double) sum/array.length;
}
return findAverageHelper(array, index+1, sum+=array[index]);
}
}
The output continues to look like this:
Please enter the class size:
2
Please enter the grade of the user at: 1
12
Please enter the grade of the user at: 2
5
The average for the class is: 0.0
Related
I am learning Java and am having a very simple problem.
How to print the final sum from a while loop?
if I enter integers 10 10 40
the output I get is
10
20
60
but am only trying to get the final 60.
This answer can also relate to printing the final anything in a while loop as I just can't seem to get this.
my sample code below...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
System.out.println("The Sum is: " + total);
}
}
Your main problem is that you have put the print statement inside the loop.
Also, in.hasNextDouble() doesn't make sense for input from the keyboard; it is useful when you are reading data from a file or a Scanner for some string. You can use an infinite loop (e.g. while(true){...}) and break it when there is no input from the user.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up, press Enter without any input to exit: ");
double total = 0;
while (true) {
String input = in.nextLine();
if (input.isBlank()) {
break;
}
total += Double.parseDouble(input);
}
System.out.println("The Sum is: " + total);
}
}
A sample run:
Enter a sequence of numbers to sum up, press Enter without any input to exit:
10
20
30
The Sum is: 60.0
A demo of a Scanner for a string:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner("10 20 30");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
}
Output:
The Sum is: 60.0
The problem lies in: System.out.println("The Sum is: " + total);
If you would like for only the final sum to be printed it needs to be outside of the while loop.
Please, print the total outside of the loop and it will work fine !
Code:
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
my lecturer give me these question:
1. Write a program that does the following:
a. Get the number of students from user (n)
b. Ask user to enter n grades of n students, store them in an array.
c. Print out the max, the min, and the average of those n grades.
Note: write 3 methods to return the max/min/average element of an array
and use them in this program.
I try to do it, but the output of my program doesn't like what I'd expected.
Here is my code:
package javaapplication2;
import java.util.*;
public class JavaApplication2 {
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i;
}
}
return max;
}
public static double min(double[]y) {
double min = max(y);
for (int i =0; i < y.length; i++) {
if (y[i] < min) {
min = y[i];
}
}return min;
}
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
double grades [] = new double [5000];
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
}
And here is my output:
Enter student's name:
k
Enter student's score:30
The max grade is: 0.0
The min grades is: 0.0
Enter student's name:
Yah, I dont know why my max grade and min grade is 0.0. Anyone, please help me, thank you !!!
Your problem comes from the grade array s being reassigned each loop
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
//you set the grades array each loop to a new empty array
double grades [] = new double [5000]; //<--- Move this one out
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
Move it out and then try to get the methods done :)
Edit:
You also have a little error in the max method in regard of the value.
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i; //<-- Not max = i but max = x[i] :)
}
}
return max;
}
In the function where you are calculating max, you should use:
if (max < x[i]) {
max = x[i];
}
As you want to return the element and not it's index. Also you would want to declare your array named grades before the while loop or else it would create a new array on every iteration.
And for improving the code performance:
1. you can in your max/min functions, exit the loop as soon as you encounter a value=0. In your current code the loop iterates 5000 times even if there is a single entry.
2. in your min function instead of doing double min = max(y); you should use double min = Double.MAX_VALUE;. It will prevent the unnecessary calling of the max function.
My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)
I know that scanf is not a java function, so i'm hoping someone can help me to understand how to convert this. Research on this topic is difficult to piece together.
This is my code:
import java.util.Scanner;
public class Average {
Scanner Scanner = new Scanner (System.in);
int main (){
int counter;
int number;
int total;
float average;
total = 0;
counter = 0;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
While (number != 0) {
total = total + number;
counter = counter + 1;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
}
if(counter != 0) {
average = (float) total / counter;
System.out.println("Average is %.2f\n", average);
} else {
System.out.println("No valid numbers have been entered.");
return 0;
}
}
}
use input like this`
public class seting{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);`
int total = 0;
System.out.printlnln("Enter the value of total :");
total = scan.nextInt(); // use integer input
}
}
You cannot use the same name for the object as for the class. Change Scanner initialization as follows:
Scanner scanObj = new Scanner(System.in);
Replace all your scanf statements with the below:
number = scanObj.nextInt();
These are the changes done to your code:
import java.util.Scanner;
public class one {
public static void main(String[] args) {
Scanner Scanner = new Scanner (System.in);
int counter;
int number = 1;
int total;
float average;
total = 0;
counter = 0;
while(number != 0){
System.out.println("Enter the number 0 to end: ");
number = Scanner.nextInt();
System.out.printf("%d", number);
total = total + number;
counter = counter + 1;
}
if(counter != 0){
average = ((float)total /(float)counter);
System.out.printf("Average is %.2f\n", average);
}
else{
System.out.println("No valid numbers have been entered.");
//return 0;
}
}
}
First the Scanner takes the value the user entered. number = Scanner.nextInt(); This must be done inside your while loop since its the one that check the condition.
The next thing I changed was average = (float) total / counter;
This casts the total value only to a float. use brackets to both ends.
average = ((float)total /(float)counter); like this
I am in the middle of an exercise on arrays and I am currently stuck on one of the variations in which
I have to use an Array (no arraylists) to gather user input with a
max number of 100 inputs and the inputs must stop if a negative
number is inserted.
The program then prints each value input by the user on a separate
line with the "Above", "Below", or "EqualTo" relating to the average
of the inputs.
Issue :- I am currently stuck in how I am supposed to get the value of the inputs from the load method into the correct spots on the print method. The program will compile but will only return an average1 equal to zero. Any help is appreciated, I just can't use an arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}
That's because you are not saving the average to the global variable average1 but to a local variable. That is why average1 returned by getAverage() equal to zero.
Change the below line in load() method from
double average1 = sum / used;
to
average1 = sum / used;