java random numbers must be different [duplicate] - java

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 5 years ago.
I'm creating a small program that extracts 3 random numbers, the only condition is that all three numbers must be different from each other, for example: 3,9,3 is not acceptable.
This i my code, i tried it several times and occasionally appear numbers equal to each other.
What is wrong in my code ?
public class Premi {
public static void main(String[] args) {
int num = (int) (Math.random() *10) + 1;
int num2 = (int) (Math.random() *10) + 1;
int num3 = (int) (Math.random() *10) + 1;
boolean first = true;
boolean second = true;
boolean third = true;
while(first) {
if (num!=num2) {
first=false;
} else if (num==num2) {
num = (int) (Math.random() *10) + 1;
}
}
while(second) {
if (num!=num3) {
second=false;
} else if (num==num3) {
num = (int) (Math.random() *10) + 1;
}
}
while(third) {
if (num2!=num3) {
third=false;
} else if (num2==num3) {
num2 = (int) (Math.random() *10) + 1;
}
}
System.out.println(num + "," + num2 + "," + num3);
}
}
Thank you.

Set<Integer> numbers = new HashSet<>();
while (numbers.size() < 3)
numbers.add(((int) (Math.random() *10) + 1));
Using Set here will guarantee that the numbers are not repeating.
And if you're not allowed to use any collections or arrays (I'll reserve my opinion of courses that forbid students to use valid techniques) you can use:
int n1 = (int) (Math.random() * 10) + 1;
int n2;
do {
n2 = (int) (Math.random() * 10) + 1;
} while (n2 == n1);
int n3;
do {
n3 = (int) (Math.random() * 10) + 1;
} while (n3 == n2 || n3 == n1);
The do loop is guaranteed to run at least once.

Related

How can I make it so the random number is changed every time it prints?

Write the code to ask the user for a positive integer n, then print 10 random integers from 1 to n inclusive using Math.random().
How do I make it so that the output is different every time? As of now every output following the first one is exactly the same.
/* Lesson 8 Coding Activity Question 1 */
import java.util.Scanner;
import edhesive.testing.Math;
public class U2_L8_Activity_One{
public static void main(String[] args){
/* Write your code here */
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer.");
int n = scan.nextInt();
double ran = Math.random();
int range = n;
int min = 1;
int answer = (int) (ran * range) + min;
System.out.println("Printing 10 random integers from 1 to n...");
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
System.out.println(answer);
}
}
You properly generate a random number, but then just print it out ten times. If you want ten different numbers, you need to regenerate the number each time. E.g.:
for (int i = 0; i < 10; ++i) {
double ran = Math.random();
int answer = (int) (ran * range) + min;
System.out.println(answer);
}
You need to call the Math.random() method every time you want a random number. You are calling it once and assigning the result to a variable. Calling a System.out.println to print the variable will not change the result, because there is no reassignment of the variable you're printing.
Go with
System.out.println("The random number is " + Math.random());
This should work:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer.");
int max = scan.nextInt();
int min = 1;
for (int i = 0; i < 10; ++i) {
int ran = (int) (Math.random() * (max - min)) + min;
System.out.println(ran);
}
}
This Will work when exciuted, and its done in a simple manner such as what you provided
import java.util.Scanner;
import edhesive.testing.Math;
public class U2_L8_Activity_One{
public static void main(String[] args){
System.out.println("Please enter a integer");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
double ran = Math.random();
int min = 1;
int answer = (int) (Math.random() * n) + min;
int answer1 = (int) (Math.random() * n) + min;
int answer2 = (int) (Math.random() * n) + min;
int answer3 = (int) (Math.random() * n) + min;
int answer4 = (int) (Math.random() * n) + min;
int answer5 = (int) (Math.random() * n) + min;
int answer6 = (int) (Math.random() * n) + min;
int answer7 = (int) (Math.random() * n) + min;
int answer8 = (int) (Math.random() * n) + min;
int answer9 = (int) (Math.random() * n) + min;
System.out.println(answer);
System.out.println(answer1);
System.out.println(answer2);
System.out.println(answer3);
System.out.println(answer4);
System.out.println(answer5);
System.out.println(answer6);
System.out.println(answer7);
System.out.println(answer8);
System.out.println(answer9);
}
}

I need to make this java code repeat based on the user input and I cannot make it repeat using the code that I do have so far

I need to make this java code repeat based on the user input, and I cannot make it repeat using the code that I do have so far. I am not supposed to use any other imports besides the scanner and use class main. This is because we are using the https://repl.it/languages/java10 as our compiler because we are an elementary class. When I run the code, it is supposed to ask ten random addition and subtraction and should ask if the user wants to continue or not. When entering 1 for continue, it should ask another ten questions. however, upon running this code, it stops after the first question.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int n = 0;
int H = 0;
boolean p = true;
while (p){
int R1 = (int)(Math.random() * 50 + 1);
int R2 = (int)(Math.random() * 999 + 1);
int R3 = (int)(Math.random() * 999 + 1);
if(R1>25){
System.out.println( "" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3))
System.out.println("Correct");
else
System.out.println("Incorrect");
}
if(R1<25){
System.out.println( "" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3))
System.out.println("Correct");
else
System.out.println("Incorrect");}
N--;
if (N==0)
p = false;
continue;
}System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H==1)
p=true;
else
p=false;
while (N>0);
}
}
That's why you put the question System.out.println("Do you want ot continue? Put 1 for yes, 2 for no."); out of the while.
I recommend use do while instead of while. So you just need to put the question inside of loop do while.
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int H = 0;
boolean p = true;
do{
int R1 = (int) (Math.random() * 50 + 1);
int R2 = (int) (Math.random() * 999 + 1);
int R3 = (int) (Math.random() * 999 + 1);
if (R1 > 25) {
System.out.println("" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
if (R1 < 25) {
System.out.println("" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
N--;
System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H == 1) {
p = true;
} else {
p = false;
}
if (N == 0) {
p = false;
System.out.println("You have reached your max attempts.")
}
}while (N > 0 && p);

Error: reached end of file while parsing

I am getting this error:
Error: reached end of file while parsing
I know it means I need to close the curly bracket somewhere, but I have tried everything. I figured line 45 is the brace that needs to be closed, but I'm not sure how. This is a program for helping find the smallest number of coins needed to make the integer inputted by the user. For example, 37 would yield 2 Quarters, 1 Dime, and 2 pennies.
import java.util.Scanner;
public class Change {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
Int n = sc.nextInt("Enter a positive integer" );
int number1, number2; // Division operands
int quotient; // Result of division
{if (QtrCnt > 0)
if (QtrCnt > 1)
System.out.println(QtrCnt + " quarters");
else
System.out.println(QtrCnt + " quarter");
}
if (DimeCnt > 0)
{
if (DimeCnt > 1)
System.out.println(DimeCnt + " dimes");
else
System.out.println(DimeCnt + " dime");
}
if (NicklCnt > 0)
{
if (NicklCnt > 1)
System.out.println(NicklCnt + " nickles");
else
System.out.println(NicklCnt + " nickle");
}
if (PennyCnt > 0);
{
if (PennyCnt > 1);
System.out.println(PennyCnt + " pennies");
System.out.println(PennyCnt + " penny");
}
int q = 25;
int d = 10;
int n = 5;
int p = 1;
if (a < 0);
System.out.println("ERROR");
{
String (money >=25); { int numQuarters = money/ 25; }
money -= numQuarters * 25;
QtrCnt = (num1 - num1 % 25) / 25;
num1 = num1 - QtrCnt * 25;
String(money >=10); { int numDimes = money/ 10; }
money -= numDimes * 10;
DimeCnt = (num1 - num1 % 10) / 10;
num1 = num1 - DimeCnt * 10;
String (money >=5); { int numNickles = money/ 5; }
money -= numNickles * 5;
NicklCnt = (num1 - num1 % 5) / 5;
num1 = num1 - NicklCnt * 5;
String (money >=1); { int numPennies = money/ 1; }
money -= numPennies * 1;
PennyCnt = (num1 - num1 % 1) / 1;
num1 = num1 - PennyCnt * 1;
}
}
Yes, you are in fact missing the closing bracket for the class.
You also have a lot of brackets that basically don't do anything. Remember that if you don't put a { immediately after the () of an if, it won't belong to the if statement.
I cleaned up your code a little and got this:
import java.util.Scanner;
public class Change
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
Int n = sc.nextInt("Enter a positive integer" );
int number1, number2; // Division operands
int quotient; // Result of division
{ // <- Won't do anything
if (QtrCnt > 0)
if (QtrCnt > 1)
System.out.println(QtrCnt + " quarters");
else
System.out.println(QtrCnt + " quarter");
}
if (DimeCnt > 0)
{
if (DimeCnt > 1)
System.out.println(DimeCnt + " dimes");
else
System.out.println(DimeCnt + " dime");
}
if (NicklCnt > 0)
{
if (NicklCnt > 1)
System.out.println(NicklCnt + " nickles");
else
System.out.println(NicklCnt + " nickle");
}
if (PennyCnt > 0);
{
if (PennyCnt > 1);
System.out.println(PennyCnt + " pennies");
System.out.println(PennyCnt + " penny");
}
int q = 25;
int d = 10;
int n = 5;
int p = 1;
if (a < 0);
System.out.println("ERROR");
{ // <- Won't do anything
String (money >=25); { int numQuarters = money/ 25; }
money -= numQuarters * 25;
QtrCnt = (num1 - num1 % 25) / 25;
num1 = num1 - QtrCnt * 25;
String(money >=10); { int numDimes = money/ 10; }
money -= numDimes * 10;
DimeCnt = (num1 - num1 % 10) / 10;
num1 = num1 - DimeCnt * 10;
String (money >=5); { int numNickles = money/ 5; }
money -= numNickles * 5;
NicklCnt = (num1 - num1 % 5) / 5;
num1 = num1 - NicklCnt * 5;
String (money >=1); { int numPennies = money/ 1; }
money -= numPennies * 1;
PennyCnt = (num1 - num1 % 1) / 1;
num1 = num1 - PennyCnt * 1;
}
}
// <- This is where you're missing the class bracket
Please try to improve the way you're formating your code because it really helps finding these kinds of mistakes very quickly.
Keep in mind that I only reformated the code, I did not change what it does or check if it even works.

Generating two random prime numbers in JAVA

I'm trying to generate two random prime numbers in JAVA, however, I want the loop to keep repeating itself until both of those two variables are prime numbers, and then they output themselves.
The p and q variables are randomized by the Math.random() function and are in the range of 2 to 128 (excluding the 128).
Here is my code:
int pRandom = (int) (Math.random() * (127 - 2) + 2);
int qRandom = (int) (Math.random() * (127 - 2) + 2);
int p = pRandom;
int q = qRandom;
for (int i = 1; i < p; i++) {
boolean isPPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPPrime = false;
break;
}
}
if (isPPrime){
JOptionPane.showMessageDialog(null, "YAY!");
break;
}
System.out.println("P value: " + p + "\n" + "Q value: " + q);
}
Here is what you want:
public class RandomPrimeGenerator {
public static void main(String[] args) {
while (true) {
int pRandom = (int) (Math.random() * (127 - 2) + 2);
if(isPrime(pRandom)){
System.out.println("Got Random Prime P :"+pRandom);
break;
}
}
while(true){
int qRandom = (int) (Math.random() * (127 - 2) + 2);
if(isPrime(qRandom)){
System.out.println("Got Random Prime Q :"+qRandom);
break;
}
}
}
private static boolean isPrime(int n) {
int i;
for(i=2;i<=Math.sqrt(n);i++){
if(n % i == 0){
return false;
}
}
return true;
}
}

Why do I get a "Selection does not contain a main type" message in Eclipse?

import java.util.Scanner;
public class data {
public static int setoriginal() { //prompt user to input 4 digit number
int n = 0;
int l = 0;
do {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a 4 digit number: ");
n = input.nextInt();
if (n >= 1000 && n <= 9999) {
break;
} else {
System.err.
printf("You did not enter 4 digits\n");
}
l = l + 1;
}
while (l < 3);
return n;
} //end method
public static int encrypt(int n) { //encrypt number inputted by user
int e1 = (((n / 1000) + 7) / 10);
int e2 = ((((n % 1000) / 100) + 7) / 10);
int e3 = ((((n % 100) / 10) + 7) / 10);
int e4 = ((((n % 10) / 1) + 7) / 10);
int e = e1 * 1000 + e2 * 100 + e3 * 10 + e4;
int firstPart = e % 100;
int lastPart = e / 100;
int result = firstPart * 100 + lastPart;
return result;
} //end method
public static int decrypt(int result) { //decrypt encrypted number
int d1 = (((result / 1000) - 7) * 10);
int d2 = ((((result % 1000) / 100) - 7) * 10);
int d3 = ((((result % 100) / 10) - 7) * 10);
int d4 = ((((result % 10) / 1) - 7) * 10);
int d = d1 * 1000 + d2 * 100 + d3 * 10 + d4;
int firstPart1 = d % 100;
int lastPart1 = d / 100;
int result1 = firstPart1 * 100 + lastPart1;
return result1;
} //end method
public static int decrypt1(int n) { //decrypted number inputted by user
int dd1 = (((n / 1000) - 7) * 10);
int dd2 = ((((n % 1000) / 100) - 7) * 10);
int dd3 = ((((n % 100) / 10) - 7) * 10);
int dd4 = ((((n % 10) / 1) - 7) * 10);
int dd = dd1 * 1000 + dd2 * 100 + dd3 * 10 + dd4;
int firstPart1 = dd % 100;
int lastPart1 = dd / 100;
int result1 = firstPart1 * 100 + lastPart1;
return result1;
} //end method
public static void display(int n, int result, int result1) { //output results
System.out.println("Originl number is: " + n);
System.out.println("\nEcrypted numebr is: " + result);
} //end method
public static void display1(int n, int result, int result1) { //output results
System.out.println("Originl number is: " + n);
System.out.println("\nDecrypted numebr is: " + result1);
} //end method
public static void getOriginal(int n) { //return original number
System.out.println("The original number is: \n" + n);
} //end method
public static void getEncrypt(int n, int result) { //return encrypted number
System.out.println("The encrypted number is: \n" + result);
} //end method
public static void main(String[]args, int result, int n, int result1) {
int m = 0;
Scanner input1 = new Scanner(System.in);
System.out.print("\nPlease choose from the following menu ");
System.out.print("\n1. Enter an original number");
System.out.print("\n2. Encrypt the number and print it");
System.out.print("\n3. Decrypt a number and print it");
System.out.print("\n4. Quit\n");
m = input1.nextInt();
while (m < 1 || m > 4) {
System.out.print("Error choose a number from 1-4");
m = input1.nextInt();
}
if (m == 1) {
setoriginal();
main(args, m, m, m);
}
else if (m == 2) {
if (setoriginal() == 0) {
System.out.
print
("Please enter an original number first");
main(args, m, m, m);
} else {
encrypt(n);
display(n, result, result1);
main(args, n, result, result1);
}
} else if (m == 3) {
if (encrypt(n) < 0) {
System.out.
print("Please encrypt your number first");
main(args, n, result, result1);
} else {
decrypt(n);
display1(n, result, result1);
main(args, n, result, result1);
}
} else if (m == 4) {
System.exit(0);
}
}
}
I get no compile errors in eclipse but I get an error stating "Selection does not contain a main type". Any ideas what could be wrong? Also if you see any other errors please could you let me know.
You should use:
public static void main(String[] args)
instead of:
public static void main(String[] args, int result, int n, int result1)
In order to run your program, java needs to be able to find a method with the following signature:
public static void main(String[])
Since it can't find one in your program, it has nowhere to begin execution and hence can't compile it.
To get the affect you want, change the signature of the main method to that above, and access the arguments in terms of their indices of the String[], like so:
result = Integer.parseInt( args[0] );
n = Integer.parseInt( args[1] );
result1 = Integer.parseInt( args[2] );
If you add that to the start of your main method you should be fine. :D
public static void main(String[]args, int result, int n, int result1) {
One thing you're going to have to learn doing Java programming is the incantation:
public static void main(String args[]) {
It is this exact (well, String[] args also works -- and the name doesn't matter) incantation that the JVM searches for when it looks for an entry point to run your program.
Update
If you want to get any parameters from your main() function they will be encoded as String objects in the args[] array. Simply index into them:
$ cat Echo.java ; javac Echo.java ; java Echo Hello Cruel World
import java.lang.System;
class Echo {
public static void main(String args[]) {
for(int i=0; i<args.length; i++) {
System.out.println(args[i]);
}
}
}
Hello
Cruel
World
$
Of course, they are String objects. If you need to convert them into other object classes, you'll have to parse the strings correctly. (Integer() and similar things can come in handy for simple cases.)

Categories