This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Guess a number program with Java
(6 answers)
Closed 2 years ago.
I'm new to programming and while working on the Head First Java book I wanted to make a simple program, but there are some points I can't do. What I want the program to do is keep an integer number between 0 and 100 randomly and the user tries to find it. If the user finds the number, congratulations will appear on the screen. If not, it will ask for a new prediction. The code I wrote is below:
package Intro;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number: ");
int prediction = input.nextInt();
int number = (int) (Math.random());
if (number==prediction) {
System.out.println("Congratulations!");
}
else {
System.out.println("Wrong answer! Try a new number: ");
}
}
}
The point I stuck is that I can't make the randomly stored number integer and a number between 0 and 100. Another point is that if the answer is wrong, the program does not want a new prediction.
Very simple read this documentation on Random:
https://www.geeksforgeeks.org/java-math-random-method-examples/
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
int rand = (int)(Math.random() * range) + min;
// Output is different everytime this code is executed
System.out.println(rand);
}
Output:
6
8
10
10
5
3
6
10
4
2
Related
This question already has answers here:
frequency of each element in array
(5 answers)
find the frequency of elements in a java array
(11 answers)
Finding frequency of each element in an array [closed]
(4 answers)
i want to find the frequency of all elemnts in a java array? [duplicate]
(3 answers)
Closed 3 months ago.
To explain about the program that I am making, it is program that asks the user how many times he would like his coin to flip. In this program, the coin of the head is even, and the odd is the tail.
I created a script that randomizes numbers from 1 to 10 based on the number you entered. And also I've made the script that how many odd and even numbers had come out, but I don't know how to make a script that shows how many times do each of the 10 random numbers occur and which number occurred most often.
Here is the script that I have made:
import java.util.*;
public class GreatCoinFlipping {
public static void main(String[] args) {
System.out.println("How many times do you want to flip the coin? : ");
Scanner sc = new Scanner(System.in);
int amount = sc.nextInt();
int[] arrNum = new int[amount];
int even = 0, odd = 0;
for (int i = 0; i < amount ; i++) {
arrNum[i] = (int)(Math.random() * 10 + 1);
System.out.println(arrNum[i]);
if (arrNum[i] % 2 == 0) even++;
else odd++;
}//end for
System.out.println("Head: " + even + ", Tail: " + odd);
}//end main
}//end class
What I am expecting on this script that that I want to make the script that shows how many times do each of the 10 random numbers occur and which number occurred most often and I want to make it by the count method. But the ramdon number part has to be in array method. Can someone please help me with this problem?
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 months ago.
So I'm trying to figure out how to print out a random number between 1 to 1000.
I tried:
double a = 1+ (Math.random()*1000);
System.out.println(a);
But when I try this i get numbers with a bunch of decimals. I do not want any decimals. Anyone can help? I want to get a value like 50 or 289 or 294. I do not want to get a number like 234.5670242
or 394.220345. Help if you can. will appreciate it. Thank you.
Try this:
public static void main(String args[])
{
// define the range
int max = 1000;
int min = 1;
int range = max - min + 1;
// generate random numbers within 1 to 1000
for (int i = 0; i < 1000; i++) {
int rand = (int)(Math.random() * range) + min;
// Output
System.out.println(rand);
}
}
I am making a program that accepts user input to subtract all the numbers desired by the user
I first made the program ask how many numbers the user wants to subtract, and initialized the value in int inputNum, which is then passed on to the for loop for (int Count=1; Count<=inputNum; Count++), so that the program loops for user input, based on the inputNum.
Unfortunately, the output is wrong. I can't understand how this would work properly.
I've tried switching the operator in difference by making difference =- toBeSubtracted; into difference -= toBeSubtracted;
For difference =- toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -5
For difference -= toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -15
Here is the code:
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
int toBeSubtracted = scan.nextInt();
difference =- toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
Ok this might help you out:
difference = 0
and than you have:
difference -= toBesubtracted
so what you are doing is:
difference = difference - toBeSubtracted
which in terms is
difference = 0 - 10
difference = -10 - 5
thus you get -15
and where you have
difference =- toBeSubtracted
it is the same as
difference = -1 * toBeSubtracted
thus you get -5
I suppose you want output of 5. Here is your code with one change
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = scan.nextInt(); // so read in the first number here.
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1;Count<inputNum; Count++) // go till from 1 to inputNum - 1 because you have already got one number above
{
int toBeSubtracted = scan.nextInt();
difference -= toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
You need to understand the operator shorthand notation. You should write -= for minus shorthand. The shorthand is equal to difference =difference - tobesubstracted. Since your initial value is 0 it becomes 0-10-5= -15.
Assign the first value as difference and then do the substraction of next values.
So something like:
difference = scanner.nextInt();
And then do the loop for rest of the values to minus from initial value.
The problem isn’t that your program is working incorrectly.
The problem is that the requirements are nonsense. You can have the difference between two numbers. The difference between 19 and 8 is 11. There is no such thing as the difference between 3 or more numbers. Therefore no program could ever produce that.
That said, Davis Herring is correct in the comment: there is no =- operator. You tried to use one in the line:
difference =- toBeSubtracted;
But the line is understood as just:
difference = -toBeSubtracted;
So your program just outputs the negative of the last entered number. I tried entering three numbers, 11, 3 and 5. The first time through the loop difference is set to -11. Next time this value is overwritten and -3 is set instead. In the final iteration the difference is set to -5, which “wins” and is output.
Instead I suggest that your program should always subtract 2 numbers, as you are also trying in your example. So the user needs not enter the number of numbers, but is just told to enter the two numbers. Then you also don’t need any loop. Just read the first number, read the second number, subtract the second from the first (or the first from the second, or the smaller from the larger, what you want) and print the result. I am leaving the coding to you to avoid spoiling it.
I did this
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
int currentNumber = 0; //current number from scanner
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
if(Count == 1)
{
//nothing to subtract if count is 1
currentNumber = scan.nextInt();
difference = currentNumber;
}
else {
currentNumber = scan.nextInt();
difference = difference - currentNumber;
}
}
System.out.println("The difference of those numbers is " + difference);
}
}
You started your difference at 0. So if you subtracted two numbers, 15 and 3, then you would get 0 - 15 - 3 = -18. I set the difference equal to the first number, 15 in the first loop. Then it should work correctly because you do 15 - 3 = 12.
This question already has answers here:
print factorial calculation process in java
(3 answers)
Java factorial format
(2 answers)
How do I calculate factorial and show working?
(2 answers)
Closed 4 years ago.
I couldn't find a proper title.
I wrote a tiny program to calculate the factorial of a given integer. The program works fine as expected. Now I would like to also print its representation, say we have 4 as input, the program would output 24 and then print Because 4! = 4 x 3 x 2 x 1.
public class Test {
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
int i;
int fact;
int number= sc.nextInt();//Get user input and calculate its factorial
fact = factorial(number);
System.out.println("Factorial of " + number + " is " + fact);
System.out.println("Because " + number+"!" + " = " + number + "x" + (number - 1) ); // This is what I tried so far
}
}
The last println shows what I have tried. However, I'm only able to output 4! = 4 x 3, unable to go down to 1.
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I am kind of new in Java, and I got assigned some exercises. Any idea how to this small problem?
create an array consisting of 100 random integers in the range 100 to 500, including the end points.
make a method to print the array, 5 numbers per line, with a space between each.
make a method to print the smallest number in the array.
So far this is what i got for the first 2 parts but i doesn't seem work, help please, sorry for asking such dumb questions...
package randomhundred;
import java.text.DecimalFormat;
public class RandomHundred {
public static void main(String[] args) {
//setting the 100 array
int rand [] = new int [100];
double numb;
DecimalFormat dec = new DecimalFormat("0");
for(int i=0; i<rand.length; i++){
numb = Math.random() * ( 500 - 100 );
}
}
public static int arai (){
return System.out.print(" " + dec.format(numb) + " ");
}
}
Let's get step 1 right.... generating 100 random values.
Your process is nearly there.... but:
it does not generate an int value so you can't store it in an int[] array.
it will never generate the value 500.
To convert the random number to an integer, try the following:
int numb;
....
numb = (int)(Math.random() * ( 500 - 100 ));
but, this will not generate the value 500 (because 500 - 100 is 400, but, there's actually 401 numbers you need to generate....), so change it to (see How do I generate random integers within a specific range in Java?):
numb = 100 + (int)(Math.random() * ( (500 - 100) + 1))
Now we have random numbers between 100 and 500 (inclusive), you need to store them in your array now:
rand[i] = numb;
Once you have that working, come back and we can tackle the other problems.
until then, you can print out your array with:
System.out.println(Arrays.toString(rand)); // Arrays is java.util.Arrays
I'll try to supply some pseudo code for your problem:
// Task 1
Declare array of 100 ints (I will relate to 100 later on with n).
Fill array with random integers between 100 and 500 including borders
Hint code for this: 100 + new Random().nextInt(401), 401 as the upper bound is exclusive which makes the max result: 100 + 400 -> 500 and the minimum: 100 + 0 = 100. Even though this will generate the 100 numbers it will be faster if you store the random instance somewhere and re-use it, but that's an optimization step.
// Task 2
for i = 0; i < n; i++
print integer from array
add space
if i is divisible by 5 then
add new line
end-if
end-for
//Task 3
declare a min of the maximum value which is possible: in this case your maximum random number of 500
loop through the list checking for smaller numbers
after loop has finished print the last number
I hope this is clear enough for you get an idea on how this could be done.
Ad. 1
For the sake of completeness (it's been explained by others):
for(int i=0; i<rand.length; i++){
rand[i] = 100 + (int)(Math.random() * ( 401 ));
}
Ad. 2
This is wrong:
public static int arai (){
return System.out.print(" " + dec.format(numb) + " ");
}
Return type is int, but System.out.print() doesn't return anything, so change int to void and remove return keyword. Next, you'll need to iterate through the whole array:
public static void arai (){
for (int i=0; i< 100; i++) {
//this is modulo, which means that if i divided by 5 has no remainder, print next line
//eg. 5%2 = 1, because 2*2 + 1 = 5
//5%3 = 2 and so on, read here http://en.wikipedia.org/wiki/Modulo_operation
if (i%5 == 0) {
System.out.println();
}
//finally, print each value from rand array
System.out.print(rand[i] + " ");
}
}
Ad. 3
Try yourself, and comeback if you have issues, but follow Johnnei's advice of finding the smallest number.
NOTE: you also need to make the rand array declaration global, so that it's available to arai() method.