I've written some code that has a scanner read from a text file on my computer, but when running the code, the scanner only reads every other number that's in the text file.. any ideas?
Note: For the grades.txt, this is the file
"3 8 1 13 18 15 7 17 1 14"
import java.util.*;
import java.io.*;
public class GradeAverage
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("C:\\Users\\Media - Graphics\\Documents\\SCHOOL\\NCVPS\\GradeAverage\\grades.txt"));
int i = 0;
int sum = 0;
int lineNumber = 0;
int average = 0;
while(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
lineNumber++;
}
System.out.println("The sum of the numbers: "+sum);
System.out.println("The number of scores: "+lineNumber);
average = sum/lineNumber;
System.out.println("The average of the numbers: "+average);
}
}
Here's what it outputs:
3
1
18
7
1
The sum of the numbers: 67
The number of scores: 5
The average of the numbers: 13
Every time you call nextInt() in your loop, you consume one int. So when you do
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
You consume two int(s). You want something like
int t = scanner.nextInt();
System.out.println(t);
sum += t;
Also your average is currently an int (I would expect a float or double).
double average = sum/(double)lineNumber;
Don't forget to remove int average = 0; (or modify this and average accordingly).
Related
Here is the coding question for which I am trying to solve
Write a program that reads two numbers aa and bb from the keyboard and calculates and outputs to the console the arithmetic average of all numbers from the interval [a; b][a;b], which are divisible by 33.
Sample Input 1:
-5
12
Sample Output 1:
4.5
Here is my Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double average = 0;
int a = scanner.nextInt();
int b = scanner.nextInt();
Problem: Throws Arithmetic Exception
What is the problem?
Your variable i loops from -5 to 12. Then, you divide (a + b) / i (line 14).
0 is between -5 and 12. Thus, you will eventually divide by zero.
(I assume that line 13 is supposed to prevent this, but the way you have written it, it does not. In fact, 0 is among the very few values of i for which line 14 will actually be executed.)
According to your sample input and sample output, you need to add all the numbers in the range that are divisible by 3 and divide that total by how many different numbers are in the range.
Between -5 and 12, the numbers that are divisible by 3 are:
-3, 0, 3, 6, 9, 12
When you add them all together, you get 27.
And there are 6 different numbers altogether.
So the average is 27 divided by 6 which gives 4.5
Now for the code.
import java.util.Scanner;
public class RangeAvg {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter lower bound: ");
int a = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter upper bound: ");
int b = scanner.nextInt();
int lower = Math.min(a, b);
int upper = Math.max(a, b);
int total = 0;
int count = 0;
for (int i = lower; i <= upper; i++) {
if (i % 3 == 0) {
System.out.println(i);
total += i;
count++;
}
}
System.out.println("total = " + total);
System.out.println("count = " + count);
if (count > 0) {
double average = (double) total / count;
System.out.println("average = " + average);
}
else {
System.out.printf("No numbers divisible by 3 between %d and %d%n", lower, upper);
}
}
}
Below is a sample run:
Enter lower bound: -5
Enter upper bound: 12
-3
0
3
6
9
12
total = 27
count = 6
average = 4.5
I need to write a code where you insert 10 grades and get back the average of those ten grades. I know how to do it, except I don't know how to calculate the sum of all the grades. I found on this site this code:
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
so I wrote my code like this and it worked!:
import java.util.Scanner;
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Please enter how many grades you want to insert : ");
int num1 = scan.nextInt();
int num;
double sum =0;
for(int i= 0; i<num1; i++)
{
System.out.println("Please enter a grade: ");
num = scan.nextInt();
sum += num;
}
System.out.println("the average is: "+(sum)/num1);
}
so my question is what sum+=num; mean? how does that line give me the sum? and why I had to write double sum= 0?
Over here I explain each of those lines to better help you understand this code.
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); //this is what allows the user to input their data from the console screen
System.out.println("Please enter how many grades you want to insert : "); //this just outputs a message onto the console screen
int num1 = scan.nextInt(); //This is the total number of grades the user provides and is saved in the variable named num1
int num; //just a variable with nothing in it (null)
double sum =0; //this variable is to hold the total sum of all those grades
for(int i= 0; i<num1; i++) //loops as many times as num1 (if num1 is 3 then it loops 3 times)
{
System.out.println("Please enter a grade: "); //output message
num = scan.nextInt(); //every time the loop body executes it reads in a number and saves it in the variable num
sum += num; //num is then added onto sum (sum starts at 0 but when you add 3 sum is now 3 then next time when you add 1 sum is now 4 and so on)
}
System.out.println("the average is: "+(sum)/num1); //to get the average of a bunch of numbers you must add all of them together (which is what the loop is doing) and then you divide it by the number of items (which is what is being done here)
}
sum += num; Means that your sum which is declared 0 is added with num which you get from the console. So you simply make this: sum=sum+num; for the cycle. For example sum is 0, then you add 5 and it becomes sum=0+5, then you add 6 and it becomes sum = 5 + 6 and so on. And it is double because you are using division.
The reason you needed to write
double sum = 0.0;
is because you needed to initialize the sum first. Next the
sum += num;
means
sum = sum + num;
just in a more simple way.
I am trying to make a program, that gets an integer from the user.
Adds up all the numbers from 1 to that number, and display the total. Below is the program that I wrote and the problem is sum doesn't add the value the user inputs.
import java.util.Scanner;
public class AddingValuesForLoop
{
public static void main(String[] args)
{
int Number,Sum;
Sum=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter your Number: ");
Number=keyboard.nextInt();
for (int i=1;i<=Number;i++)
{
Sum=i+Number;
System.out.println("\r"+i+"");
}
System.out.println("the total Sum = "+Sum+".");
}
}
OUTPUT:
Enter number: 5
1
2
3
4
5
The total Sum = 10.
You shall write Sum = i + Sum instead of Sum=i+Number. Here is the full code.
import java.util.Scanner;
public class AddingValuesForLoop{
public static void main(String[] args) {
int Number,Sum;
Sum=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter your Number: ");
Number=keyboard.nextInt();
for (int i=1;i<=Number;i++) {
// Add i to sum until now
Sum=Sum+i;
}
System.out.println("the total Sum = "+Sum+".");
}
}
Your problem is in this line:
Sum=i+Number;
This line means that your sum will contain the last i value from the loop and the number entered by the user, it should looks like:
Sum += i;
And then add the number entered by the user to the Sum value, your code will looks like that:
import java.util.Scanner;
public class AddingValuesForLoop{
public static void main(String[] args) {
int Number,Sum;
Sum=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter your Number: ");
Number=keyboard.nextInt();
for (int i=1;i<=Number;i++) {
Sum +=i;
System.out.println("\r"+i+"");
}
Sum+=Number;
System.out.println("the total Sum = "+Sum+".");
}
}
2 problems with your program.
Firstly, you are resetting the value of Sum in each iteration. So during the last iteration, the i value is 5, Number value is 5 and thus you get output as 10.
Secondly, you want to add up numbers from 1 to that Number, so it should be something like this:
sum = sum + i;
If the user enters 3
(sum = 0 + 1, sum = 1 + 2, sum = 3 + 3), thus output will be 6.
since you use
Sum=i+Number;
which in that code means get the value of i and value of number and sum them together and put it in Sum var each time that's way there is no sum happening
you should use
Sum += i+Number;
which means
Sum = Sum + (i+Number);
I am fairly new to java and I'm trying to code to find the average. I understand that the average is adding all the numbers and then dividing the sum by the number of numbers but I'm not really sure how to code that. My guess is that I'd need a for loop but I don't know what to do from there. The program basically asks for a file to be read and then calculate the average. Here's the code I have so far:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Calculations
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));
int length = reader.nextInt();
double [] num = new double[length];
double [] num2 = new double[length];
System.out.println("The numbers are:");
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
System.out.println(num[i]);
}
}
}
The file I would be using is list.txt which contains:
20
1.1 2 3.3 4 5.5 6 7 8.5 9 10.0
11 12.3 13 14 15.5 16.1 17 18 19.2 20.0
The mean should be 10.625. Any help is deeply appreciated. Thank you in advance.
Just introduce a new variable sum, initialize it to 0, and add the elements to the variable while you are printing them.
System.out.println("The numbers are:");
double sum = 0; //new variable
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
sum += num[i];
System.out.println(num[i]);
}
sum /= (double) length; //divide by n to get the average
System.out.print("Average : ");
System.out.println(sum);
It appears that you're simply having trouble computing the average; I'll address that issue here:
In Java 7 and below, use a for loop:
double sum = 0; //declare a variable that will hold the sum
//loop through the values and add them to the sum variable
for (double d : num){
sum += d;
}
double average = sum/length;
In Java 8 you can use a Stream to compute the average
double sum = Arrays.stream(num).sum(); //computes the sum of the array values
double average = sum/length;
I am new to Java and I would like some help. I have to solve this problem and I have it almost 90% solved:
Prompt the user to enter number of students. It must be a number that is perfectly divisible by 10 i.e. (number % 10) = 0
Check user input. If user input is not divisible by 10, keep asking the user for input until he enter a right number.
Accept user input and generate that many random numbers in the range from 0 to 100.
Print a matrix of random numbers and calculate the sum and average of all these random numbers and print them to the user.
Format sum and average to three decimal points.
This is my code so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.abs(Math.random() * ( 0 - 100 ));
System.out.print(" " +dec.format(numb) + " ");
}
}
}
As you can see, I have solved until the first part of # 4. I am not sure how I could sum all those random numbers displayed on the screen after user input. Of course, we have to store them in an array but I tried to do that but couldn't. So, how could I complete step #4 and 5? I would appreciate any help. Thanks a lot guys.
Here is how you should do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
double sum=0;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.random() * ( 100 - 0));
System.out.print(" " + dec.format(numb) + " ");
sum += numb;
}
System.out.println("The sum is: " + dec.format(sum));
System.out.println("The average is:" + dec.format(sum/num));
}
}
Please note that I have slightly changed the way you were generating the random numbers which obviates the need to use Math.abs(). Also see the following answer to see how to generate random numbers between two different values:
Generating random numbers with Java
You do not need to store them in an array. Just declare int sum = 0 at the start and do sum += numb each time you generate a random number. Also, you are generating random numbers in a strange way. Take a look at the java.util.Random class.