This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
i'm trying to read in two integer numbers from the console and then display a random integer number generated between these two numbers.
this is my code.
import java.awt.*;
import java.io.*;
import java.util.*;
import java.math.*;
public class Question8{
public static void main(String[] args)
{
int first, second;
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter first integer: ");
int numOne;
numOne = myScanner.nextInt();
System.out.println("You have keyed in " + numOne);
System.out.println("Enter second integer: ");
int numTwo;
numTwo = myScanner.nextInt();
System.out.println("You have keyed in " + numTwo);
Random generator = new Random();
//int num = generator.nextInt(numOne) + numTwo;
System.out.println("Random number: " + numOne + generator.nextInt(numTwo - numOne));
}
}
after i execute this program..
i do not get the random number that's between the 2 integers.
this is my output:
Enter first integer:
20
You have keyed in 20
Enter second integer:
30
You have keyed in 30
Random number: 204
hope you guys can help me in any way you can (:
Make sure that first is always the smaller value and use new Random().nextInt(second - first) + first;. first is in the range of possible generated numbers, second is exclusive.
A random generator (Method in java.lang.Math?) will generate a random double x, where 0 <= x <= 1. Just multiply x with the range and add any offset to the product.
Related
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 5 years ago.
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:
Generate a random number within a certain range (e.g. 5 through 20).
Take the number and store it within a variable.
Perform arithmetic on it.
Here's the code:
import java.util.HashMap;
public class Attack {
public static void main(String[] args) {
HashMap<String, Integer> attacks = new HashMap<String, Integer>();
attacks.put("Punch", 1);
attacks.put("Uppercut", 3);
attacks.put("Roundhouse Kick", 5);
int actionPoints = // Code for random number generation
System.out.println("A brigade integrant appeared!");
System.out.println("What do you do?");
System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
System.out.println("You have " + actionPoints + " Action Points.");
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = reader.nextInt();
reader.close();
if n == 1 {
System.out.println("The brigade integrant takes 2 HP of damage!");
}
else if n == 2 {
System.out.println("The brigade integrant takes 5 HP of damage!");
}
else if n == 3 {
System.out.println("The brigade integrant takes 8 HP of damage!");
}
}
}
In Java 1.7+ you can do it in one line (not counting the import statement ;):
import java.util.concurrent.ThreadLocalRandom;
int actionPoints = ThreadLocalRandom.current().nextInt(5, 21); // 5 to 20 inclusive
Try this :
int lower = 12;
int higher = 29;
int random = (int)(Math.random() * (higher-lower)) + lower;
There are multiple options for you to generate a random number. Two of these would be:
Math.random(); // Random values ranging from 0 to 1
Random rand; rand.nextInt(x); // Random int ranging from 0 to x
To specify the exact range you could do something like this:
int RandomNumber = Min + (int)(Math.random() * Max);
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));
}
}
package Review_Randomnum;
import java.util.Scanner;
public class RandomNum {
public static void main(String[] args) {
System.out.println("Please enter a minimum value: ");
Scanner input = new Scanner(System.in);
int first = input.nextInt();
System.out.println("Please enter a maximum value: ");
int second = input.nextInt();
int number = ((int)(Math.random()) * ((second - first)) + first);
System.out.println(number);
}
}
So I've checked numerous answers on this website, and to no avail, I don't get any errors, I just get the minimum value printed. I don't know how to get the program to produce a random integer between the two values input
Your random number is being truncated to 0 in the following expression:
((int)(Math.random())
The reason for this is that Math.random() returns a double greater than or equal to 0 and less than 1, which when cast to an int will be truncated to 0 (see the documentation for more information).
Instead, compute your desired number first as a double, and then cast back to an int:
int number = (int)(Math.random() *(second - first) + first);
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Find the max of 3 numbers in Java with different data types (Basic Java)
Write a program that uses a scanner to read three integers (positive) displays the biggest number of three. (Please complete without using either of the operators && or ||. These operators will be covered in class shortly. Similarly loops are not required.)
Some sample run:
Please input 3 integers: 5 8 3
The max of three is: 8
Please input 3 integers: 5 3 1
The max of three is 5
import java.lang.Math;
import java.util.Scanner;
public class max {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please input 3 integers: ");
String x = keyboard.nextLine();
String y = keyboard.nextLine();
String z = keyboard.nextLine();
int max = Math.max(x,y,z);
System.out.println(x + " " + y + " "+z);
System.out.println("The max of three is: " + max);
}
}
I want to know what's wrong with this code and how I can find the max when I input 3 different values.
Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.
In Summary, change below:
String x = keyboard.nextLine();
String y = keyboard.nextLine();
String z = keyboard.nextLine();
int max = Math.max(x,y,z);
to
int x = keyboard.nextInt();
int y = keyboard.nextInt();
int z = keyboard.nextInt();
int max = Math.max(Math.max(x,y),z);
You should know more about java.lang.Math.max:
java.lang.Math.max(arg1,arg2) only accepts 2 arguments but you are
writing 3 arguments in your code.
The 2 arguments should be double,int,long and float but your are
writing String arguments in Math.max function. You need to parse them in the required type.
You code will produce compile time error because of above mismatches.
Try following updated code, that will solve your purpose:
import java.lang.Math;
import java.util.Scanner;
public class max {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please input 3 integers: ");
int x = Integer.parseInt(keyboard.nextLine());
int y = Integer.parseInt(keyboard.nextLine());
int z = Integer.parseInt(keyboard.nextLine());
int max = Math.max(x,y);
if(max>y){ //suppose x is max then compare x with z to find max number
max = Math.max(x,z);
}
else{ //if y is max then compare y with z to find max number
max = Math.max(y,z);
}
System.out.println("The max of three is: " + max);
}
}
It would help if you provided the error you are seeing. Look at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html and you will see that max only returns the max between two numbers, so likely you code is not even compiling.
Solve all your compilation errors first.
Then your homework will consist of finding the max of three numbers by comparing the first two together, and comparing that max result with the third value. You should have enough to find your answer now.