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.
Related
I want to generate random national identification number and when i add 0's with String.format() to fill in digits, i can't parse it back into int
public class NinGenerator {
public static void Generator(sex name){ // sex is enum
Random rand = new Random();
int year = rand.nextInt(60) + 40; // For starting at year 40
int month, day, finalNumbers;
month = rand.nextInt(12) + 1;
if(name == sex.FEMALE){ // In case of female
month += 50;
}
switch(month){ // For max number of days to match given month
```
case 1:
case 3:
day = rand.nextInt(30) + 1;
```
}
finalNumbers = rand.nextInt(9999) + 1; // last set of numbers
String nin = FillZeroes(year, 2) + FillZeroes(month, 2) + FillZeroes(day, 2) + FillZeroes(finalNumbers, 4); // Merging it into string
// Here occurs error
int ninInt = Integer.parseInt(nin); // Parsing it into number
while(ninInt % 11 != 0){ // Whole number has to be divisble by 11 without remainder
ninInt++;
}
System.out.println("National identification number: " + ninInt);
}
public static String FillZeroes(int number, int digits){ // For number to correspond with number of digits - filling int with zeros
String text = String.valueOf(number);
if(text.length() < digits){
while(text.length() != digits){
text = String.format("%d1", number);
}
}
return text;
}
}
I want to generate 10 digit number divisible by 11 without reminder, compiler always generates error on the line with parsing
I tested out your code and I believe you are hitting the limit for how high an int can go. If you try placing "2147483647" as your nin value it will run, but as soon as you go to "2147483648" you will get the same error. If you want to fix this you might have to use a datatype such as a long or double depending on what you want to do with it.
Here is a link showing the different datatypes and their ranges.
Your FillZeroes() function could simply be:
public static String FillZeroes(int number, int digits)
{
String format = "d" + digits.ToString();
return number.ToString(format);
}
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.
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()
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 "=="
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.