I'm writing a program that takes 10 floating point numbers as input. However, whenever I enter a decimal the program sends me an error. I question is: how would I edit my current try-catch exception to catch only letters, etc., and allow decimals to be entered (and then store them into an array). Also, regardless of this problem, my program is also outputting the average many times, and always saying that it is equal to 0.
Below is the program:
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
new Average().average(new double[10]);
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
System.out.println("Average value of your input is: " + average);
System.out.println();
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}
You're using the nextInt() function, which only returns ints. Ints cannot hold decimals. Consult the API and take a look at the nextFloat() and nextDouble() methods instead.
For your Average problem, Your print statement is into a for loop so it will be executed number.length times. Move the print statements outside the loop. You will also need the declaration of the average variable to be outside the loop. Also you should only need to the loop to calculate the sum, you don't need the calculate the average everytime
double average;
for(/*loop conditions*/)
{
sum = sum + number[i];
}
average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();
Related
I'm not sure what to title this question(if anyone has input on what to name the question, please let me know). My program asks the user for 5 int and 5 doubles. Then those numbers are put in an array and passes it to a method to get the average. My question is if I separate the user input by spaces and press enter(like so, 5 space 6...enter; it allows me to enter more than what is allowed in the array index. Why doesn't it give you a error? and how do you prevent this? Also any advice on how I write code would be helpful too!
Here is the code.
import java.util.*;
public class Lab7A_BRC{
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int [] list1 = new int[n];
double [] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for(int i = 0; i < n; i++) {
list1[i]= input.nextInt();
if(i == (n - 1)){
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
}
}
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++){
list2[i]= input.nextDouble();
if(i == (n-1)){
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n){
int sum = 0;
for(int i = 0; i < n; i++){
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n){
double sum = 0;
for(int i = 0; i < n ; i++){
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
It doesn't give you an error because you only read the first 5 values, as stated in your for loop.
The first thing is you should decouple your input logic from your output logic, so you know for sure you're in your 5th number when you exit the for loop.
Then you can check if there's anything else than a blank string left, if there is then you can throw an exception stating it has too many numbers.
I've adapted the integer part, you can easily adapt the doubles logic.
Feel free to ask if you have any doubts.
The adapted code:
import java.util.Scanner;
public class Lab7A_BRC {
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int[] list1 = new int[n];
double[] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for (int i = 0; i < n; i++) {
list1[i] = input.nextInt();
}
if (!input.nextLine().equals("")) {
throw new RuntimeException("Too many numbers entered!");
}
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++) {
list2[i] = input.nextDouble();
if (i == (n - 1)) {
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
I think you're confusing two different concepts.
One is the input, and another one is your variable.
Input is a buffer (read: block of data) managed by the shell and the Scanner. It can contain an arbitrary amount of data, you have nothing to do with it.
What happens in your code is that the scanner takes the buffer and parses (read: interprets) the next valid value from the buffer and transforms it into the right data type - until the "nth" element. So, because you're taking "n" elements (controlled by the for), it doesn't matter how much data is available in the input buffer, you always read a finite amount.
The only way the amount of data matters is when there's no more input for the scanner to read from, in which case it asks for more input.
The reason is that you are iterating till the n number that you defined in the beginning.
for(int i = 0; i < n; i++) {
list1[i]= input.nextInt();
So if you try to enter 1 1 1 1 1 124124 1241 you will see that the average is 1 because the rest is ignored and not added to the list. Because it doest not try nextInt() more than n given.
I am a beginner, so my answer might be wrong:), sorry for that. This code is working for me. Like #iajrz mentioned, you can do spaece or newline when try to use system.in.
Because the for loop does n iterations so you pick up only the first n integers of the input. If your input is 1 2 3 4 5 6 7 8 it will select only 1 2 3 4 5 (because in your code n=5). You can also insert multiple digits number separated by spaces, so input 15 0 00 0010 0 has average=5
The purpose of this program is to intake 5 values (test scores) from the user, then output the average score. I am not familiar with arrays so I really don't have the slightest clue what I'm doing wrong. All I know is the double 'sum' cannot be set equivalent to the int ' total'. Sorry for being dumb but I'M TRYING HERE :)
import java.util.Scanner;
public class Main
{
public static void main (String [] args)
{
int x = 0;
double testScore[] = new double[5];
double sum[] = new double[5];
double total;
int avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
score = testScore[i];
sum = testScore;
sum = (int)total;
avg = ((total) / 5);
System.out.print("The sum of your grades is " +avg +"\n");
}
}
}
double sum = 0;
for (double score: testScore) {
sum += score;
}
double avg = sum / testScore.length;
Here you go, I tried not to change much of your code so you can still understand what I changed!
public static void main(String[] args) {
double testScore[] = new double[5];
double sum = 0;
double avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++) {
System.out.println("Enter your grade for test number " + 1);
double score = keys.nextDouble();
sum += score;
avg = sum / 5;
System.out.print("The sum of your grades is " + avg + "\n");
}
}
Basically, all you need is the sum variable, you can get the avg from it!
first i would declare your variables like this:
int x = 0;
double[] testScore = new double[5];
double[] sum = new double[5];
double total;
int avg;
A few changes to be made:
You don't want to set score to testscore[i] because its null so flip that. If you want to cast the doubles to integers use Integer.valueOf(). You should also place them outside the for loop and calculate sum in the for loop, as shown:
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
testScore[i] = score;
sum += Integer.valueOf(score);
total += score;
}
avg = Integer.valueOf(total / testScore.length);
System.out.print("The sum of your grades is " +avg +"\n");
I haven't tested this code but i hope it helps.
In order to get the sum of all elements of an array, you will need to iterate over it:
Scanner keys = new Scanner(System.in);
double[] testScore = new double[5];
double sum = 0.0;
for (int i = 0; i < testScore.length; i++) {
// We don't need to use x, we already have i
System.out.println("Enter your grade for test number " + (i + 1));
double score = keys.nextDouble();
testScore[i] = score; // Store the grade into the element #i of the array
// We can instantly process the data we have to collect. Otherwise we must
// walk a second time over the elements
sum = sum + score; // Or the shorthand notation: sum += score
}
double avg = sum / testScore.length;
System.out.println("The average of your grades is " + avg + "\n");
I modified the following things to your code:
You are using two arrays (testScore and sum) having the same function. Both are meant to store the grades in it. I removed one of them.
I removed x, because i fulfills its function already.
I changed the type of your variable avg to a double. Feel free to change it back to an int, but then the average's decimals will be truncated (for instance, 4.6 will be 4).
import java.util.Scanner;
public class Lab11d
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
double [] anArray; // declares an array of integers
anArray = new double [5];
int min=0;
//Initalizes the array values//
System.out.println ("Enter 5 numbers of your choosing");
double a = in.nextDouble();
for ( int count=0; count < 5; count++)
{
anArray[count] = a;
a = in.nextDouble();
}
//Prints array values//
for (double value : anArray)
System.out.println ("Element at index " + (min++) + ":"+ value + "" );
}
}
It runs, but I only want to input 5 numbers, not sure what I am doing wrong. It allows me to enter six with like a limit of 5, curious how to change it please
Because you get one double before your loop. Change it to something like
// double a = in.nextDouble();
for (int count=0; count < 5; count++)
{
double a = in.nextDouble();
anArray[count] = a;
}
or eliminate a altogether like
for (int count=0; count < 5; count++)
{
anArray[count] = in.nextDouble();
}
You are accepting a double first time and then iterating through a loop which accepts 5 doubles i.e. in total you are accepting 6 doubles.
You have to edit your for loop as,
for ( int count=0; count < 5; count++)
{
anArray[count] = in.nextDouble();
}
What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}
Can anyone help me with my code? I have to find the average of every column in a matrix but I don't know what's wrong with my code cause it doesn't work.This is my code: (By the way it shows no mistakes and I had to put the numbers with JOptionPane, thanks for your help)
import javax.swing.JOptionPane;
public class Matrix {
private static final int String = 0;
public static void main(String[] args) {
double[] numbers = new double[10]; // 10 doubles
double sum = 0.0;
for (int i = 0; i < numbers.length; ++i) {
sum += numbers[i];
String input = JOptionPane.showInputDialog("Enter a number");
double d = Double.parseDouble(input);
double avg = 0.0;
avg = sum/numbers[i];
}
}
}
You never assign any numbers to your numbers array, so they all default to 0.
Try:
numbers[i] = Double.parseDouble(input);
double avg = 0.0;
sum += numbers[i];
avg = sum / (i + 1); // (i + 1) is the number of inputted numbers