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.
Related
I'm a beginner Java student faced with the following question: W"rite a program that inputs an integer that will be the number of times (n) that you will read a random number."
The program is then supposed to calculate the sum and product of those random numbers.
I understand how to generate a random number and I set up a For loop to generate the n random numbers per user input.
import java.util.Scanner;
import java.util.Random;
public class Example {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter a number:");
n = input.nextInt();
for (int i = 0; i < n; i++){
double randomNumber = Math.random();
System.out.println(randomNumber);
}
}
}
My first attempt had shoehorned
System.out.println(randomNumber * randomNumber);
System.out.println(randomNumber + randomNumber);
at the bottom of the code which did not work for reasons that are probably obvious to anyone else.
I'm stuck on the concept of storing n random numbers for long enough to do the required arithmetic on them.
You should be able to just maintain some state for the sum and product:
int n = input.nextInt();
double sum = 0d;
double product = 0d;
for (int i=0; i < n; i++) {
double randomNumber = Math.random();
sum += randomNumber;
product = i == 0 ? randomNumber : product*randomNumber;
}
System.out.println("sum = " + sum);
System.out.println("product = " + product);
The line:
product = i == 0 ? randomNumber : product*randomNumber;
is equivalent to:
if (i == 0) {
product = randomNumber;
}
else {
product = product*randomNumber;
}
The version I used is called a ternary expression, and is a concise way of writing if else logic. The idea here is that we want to initialize the product with the first random number. Otherwise, we just multiply the product with the latest random number.
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;
This question already has answers here:
Java program to find the largest & smallest number in n numbers without using arrays [closed]
(8 answers)
Closed 6 years ago.
I have a slight issue with my program. I need to ask the user to input as many numbers as they want and then the program will tell them what is the smallest and largest number. My issue is when all is said and done it prints out "the largest number is 0" and "the smallest number is 0". It always says that even if i never enter 0. I was wondering what was wrong with the program. Any pointers or helpers would be fantastic. Again to repeat, the issue im having is that the smallest and largest come back as 0's no matter what.
import java.util.Scanner;
public class LargestAndSmallest {
public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the numer");
int n = keyboard.nextInt();
num = keyboard.nextInt();
while (n != -99) {
System.out.println("Enter more numbers, or -99 to quit");
n = keyboard.nextInt();
}
for (int i = 2; i < n; i++) {
num = keyboard.nextInt();
if (num > large) {
large = num;
System.out.println(large);
}
if (num < smallest) {
smallest = num;
}
}
System.out.println("the largest is " + large);
System.out.println("the smallest is " + smallest);
}
}
I used this code as in the first place: Java program to find the largest & smallest number in n numbers without using arrays
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class LargestAndSmallest {
public static void main(String... args) {
final Scanner keyboard = new Scanner(System.in); //init the scanner
System.out.println("Enter a number");
final Set<Integer> ints = new HashSet<>(); //init a set to hold user input
int n; //declare a variable to hold each number
while ((n = keyboard.nextInt()) != -99) { //loop until 99 is entered
ints.add(n); //add user input to our set
System.out.println("Enter more numbers, or -99 to quit.");
}
//output aggregate info
System.out.println("the largest is " + Collections.max(ints));
System.out.println("the smallest is " + Collections.min(ints));
}
}