Java basic average number and random number - java

I was just practicing java programming by myself using random and averaging numbers but I was having a difficult time to do it. The program will ask "Enter # to be rolled between 0 to 100". Then I enter '3' then the output will be random 3 numbers.
My question is after 3 numbers come out, I want to find the average of those numbers. For example, I want my output to be
Your # is 89
Your # is 50
Your # is 12
Your avg is ##(//whatever the avg of numbers)
My output is like
Enter # to be rolled between 0 to 100
3
Your # is 89
your avg is 29
Your # is 39
your avg is 13
Your # is 76
your avg is 25
Can you guys help me to solve this problem? I know my codes are mess.
import java.util.Random;
import java.util.Scanner;
public class ranEx {
public static void main(String[] args) {
Random ranNumber = new Random();
Scanner input = new Scanner(System.in);
int number;
int ran;
System.out.println("Enter # to be rolled "
+ "between 0 to 100");
number = input.nextInt();
for(int i=0; i<number; i++) {
ran=ranNumber.nextInt(100);
System.out.println("Your # is " + ran);
int avg=ran/number;
System.out.println("your avg is " + avg);
}
}
}

You need to define avg outside of the loop and then add all your numbers to it. It's also better to call it sum and define it as double to prevent rounding, this way you can divide it by number after the loop and get the average.
double sum = 0;
for(int i=0; i<number; i++) {
// ...
sum += ran;
}
System.out.println("your avg is " + sum/number);

int sum=0;
for(int i=0; i<number; i++) {
ran=ranNumber.nextInt(100);
System.out.println("Your # is " + ran);
sum = sum+ran;
}
System.out.println("your avg is " + sum/number);

it's tested :
user must enter a number integer :
import java.util.Random;
import java.util.Scanner;
public class ranEx {
public static void main(String[] args) {
Random ranNumber = new Random();
Scanner input = new Scanner(System.in);
int number;
int ran = 0;
System.out.println("Enter A NUMBER to be rolled "
+ "between 0 to 100");
number = input.nextInt();
for(int i=0; i<number; i++) {
ran=ran+(ranNumber.nextInt(100));
System.out.println("Your # is " + ran);
int avg=ran/number;
System.out.println("your avg is " + avg);
}
}
}
output :
run:
Enter A NUMBER to be rolled between 0 to 100
5
Your # is 95
your avg is 19
Your # is 107
your avg is 21
Your # is 178
your avg is 35
Your # is 274
your avg is 54
Your # is 338
your avg is 67
BUILD SUCCESSFUL (total time: 2 seconds)

You want the compute the average only once, outside the loop, after the loop generates the values. You could accomplish your goal as follows:
Intialize an accumulator variable to zero before the loop
Inside the loop, add each generated value to the accumulator
After the loop, divide the accumulator value by the number of values

If you just want the average, define a variable that keeps the accumulate total, and then divide by the number of rolls.
// double for large values and decimal division later on
double total= 0;
int rolls = 4;
for ( int x = 0 ; x < rolls; x++ ) {
total += x;
}
// calculate average
double average = total / rolls;
// validate that it works, ( ( 0 + 1 + 2 + 3 ) / 4 ) == 1.5
Assert.assertEquals( 1.5d, average );

Related

Print only 10 outputs per line

I have a Printf formating question. I am to print only 10 numbers, before going to the next line and printing 10 more numbers and so on. with the end goal being like a table, with all the columns lining up and being aligned to the right. I am using a while statement as well. I have tried a few different things that I have found in my research, with no success. Would I use a different print statement for it other than Printf? Such as Print, or PrintLn? Also thought about using an If statement as well. Any help would be greatly appreciated! Thank you.
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
}
Using a MOD condition, You can ensure 10 output per line.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while (sqrt < n) {
sqrt = Math.pow(startNum, 2);
if(startNum != 0 && startNum % 10 == 0) {
System.out.println();
}
System.out.printf("%6.0f", sqrt);
startNum++;
}
}
}
Output -
Please enter a maximun integer value: 150
The number you entered was: 150
Squares less than 150 are: 0 1 4 9 16 25 36 49 64 81
121 144 169
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
if(startNum%10==0){
System.out.printf("/n");
}
}

how would I find the nth term in a loop? java

Here is a quick look at the program that I made to give a better example of my question.
Loop code
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
This is what my program outputs
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44
This work can be up to 4 days late before failing.
This is what the output is supposed to be
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44 (5) 39 (6) 34 (7) 29 (8) 24
This work can be up to 4 days late before failing.
I have to display how many days late the assignment is and calculate the late penaltie (mark -5) I also have to display the number of days needed needed to fail the assigment ( number of days until failure might be larger than the number (d) of days that the user input ) . the failing mark is less than 40.
2nd example (output)
Please input mark: 64
Please input number of days to display: 2
Scheme 1
(0) 64 (1) 59 (2) 54
This work can be up to 4 days late before failing.
I have almost complete my code but this problem is slowing me down.
P.S. I am new at java
here is my full program
LatePenalties calss
public class LatePenalties {
// attributes
private int mark;
private static final int constantDiffSch1 = -5;
private static final double constantDiffSch2 = 0.9;
private static final int START_CONDITION = 0;
// constructors
public LatePenalties(int m) {
mark = m;
}
// methods
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
public void scheme2(int d) {
double total = mark;
System.out.print("\n\nScheme 2"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print( "(" + loopParameter + ") " );
System.out.printf("%.02f",total);
System.out.print(" ");
total = total * constantDiffSch2;
} // End
System.out.print("\n");
}
}
Main class
import java.util.Scanner;
public class LatePenaltiesUser {
public static void main(String [] args) {
// local variables
Scanner input = new Scanner(System.in);
LatePenalties latePen;
int mark;
int days;
// input
do{
System.out.print("Please input mark (between 0 and 100) --> ");
mark = input.nextInt();
if (( mark < 0 ) | (mark > 100 )){System.out.print("\n" + "Input value outside the range!!!" + "\n");}
}while(( mark < 0 ) | (mark > 100 ));
do{
System.out.print("Please input number of days to display (between 0 and 20) --> ");
days = input.nextInt();
System.out.print("\n");
if (( days < 0 ) | (days > 20 )){System.out.print("Input value outside the range!!!"+ "\n");}
}while(( days < 0 ) | (days > 20 ));
// computation
latePen = new LatePenalties(mark);
latePen.scheme1(days);
latePen.scheme2(days);
}
}
I have to show when the faling mark occurs(at less than 40), but I have to stop the loop at 20 or when the number of days is reached, as I show in the example on what it is expected.
You can use break to come out of the loop as soon as total is less than 40. You can update your scheme1 method as below
public void scheme1(int d) {
int total = mark;
System.out.print("Scheme 1" + "\n");
int days = 0;
// Loop
for (int loopParameter = START_CONDITION; loopParameter <= d; loopParameter++) {
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
if(total < 40)
break;
days++;
} // End
if (total <= 40) {
System.out.print("\nThis work can be up to " + days +" days late before failing.");
}
System.out.print("\n\n");
}
Please input mark (between 0 and 100) --> 82
Please input number of days to display (between 0 and 20) --> 10
Scheme 1 (0) 82 (1) 77 (2) 72 (3) 67 (4) 62 (5) 57 (6) 52
(7) 47 (8) 42
This work can be up to 8 days late before failing.
You don't need to know your loopParameter to calculate the number of days. You can calculate it like so:
int days = (d - 40) / -constantDiffSch1;
You can use break when you want to quit loop. So:
if (total < 20) break;
And off topic. Don't call loopParameter like that. It is good practice to call it in one symbol (or short word) like i or day. It makes code easier to read and understand.

Totaling up from an array converted from a string to an integer(command line compiling)

I am compiling the code in command line with the following code typed in command line:
java aac 2 4 6 8 10
and I am getting the result:
5
The number in position 0 is 2.0
The Sum is: 2.0
The number in position 1 is 4.0
The Sum is: 4.0
The number in position 2 is 6.0
The Sum is: 6.0
The number in position 3 is 8.0
The Sum is: 8.0
The number in position 4 is 10.0
The Sum is: 10.0
What I am trying to achieve is, for the sum to be the total of all the numbers divided by the amount of numbers, however for the amount of numbers there is I have come up with a length variable. For this example the length is displayed as 5 right at the start.
public class aac {
public static void main(String args[]) {
// working out the length
int length = args.length;
System.out.println(length);
// this is a for loop that repeats until integer i is greater than
// integer length, which is the length of the args String array.
for (int i = 0; i < length; i++) {
// this string equals whatever value is in position i in string array args
String all = args[i];
// integer numConvert now equals the integer of String all
double numConvert = Double.parseDouble(all);
System.out.print("The number in position " + i + " is " + " ");
System.out.println(numConvert);
double sum = 0;
sum = sum += numConvert;
System.out.println("The Sum is: " + sum);
System.out.println();
}
}
}
Are you having problems creating the sum in order to calculate the average? If so, move the double sum = 0; out of your for loop. After the loop you divide it by args.length and that'll be your average.
Here's a little amelioration of your code :
double average = 0.0;
double sum = 0;
for(int i = 0; i < length; i++){
String all = args2[i];
double numConvert = Double.parseDouble(all);
System.out.print("The number in position "+i+" is ");
System.out.println(numConvert);
sum += numConvert;
average = sum / (i+1);
System.out.println("The Sum is: "+sum);
System.out.println("The average is :" + average);
System.out.println();
}
I created 2 double variables outside of your for loop.
Each time we loop in, the current value is added to the sum variable to get the total sum.
Also, the average is changed to the value of sum divided by the numbers we've already seen.
Here is the output :
5
The number in position 0 is 2.0
The Sum is: 2.0
The average is :2.0
The number in position 1 is 4.0
The Sum is: 6.0
The average is :3.0
The number in position 2 is 6.0
The Sum is: 12.0
The average is :4.0
The number in position 3 is 8.0
The Sum is: 20.0
The average is :5.0
The number in position 4 is 10.0
The Sum is: 30.0
The average is :6.0

java scanner data to multiple types

I've been spinning my wheels on a homework assignment for the last 3 hours and am not making very much progress. I was wondering if someone could help nudge me in the right direction.
The assignment is to read data from a file and convert it to something that is more reader friendly. The data file looks something like this:
0.30 0.30 0.40
161
3333 70 60 50
4444 50 50 50
5555 80 90 80
0
162
1212 90 85 92
6666 60 80 90
7777 90 90 90
8888 95 87 93
9999 75 77 73
0
263
2222 90 65 75
8989 60 40 60
9090 70 80 30
0
The file contains 5 different types of numbers.
1. The three digit numbers are course numbers.
2. The four digit numbers are student numbers.
The two digit numbers are scores for assignments, mid terms, and finals for each student.
The decimals across the top are used to find the weighted average for the scores.
zeros are a break between courses.
I am supposed to read all of the data in the file and then format and output it so it's easy to read:
Grade Data For Class 161
ID Programs Midterm Final Weighted Average Programs grade
-- -------- ------- ----- ---------------- --------------
3333 70 60 50 59.00 Pass
4444 50 50 50 50.00 Fail
5555 80 90 80 83.00 Pass
Class Average: 64.00
I have the scanner setup and am able to parse out the numbers from the text, my problem is that they are all saved as Strings so I can't do any mathematical checks on them. I'm starting to wonder if this is even the best way to go about this.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class classAverage
{
public static void main(String[] args) throws IOException
{
//in variable equals entire file
Scanner in = new Scanner(new File("courseData.txt"));
int classID;
System.out.println("ID Programs Midterm Final Weighted Average Programs Grade");
System.out.println("-- -------- ------- ----- ---------------- --------------");
while(in.hasNextLine()) //While file has new lines
{
//line equals each line of text
String line = in.nextLine();
Scanner lineParser = new Scanner(line);
System.out.println(line);
for(; lineParser.hasNext();)
{
//number = each number
String number = lineParser.next();
System.out.println(number);
if(number < 1 && number > 0)
{
double programsAverage = number.nextDouble();
double midtermAverage = number.nextDouble();
double finalAverage = number.nextDouble();
System.out.println(programsAverage);
System.out.println(midtermAverage);
System.out.println(finalAverage);
}
}
}
}
}
Update I've included my updated code. My problem now is my conditions in my for statements. These should be checking the values of the incoming Scanner data to see if the data is:
a weight calculator(0,1)
a score(1,100),
a classNumber (100,400),
a studentNumber(1000,9999),
a class separator (0).
I am thinking something like:
for(in.next(); in < 100 && in > 1; next());
This isn't quite doing it though.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
/**
* Write a description of class classAverage here.
*
* #author
* #version
*/
public class classAverage
{
public static void main(String[] args) throws IOException
{
//in variable equals entire file
Scanner in = new Scanner(new File("courseData.txt"));
int classNumber;
int studentNumber;
int programs;
int midterm;
int finals;
double programWeight = in.nextDouble();
double midtermWeight = in.nextDouble();
double finalWeight = in.nextDouble();
//System.out.println(programWeight + " " + midtermWeight + " " + finalWeight);
for(int k = 0; k < 3; k++)
{
for(int i = 0; i <= 0; i++)
{
classNumber = in.nextInt();
System.out.println("Grades for class: " + classNumber);
System.out.println(" ID Programs Midterm Final Weighted Average Programs Grade");
System.out.println(" -- -------- ------- ----- ---------------- --------------");
}
int studentCount = 0;
double sumAverage = 0.0;
for(int j = 0; j <= 2; j++)
{
studentNumber = in.nextInt();
programs = in.nextInt();
midterm = in.nextInt();
finals = in.nextInt();
studentCount++;
double weightedAverage = (programWeight * programs) + (midtermWeight * midterm) + (finalWeight * finals);
sumAverage += weightedAverage;
System.out.printf("%d %d %d %d %.2f ", studentNumber,programs,midterm,finals,weightedAverage);
if(programs >= 70)
{
System.out.print("PASS");
} else {
System.out.print("FAIL");
}
System.out.println();
}
double classAverage = sumAverage / studentCount;
System.out.printf("Class average is: %.2f", classAverage);
System.out.println("\n\n");
}
}
}
You have 2 options here :
Use Scanner#hasNextInt() and nextInt() instead of nextLine() to read Integers directly instead of numbers in String format.
Keep your reading / scanning code intact. Use Integer.parseInt() to convert String to Integers. --> Preferred solution. As it is more efficient.

How to Write a Summation of Fives in Java

I need to write a program in Java that can take the multiples of five up to a value given by the user, and then add all of the multiples together. I need to write it with a while loop.
Here's what I have so far:
import java.util.Scanner;
public class SummationOfFives {
public static void main(String[] args){
//variables
double limit;
int fives = 0;
//Scanner
System.out.println("Please input a positive integer as the end value: ");
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
limit = input.nextDouble();
//While Loop
while ((fives+5)<=limit)
{
fives = fives+5;
System.out.println("The summation is: "+fives);
}
}
}
When I run this program however, all it gives me is the multiples:
Please input a positive integer as the end value:
11
The summation is: 5
The summation is: 10
You're nearly there! Think about what your output is telling you. In your while loop, fives is the next multiple of 5 on each iteration. You're not adding it to a total variable anywhere.
So - define a total before the loop e.g.
int total = 0;
keep adding to it in the loop (where your System.out.println is now) e.g.
total = total + fives;
output the total after the loop e.g.
System.out.println(total);
I added a total variable into your loop that will accumulate the value of all of the summations.
int counter =1;
int total = 0;
//While Loop
while ((fives+5)<=limit)
{
total = counter*5;
counter++;
fives = fives+5;
System.out.println("The summation is: "+fives);
System.out.println("The total is: "+total);
}
The summation you do in fives is wrong. You need another variable multiple initialised to 0 that you will increment by 5 at each step of the loop. The stop condition in the while is (multiple < limit). Then fives are the sum of the multiples.
double limit;
int fives = 0;
int multiple = 0
//While Loop
while (multiple<=limit)
{
multiple += 5;
fives = fives + multiple;
System.out.println("So far, the summation is: "+fives);
}

Categories

Resources