I am trying to prompts the user for two numbers where the first number
is a min value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user should be continually prompted until a number within the range is entered. However, I get an instance error when attempting to generate a random number between the max and min range.
import java.util.Scanner;
import java.util.Random;
public class MaxMin {
public static void main(String[] args) {
Random rand;
Scanner console = new Scanner(System.in);
System.out.print("Enter a min value: ");
int max = console.nextInt();
System.out.print("Enter a max value: ");
int min = console.nextInt();
System.out.print("Guess a number within the range inputted: ");
int guess = console.nextInt();
int randomNum = rand.nextInt((max - min) + 1) + min; // Error
if (guess == randomNum) {
System.out.print("Correct guess!");
}
else {
System.out.print("Guess a number within the range inputted: ");
}
}
}
Related
I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.
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);
}
}
//
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);
}
}
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
public class Exercise_442 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int count=0;
int positive=0;
int negative =0;
int nums=0;
int sum=0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Pleaes enter a positive or negative integer");
nums = keyboard.nextInt();
while(nums!=0){
sum+=nums;
System.out.println("Plese enter a positive or negative integer");
nums = keyboard.nextInt();
if(nums<0)
negative++;
if (nums>0)
positive++;
}
System.out.println("The sum of these numbers is " +sum);
System.out.println("The amount of negative numbers here is " + negative);
System.out.println("The amount of positive numbers here is " + positive);
}
}
I need to count the positive and negative numbers here when I enter them. It displays these when the user inputs 0. It counts the negative numbers ok and gets the sum but I don't know why it falls short of one number when it counts the positive integers?
Your first nums is ignored for +/- when you enter the while loop for the first time.
Let's say you enter 1 as nums. It'll add 1 to the sums and then ask for a new input without evaluating > or <.
Move your if statements above the nums = keyboard.nextInt(); in the while loop.
while(nums!=0){
sum+=nums;
//moved everything up before we pull nextInt
if(nums<0)
negative++;
if (nums>0)
positive++;
System.out.println("Plese enter a positive or negative integer");
nums = keyboard.nextInt();
}