Java Input and Out put - java

Hi my code should do this instruction below but am not getting it at all
The user can enter as many positive floating-point numbers on the console as desired. Zero (or a
negative numbers) signals end of input (no more numbers can be entered). After input the program
displays
 the smallest number entered (min)
 the largest number entered (max)
 the mean of all numbers entered (mean)
Do NOT use arrays for this assignment, even if you know them.
Sample should look like this
enter numbers: \n
1 2 3 4 5 6 0 \n
numbers entered: 6 \n
minimum: 1.00 \n
maximum:6.00 \n
mean: 3.50\n
enter numbers: \n
0 \n
no number entered.
public class LoopStatistics {
public static void main(String[] args) {
double max, min, sum=0, input, mean=0;
int counter = 0;
TextIO.putln("enter numbers:");
do
{
input = TextIO.getDouble();
min = input;
max = input;
counter++;
if (input > max)
max = input;
if ( input < min)
min = input;
sum = sum + input;
} while( input != 0);
mean = sum / counter;
TextIO.putf("numbers entered:%d\n", counter);
TextIO.putf("minimum:%f\n", min);
TextIO.putf("maximum:%f\n", max);
TextIO.putf("mean:%f", mean);
}
}

You assign your max and min before you test whether they are greater/less than the current max/min:
min = input;
max = input;
This means that they both equal whatever the person entered last.
Tidying up your code and removing those calls yields:
public static void main(String[] args) throws Exception {
final Scanner scanner = new Scanner(System.in);
double max = 0;
double min = Double.POSITIVE_INFINITY;
double sum = 0;
int counter = 0;
while (true) {
final double d = scanner.nextDouble();
if (d <= 0) {
break;
}
sum += d;
max = Math.max(max, d);
min = Math.min(min, d);
++counter;
}
System.out.println("Max=" + max);
System.out.println("Min=" + min);
System.out.println("Ave=" + sum / counter);
}

Related

Java :Generate random numbers between minimum and a maximum values

This is the exercise I am stuck with :
Ask user for minimum, maximum (inclusive) and how many (count) random
numbers user wants to generate. Makes sure minimum is not larger than
maximum and count is not negative. Display error message if inputs are
invalid. If all is fine then generate the random numbers and print
them out, comma-separated on a single line.
I wrote the code in many ways. I can never get the for loop to print the Random numbers.
package randnumsmany;
import java.util.Scanner;
public class RandNumsMany {
public static double getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter minimum :");
int min = input.nextInt();
System.out.println("Enter maximum :");
int max = input.nextInt();
System.out.println("Enter number generated :");
int num = input.nextInt();
int[] rand = new int[num];
for (int i = 0; i == num - 1; i++) {
rand[i] = (int) getRandomNumber(min, max);
}
for (int i = 0; i == num - 1; i++) {
System.out.println(rand[i]);
}
System.out.println("How many generated: " + num);
}
}
You do not need an array for it. You can simply print all the numbers when they are calculated. Since you have to print them separated by a comma, you can print all but the last one followed by a comma and then print the last one without a comma.
Also, you can use an infinite loop to check the validity of inputs. If the inputs are valid, you can break the loop otherwise because of the loop, the inputs will be requested again.
Also, since the maximum needs to be inclusive, your formula to calculate the random number should be (int) (Math.random() * (max - min + 1) + min).
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min, max, num;
System.out.print("Enter minimum: ");
min = input.nextInt();
while (true) {
System.out.print("Enter maximum: ");
max = input.nextInt();
if (min > max) {
System.out.println("Minimum can not be larger than maximum");
} else {
break;
}
}
while (true) {
System.out.print("Enter number generated: ");
num = input.nextInt();
if (num < 0) {
System.out.println("The count can not be negative");
} else {
break;
}
}
// Print all but the last number followed by a comma
for (int i = 1; i <= num - 1; i++) {
System.out.print(getRandomNumber(min, max) + ", ");
}
// Print the last number without a comma
System.out.print(getRandomNumber(min, max));
}
public static int getRandomNumber(int min, int max) {
return (int) (Math.random() * (max - min + 1) + min);
}
}
A sample run:
Enter minimum: 10
Enter maximum: 20
Enter number generated: 20
19, 17, 13, 17, 16, 19, 12, 15, 20, 15, 17, 17, 19, 12, 13, 10, 16, 12, 14, 17
Another sample run:
Enter minimum: 10
Enter maximum: 5
Minimum can not be larger than maximum
Enter maximum: 20
Enter number generated: -10
The count can not be negative
Enter number generated: 5
18, 16, 11, 11, 13
// randomStream(n, min, max): e.g using stream, generate n number between min and max
// randomRandom(min, max) example of getting one random number between min and max
// randomMath(min, max): other way similar to randomRandom(min, max)
// randomThreadLocalRandom(): just for a random number without constrain
// It is effective way to use stream when many random number are needed.
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class Randomize {
public static void main(String args[]){
randomStream(2, 3, 10);
randomRandom(3, 10);
randomMath(3, 10);
}
// (generate random number between 0.0 and 1.0) * (max - min +(1 or 0)) + min
// length: how much number you want to generate
public static void randomStream( int length, int min, int max){
System.out.println("using random as Stream");
Random rand = new Random();
int[] random = rand.ints(length, min, max).toArray();
System.out.print("As integer: ");
for(int i : random)
System.out.print(i+"; ");
System.out.println("");
double[] randomD = ThreadLocalRandom.current().doubles(length, min, max).toArray();
System.out.print("As double: ");
for(double d : randomD)
System.out.print(d+"; ");
System.out.println("");
}
public static void randomRandom(int min, int max){
System.out.println("using Random");
Random rand = new Random();
int int_random = min + rand.nextInt(max-min);
System.out.println("As integer: "+ int_random);
double double_random = min + rand.nextDouble();
System.out.println("As double: "+double_random);
}
public static void randomMath(int min, int max){
System.out.println("using Math:");
int random_int = (int)(Math.random() * (max - min + 1) + min);
System.out.println("As integer: "+random_int);
double random_double = Math.random() * (max - min + 1) + min;
System.out.println("As double: "+ random_double);
}
public static void randomThreadLocalRandom(){
int int_random = ThreadLocalRandom.current().nextInt();
System.out.println("As Integers: " + int_random);
double double_rand = ThreadLocalRandom.current().nextDouble();
System.out.println("As Doubles: " + double_rand);
}
}
//

how to get the sum, average, minimum and maximum of five numbers-java using do-while loop

I'm trying to get the sum, average, minimum and maximum of five numbers but somehow I get this output. I'm trying to re-code it all over again but it is still the same. Can you help me check this guys...
Here's my code:
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double average;
int count = 0, sum = 0, num, min = 0, max = 0;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do {
num = scan.nextInt();
sum += num;
count++;
} while (count < 5);
average = sum / 5;
{
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
System.out.println("Your average is: " + average);
System.out.println("The sum is: " + sum);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Here's the output:
Please enter the number of numbers you wish to evaluate:
1
10
5
-3
6
Your average is3.0
The sum is:19
Your maximum number is 6
Your minimum number is 0
BUILD SUCCESSFUL (total time: 19 seconds)
The minimum and maximum numbers goes somewhere...
a little advice please...
The best way to handle the min/max values is to keep track of them as your read in each value:
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i=0; i < 5; ++i) {
num = scan.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
double average = sum / 5.0d;
I seed the max and min values with the smallest/largest integer values, respectively. This lets us capture the actual min and max values as they are read in. Also, I think that a basic for loop works better here than a do while loop.
Note that I compute the average using a double type, because it may not be a pure integer value (even in your sample data the average is not an integer).
Use
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
And your
{
if(num>max)
max=num;
if(num<min)
min=num;
}
needs to be inside the do-while loop, or else it runs only for the last value of number entered.
For a start you can use Math.min & Math.max. The average is sum / count.
An example getting a min number without a loop would be:
long min = Integer.MAX_VALUE;
min = Math.min(min, 9);
min = Math.min(min, 4);
min = Math.min(min, 6);
// min = 4
Do something similar for max.
You'd also be better off starting with a list or array of numbers. Get the output right, then add more complicated things like user input.
You can do it this way without defining number of integers to read:
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Next number?");
numbers.add(in.nextInt());
IntSummaryStatistics summaryStatistics = numbers.stream()
.mapToInt(Integer::valueOf)
.summaryStatistics();
System.out.println(String.format("Max: %d, Min: %d, Average: %s, Sum: %d", summaryStatistics.getMax(), summaryStatistics.getMin(), summaryStatistics.getAverage(), summaryStatistics.getSum()));
}
}
}
If I just change the existing code, the logic should be like below:
do{
num=scan.nextInt();
sum+=num;
if(count==0){
min=num;
max=num;}
if(num>max)
max=num;
if(num<min)
min=num;
count++;
}while(count<5);
average = sum/5;
The issue was that your min-max condition was outside the loop and you were initializing min and max by 0. You should set min/max to your first input number.
Min and Max were now equal to the max and min of integer. now if any number is less than min and greater than max, min and max takes their position. The average and the sum functionality was great. The problem in your code was that it was getting the max and min after the loop for input has executed. The flow was wrong.
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
double average;
int count=0, sum=0, num=0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do{
if(num>max) max=num;
if(num<min) min=num;
num=scan.nextInt();
sum+=num;
count++;
}while(count<5);
average = sum/5;
System.out.println("Your average is"+average);
System.out.println("The sum is:"+sum);
System.out.printf("Your maximum number is %d\n",max);
System.out.printf("Your minimum number is %d\n",min);
}
}

Count numbers in a "for loop" and give back average, min, max value in java

A user should input a number "x", and then the count of "x" numbers, e.g. input = 3, then 3 random numbers like 3, 5, 7.
Afterwards the program should give an output of the average, min and max value of this "x" numbers. So it has to read the numbers, but i don't know how it can be done.
It should be done without arrays and with a for loop.
I didn't find a possible solution here, but maybe I didn't do the right search.
So here is what i got so far:
import java.util.Scanner;
public class Statistic
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
int numbers;
double averageValue;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
number1 = input.nextInt();
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
for (int count = 0; count < number1; count ++) {
System.out.println(numbers); //Just for me to see which numbers are read by the programm
}
averageValue = numbers / number1;
// Output
System.out.println("\n Biggest number: " + Math.max(numbers));
System.out.println("\n Smallest number: " + Math.min(numbers));
System.out.print("\n Average value: " + averageValue);
}
}
But it only prints out and calculates with the first number of the "numbers"-input. Further I am not sure how to use the "Math.max" for a random count of numbers.
The problem is here:
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
numbers = input.nextInt();
nextInt() only saves one int. Every subsequent number you are entering gets lost, of course.
What you need to do is to move this statement inside the for loop for your idea to work.
Also, you can't use min and max here. min and max compare two numbers and return the greater of the two. For your purpose, you'd need to check inside the loop which the greatest and smallest number is and then output it accordingly.
You will need 6 variables: min = 0, max = 0, avg, sum = 0, count, num.
(avg variable is optional)
Program flow will be:
input how many numbers you want to enter -> store in variable count
use some loop to loop count number of times and in each iteration store
users value in variable num.
Increment sum by number user entered. sum += num;
check if entered number is less than current min. If true store min as that number.
Same as min do for max variable.
When loop exit you will have min, max, sum and count variables stored. To calculate avg devide sum with count and there you go. avg = sum / count.
First your code is logically in correct. when u have to take min and max values with average u need to store the inserted elements or process each input(for time complexity this would be the best approach).
Below I have modified your code where i m using enter code hereJava Collections List to store the inputs, sort them and get the data.
After sorting first will me min and last will be max.
Math.min and Math.max only works for comparing 2 numbers not an undefined list.
Again i would say the best solution would be if u check for the number is min or max at input time.
As you are new to java you can try that out your self.
import java.util.*;
public class ZahlenStatistik
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
List<Integer> numbers = new ArrayList<Integer>(); // change it to list
double averageValue;
int sum= 0;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Bitte geben Sie eine Zahl ein: ");
number1 = input.nextInt();
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
//Define the number of times loop goes
for (int count = 0; count < number1; count ++)
{
numbers.add(input.nextInt());
}
for(Integer number:numbers)
{
sum = sum + number;
}
averageValue = sum / number1;
Collections.sort(numbers);
// Output
System.out.println("\n Die größte Zahl ist: " + numbers.get(numbers.size()-1));
System.out.println("\n Die kleinste Zahl ist: " + numbers.get(0));
System.out.print("\n Der averageValue betr\u00e4gt: " + averageValue);
}
}
Some errors that I can see
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
You need here a loop and array to read and store all elements.
To get average value you need first to sum all elements in array and then to divide by length of array.
To find min and max values in array you cannot use Math.min() and Math.max() methods because these methods get two parameters and return min/max value.
Your code should be something like this
Notes
If you cannot use Java 8 you must replace Arrays.stream(numbers).max().getAsInt(); and Arrays.stream(numbers).min().getAsInt(); with helper methods which find max/min values in an array.
If you can use Java 8 you can calculate sum int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); instead in for loop.
.
public class Statistic {
public static void main(String[] args) {
// Variables
Scanner input = new Scanner(System.in);
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
int number1 = input.nextInt();
System.out.println(" Pls enter " + number1 + " numbers: ");
int[] numbers = new int[number1];
for (int i = 0; i < number1; i++) {
System.out.println("Enter next number");
numbers[i] = input.nextInt();
}
// Find min and max values
int max = Arrays.stream(numbers).max().getAsInt();
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("\n Biggest number: " + max);
System.out.println("\n Smallest number: " + min);
// Get average value
int sum = 0;
for (int num : numbers) {
sum = sum + num;
}
double averageValue = (double) sum / number1;
System.out.print("\n Average value: " + averageValue);
}
}
import java.util.Scanner;
public class SumOf2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 integer values");
int m = s.nextInt();
int n = s.nextInt();
int sum=0;
int count=0;
for(int i=m ; i<=n ; i++)
{
if(count < n)
{
sum=sum+i;
count++;
}
}
System.out.println("Sum of two numbers is: "+sum);
System.out.println("Count between 2 numbers is : "+count);
}
}

Sentinel Value Implementation

Problem:
Write a program with a loop that lets the user enter a series of non-negative integers. The user should enter -99 to signal the end of the series. Besides -99 as sentinel value, do not accept any negative integers as input (implement input validation). After all the numbers have been entered, the program should display the largest and smallest numbers entered.
Trouble: Having trouble with implementing the loop. The sentinel value works to get out of the loop, but it still retains that value as min and max. Can anyone help me please? I'm first time user and trying to learn Java.
Code:
import java.util.Scanner;
public class UserEntryLoop
{
public static void main (String [] args)
{
/// Declaration ///
int userEntry = 0, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
/// Shortcut that shows all of these are int.
/// Integer.Min_VALUE is the lowest possible number for an int
Scanner input = new Scanner(System.in);
// Read an initial data
System.out.print(
"Enter a positive int value (the program exits if the input is -99): ");
userEntry = input.nextInt();
// Keep reading data until the input is -99
while (userEntry != -99) {
// Read the next data
System.out.print(
"Enter a positive int value (the program exits if the input is -99): ");
userEntry= input.nextInt();
}
if (userEntry > max) //// if the max was < X it would print the initialized value.
max = userEntry; /// To fix this the max should be Integer.MAX_VALUE or MIN_VALUE for min
if (userEntry < min)
min = userEntry;
System.out.println("The max is : " + max);
System.out.println("The min is : " + min);
}
}
You should test in your loop (and I'd use Math.min and Math.max respectively, instead of a chain of ifs). Also, don't forget to check that the value isn't negative. Something like,
while (userEntry != -99) {
// Read the next data
System.out.print("Enter a positive int value (the program exits "
+ "if the input is -99): ");
userEntry= input.nextInt();
if (userEntry >= 0) {
min = Math.min(min, userEntry);
max = Math.max(max, userEntry);
}
}
Let's simplify the problem with an array and a single loop.
int[] test = { 1, 2 };
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int userEntry : test) {
min = Math.min(min, userEntry);
max = Math.max(max, userEntry);
}
System.out.println("The max is : " + max);
System.out.println("The min is : " + min);
and I get
The max is : 2
The min is : 1

Averaging grades math not displaying correctly

Can not for the life of me figure out why my average is not displaying correctly I've looked at it for like 2 hours.
import java.util.Scanner;
public class midterm
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int examScore =0;
int averageExamScore = 0;
int numStudent=0;
int sum=0;
while(examScore >= 0)
{
System.out.println("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
numStudent++;
sum = sum + examScore;
}
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
}
else
{
System.out.println("No scores to average");
}
}
}
The issue here is integer division.
averageExamScore = sum/numStudent;
All three of these arguments are integers, which means:
If you cast a part of your quotient to double, you'd lose precision (and fail compilation)
Example:
averageExamScore = (double)sum/numStudent; // wouldn't compile
The floor of the quotient sum/numStudent is provided instead of the whole number (so for a number like 4.9 you'd get 4).
You can fix this in a few ways:
Declare averageExamScore to be a double. This is required.
Either cast sum or numStudent to a double, or change their type to double.
You have defined averageExamScore as an integer, so integer arithmetic will be applied.
e.g.
5 / 2 == 2
1 / 2 == 0
Make averageExamScore into a double, and also cast your other integers to doubles.
Edit
To print out
do
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
System.out.println ("average score is " + averageExamScore );
}
Go through the following code,
public class MidTerm {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int examScore = 0;
double averageExamScore = 0;
int numStudent = 0;
int sum = 0;
while (true) {
System.out.print("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
if (examScore >= 0) {
numStudent++;
sum += examScore;
} else break;
}
if (numStudent > 0) {
averageExamScore = sum / numStudent;
System.out.println("Avarage score is : " + averageExamScore);
} else System.out.println("No scores to average");
}
}
averageExamScore variable should be a double otherwise it can not stored floating point values
Good Luck !!!

Categories

Resources