Putting in random order - java

so for school i have to make a password generator in which we can set the amount of passwords as well as the amount of lower case letters, upper case letters, symbols and numbers. Here's the code:
package vantroys;
import java.util.Random;
public class PasswordGeneratorTest {
/**
* #param args
*/
public static void main(String args[]) {
int lowerCase;
int randomNum;
Random rand = new Random();
SimpleInOutDialog num = new SimpleInOutDialog("randomgenerator");
PasswordGeneratorClass test = new PasswordGeneratorClass();
test.setAmountPasswords(num.readInteger("How many passwords do you want to generate?"));
while (test.getAmountPasswords()>0){
test.setAmountLetters(num.readInteger("How many letters should this password contain?"));
test.setAmountUpperCase(num.readInteger("How many of these letters should be upper case?"));
if (test.getAmountUpperCase()>test.getAmountLetters()){
num.showString("", "This isn't possible, there aren't enough letters.");
num.stop();
}
test.setAmountNumbers(num.readInteger("How many numbers should the password contain?"));
test.setAmountSymbols(num.readInteger("How many symbols should the password contain?"));
lowercase= test.getAmountLetters()-test.getAmountUpperCase();
while (lowercase>0){
char a = (char) (rand.nextInt(26) + 'a');
lowercase=lowercase-1;
}
while (test.getAmountUpperCase()>0){
char b = (char) (rand.nextInt(26) + 'A');
test.setAmountUpperCase(test.getAmountUpperCase()-1);
}
while (test.getAmountNumbers()>0){
randomNum = rand.nextInt((10 - 1) + 1) + 1;
System.out.println(randomNum);
test.setAmountNumbers(test.getAmountNumbers()-1);
}
while (test.getAmountSymbols()>0){
char c = (char) (rand.nextInt(0xB4 - 21 + 1) + 21);
System.out.println(c);
test.setAmountSymbols(test.getAmountSymbols()-1);
}
test.setAmountPasswords(test.getAmountPasswords()-1);
}
}
everything works but now i'm supposed to put all of the letters, numbers and symbols i generated in a random order and i can't figure out how to do it, is there an easy way to do this that i'm just not seeing?

Put all chars in a list. Then use Collections.shuffle()

Related

How to randomise the characters '+' and '-' in java

I'm coding an arithmetic game where the user is asked a series of addition questions. I want to however randomly assign an operator for each question so that the question could be either:
Question 1: num1 + num2 =
or
Question 2: num1 - num2 =
I have been using the Math.random() method to randomise num1 and num2 the last thing I am struggling on is randomly generating '+' and '-'.
Is it something to do with the ASCII values of these two characters and then I can randomly pick between them? Thanks for the help!
As a side note, I want to ask the user to 'press enter' to start the game, but i'm not sure how to do it. Currently I've got the user to enter 'y' to start. Any ideas? Thanks so much.
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
heres my code so far:
public static void main(String[] args) {
//mental arithmetic game
System.out.println("You will be presented with 8 addition questions.");
System.out.println("After the first question, your answer to the previous question will be used\nas the first number in the next addition question.");
//set up input scanner
Scanner keyboard = new Scanner(System.in);
//declare constant variables
final int min_range = 1, max_range = 10, Max_Number_of_Questions = 8;
long start_time, end_time;
//generate 2 random numbers
int random_number1 = (int) ((Math.random() * max_range) + min_range);
int random_number2 = (int) ((Math.random() * max_range) + min_range);
//declare variables
int question_number = 1;
int guess;
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
//start timer
start_time = System.currentTimeMillis();
//ask the question
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
while (guess == (random_number1 + random_number2) && question_number < Max_Number_of_Questions) {
System.out.println("Correct");
++question_number;
//generate a new question
//generate 2 random numbers
random_number1 = guess;
random_number2 = (int) ((Math.random() * max_range) + min_range);
//ask the question again
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
}
end_time = System.currentTimeMillis();
int time_taken = (int) (end_time - start_time);
if (guess != (random_number1 + random_number2))
System.out.println("Wrong");
else {
System.out.println();
System.out.println("Well Done! You answered all questions successfully in " + (time_taken / 1000) + " seconds.");
}
}
}
You can use Random#nextInt to pick a random int from 0 to array.length - 1 which you can use as the index of an array of operators.
import java.util.Random;
public class Main {
public static void main(String[] args) {
char[] operators = { '+', '-', '*', '/' };
// Pick a random operator
Random random = new Random();
char op = operators[random.nextInt(operators.length)];
System.out.println(op);
}
}
A sample run:
/
I think for the random - and + characters you could use boolean like so:
Random rd = new Random(); // creating Random object
if(rd.nextBoolean()) {
//Do something
} else {
//Do Something else
}
For the enter, i think this is a game that is played in the console of the ide? Because then you can use a Scanner to track when enter is being pressed.
This will help you i think:
Java using scanner enter key pressed
The thing with the "Enter 'y' to start the game" is totally superfluous, as evidenced by the fact that you obviously don't have sensible things to do when the user does not enter 'y'.
So, since this is a command line application, why would anyone start it and then not want to play the game? Just go ahead and ask the first question! If the user did start that program by accident somehow, there will be no harm whatsoever, it's not that you're going to overwrite important files, start missiles or something like that.
You could try something like this.
Random r = new Random();
int[] signs = { 1, -1 };
char[] charSigns = { '+', '-' };
int a = r.nextInt(20);
int b = r.nextInt(20);
int sign = r.nextInt(2);
System.out.printf("%s %s %s = ?%n", a, charSigns[sign], b);
// then later.
System.out.printf("The answer is " + (a + signs[sign] * b));

Java random number with length, restrictions, characters and letters

Hi I'm new to Java and I'm trying to generate a random number 11-digit random number. How do you do this in this format "[xxx]-xxx#AxAxx" where the x is digits 0-9 and the A is any upper case letter. The brackets, dashes, and hash must be in the correct position too. Also the restriction is the last two digits can't be 5 or 6 and the first digit can't be 0. What's the best way to do this? Do you have to use a string and a random class? Thanks.
FWIW, you can do this with no looping for bad value rejection or hacks to add leading zeros:
import static java.lang.String.format;
import java.util.Random;
class Generator {
Random random = new Random();
private int not5or6() {
int val = random.nextInt(8);
return val < 5 ? val : val + 2;
}
String randomKey() {
StringBuilder s = new StringBuilder();
s.append('[');
s.append(random.nextInt(900) + 100);
s.append("]-");
s.append(format("%03d", random.nextInt(1000)));
s.append('#');
s.append((char) ('A' + random.nextInt(26)));
s.append(random.nextInt(10));
s.append((char) ('A' + random.nextInt(26)));
s.append(not5or6());
s.append(not5or6());
return s.toString();
}
// Or if you you don't like StringBuilder, here's another way...
String randomKey2() {
return format("[%d]-%03d#%c%d%c%d%d",
random.nextInt(900) + 100,
random.nextInt(1000),
(char) ('A' + random.nextInt(26)),
random.nextInt(10),
(char) ('A' + random.nextInt(26)),
not5or6(),
not5or6());
}
public static void main(String[] args) {
Generator g = new Generator();
for (int i = 0; i < 100; i++) System.out.println(g.randomKey());
}
}
Not sure if there is an "easy" way to do this.
You can just call "nextInt()" on a random number generator for each part you want to generate and then put all the pieces together, for example...
import java.util.Random;
public class Rnd {
private static Random rnd = new Random();
public static void main(String[] args) {
for(int k = 0; k < 1000; k++) {
System.out.println(Rnd.generate());
}
}
private static String generate() {
// Generate all of the random parts of the desired pattern...
// First part, 000-999
String num1 = generateNumbers(1000);
// Second part, 000-999
String num2 = generateNumbers(1000);
// Third part A...Z
char char1 = generateChar();
// Forth part, 0-9
String num3 = generateNumbers(10);
// Fifth part A...Z
char char2 = generateChar();
// Sixth part, 00-99
String num4 = "56";
// Make sure last two numbers are not a 5 or 6
while(num4.contains("5") || num4.contains("6")) {
num4 = generateNumbers(100);
}
return "[" + num1 + "]-" + num2 + "#" + char1 + num3 + char2 + num4;
}
private static char generateChar() {
// Generate a number between 0 and 25 inclusive then add 'A' to it
return (char) (rnd.nextInt(26) + 'A');
}
private static String generateNumbers(int i) {
// Generates a random int between 0 (inclusive) and i (exclusive)
// (where i should be a power of 10 that is > 1)
// Add i to the generated random number, turn it into a string and then strip first character
// This will ensure a number like 3 will come out as 003 for i = 1000
return ("" + (rnd.nextInt(i) + i)).substring(1);
}
}
This outputs something like...
[745]-770#M6U88
[481]-779#N0N82
[182]-777#S2P08
[401]-219#H6O78
[032]-181#O8E82
[579]-949#I0S02
[025]-810#K2P39
[523]-663#L0I89
[560]-084#N5W01
[915]-767#F2A97
[059]-324#R0D79
etc.

Converting parts of Strings to Character to be used in if/else statements

I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.

Why can't I get Integer input on java?

This is my equation generator and the output of the code is always 'incorrect'. I think it's because I can't get the integer input from the user. All I want is to fix this code. If anyone has any idea, please tell me.
THE CODE:
package equasionGen;
import java.util.Random;
import java.util.*;
public class EquationGen {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("This will Generate you an Equasion with numbers ranging between 1-1000");
Random random = new Random();
for(int idx = 1; idx <= 1; ++idx);
int randomInt = random.nextInt(10);
Random random1 = new Random();
for(int idx = 1; idx <= 1; ++idx);
int randomInt1 = random.nextInt(10);
System.out.print(randomInt + " + " + randomInt1 + " = ");
Scanner josh = new Scanner(System.in);
int input = josh.nextInt();
if (josh.equals(randomInt + randomInt1)){
System.out.println("CORRECT!!!");
} else if (!josh.equals (randomInt + randomInt1)){
System.out.println("INCORRECT!!");
}
}
}
The .equals() method is used to compare Strings. For comparing Integers, you should use the "==" comparison operator instead. Also, you are trying to compare the Scanner object "josh" to an Integer of (randomInt + randomInt1). Instead compare the Integer input, which you named "input" to (randomInt + randomInt1).
It should be:
if (input == (randomInt + randomInt1)) { ... }
else { ... }
If you want to compare two Integers to see if they are not the same, you can use the "!=" operator instead of the "=="

Printing 0's in Random Numbers

I originally had this program written with 3 variables, one for each set of numbers but,
I could not get java to print numbers like 0007 for the last four numbers. It would just print XXX-XXX-7 instead of XXX-XXX-0007. How can I get the random num generator to print additional 0's in numbers like 0748, 0023, 0005 for my phone numbers? Thank you!
import java.util.Random;
public class PhoneNumbers
{
public static void main (String[] args)
{
int digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8, digit9, digit10;
Random generator = new Random();
//creates a random number
digit1 = generator.nextInt(8);
digit2 = generator.nextInt(8);
digit3 = generator.nextInt(8);
digit4 = generator.nextInt(8);
digit5 = generator.nextInt(5);
digit6 = generator.nextInt(3);
digit7 = generator.nextInt(10);
digit8 = generator.nextInt(10);
digit9 = generator.nextInt(10);
digit10 = generator.nextInt(10);
//outputs the number including dashes
System.out.println("A random 10-digit phone number:");
System.out.print(digit1);
System.out.print(digit2);
System.out.print(digit3);
System.out.print("-");
System.out.print(digit4);
System.out.print(digit5);
System.out.print(digit6);
System.out.print("-");
System.out.print(digit7);
System.out.print(digit8);
System.out.print(digit9);
System.out.print(digit10);
}
}
You can create a string with the leading zeros:
int value = 7;
String valueStr = ("0000" + value);
valueStr = valueStr.substring(valueStr.length()-4);
Then just print the string.
You can also use a formatter:
int value = 7;
DecimalFormat myFormatter = new DecimalFormat("0000");
String output = myFormatter.format(value);
Then print the string
Random generator = new Random();
// creates a random number
int part1 = generator.nextInt(1000);
int part2 = generator.nextInt(1000);
int part3 = generator.nextInt(10000);
// outputs the number including dashes
System.out.println("A random 10-digit phone number:");
System.out.printf("%03d-%03d-%04d\n", part1, part2, part3);
Using printf gives you control over how the numbers are formatted. %d is a placeholder for each integer. 03 in %03d formats the number with a minimum of 3 digits, padding it with 0's as needed. See Format String Syntax for full details of how printf formatting works.

Categories

Resources