Printing 0's in Random Numbers - java

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.

Related

How to Parse String.format added 0's to int

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);
}

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.

Putting in random order

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()

Divide Euro Amount

I have a problem in my code and i can't find the answer for it.
I only can use if and else and can't use other classes for an example Math.
The code save a value and try to divide in euro coins.
If i enter 4,31 the result is 2x2e + 1x20c + 1x1c and this is ok but if i enter the value 1,20 the result is 1e + 1x10c + 1x5c + 2x2c + 1x1c but the right result is 1e + 1x20c.
I had to add 0.001 in the 1cent coin because if i don't i'll not get a print for it. Adding this is wrong too.
If somebody could help me i would be very grateful.
Regards.
Code:
import java.util.Scanner;
public class Coins {
public static void main(String[] args){
Scanner in= new Scanner(System.in);
int e2 = 0, e1 = 0,c50 = 0, c20=0,c10 = 0,c5 = 0,c2 = 0,c1;
double v;
System.out.println("Quantia em euros: ");
v = in.nextDouble();
e2 = (int)v/2;
v=v-e2*2;
e1=(int)v;
v=(v-e1)*100;
c50=(int)v/50;
v=v-c50*50;
c20=(int)v/20;
v=v-c20*20;
c10=(int)v/10;
v=v-c10*10;
c5=(int)v/5;
v=v-c5*5;
c2=(int)v/2;
v=v-c2*2;
c1=(int)(v+0.001);
if(e2!=0)System.out.print(e2+"X2Eur ");
if(e2!=0&&!(e1==0&&c50==0&&c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(e1!=0)System.out.print(e1+"X1Eur ");
if(e1!=0&&!(c50==0&&c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c50!=0)System.out.print(c50+"X50c ");
if(c50!=0&&!(c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c20!=0)System.out.print(c20+"X20c ");
if(c20!=0&&!(c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c10!=0)System.out.print(c10+"X10c ");
if(c10!=0&&!((c5==0&&c2==0&&c1==0)))System.out.print("+ ");
if(c5!=0)System.out.print(c5+"X5c ");
if(c5!=0&&!(c2==0&&c1==0))System.out.print("+ ");
if(c2!=0)System.out.print(c2+"X2c ");
if(c2!=0&&!(c1==0))System.out.print("+ ");
if(c1!=0)System.out.print(c1+"X1c");
}
}
first of all: if you store a value in a double-variable, always consider that double is a bit imprecise, i'd use cents instead (simply remove the comma and parse to int).
for the implementation itself: optimize the whole thing using arrays.
final int[] coin_values = new int[]{
200 , 100 , 50 , 20 , 10 , 5 , 2 , 1};
final String[] coin_names = new String[]{
"2€" , "1€" , "50ct" , "20ct" , "10ct" , "5ct" , "2ct" , "1ct"};
String input = in.next();
String[] temp = input.split(".");
input = temp[0] + temp[1];
int value = Integer.parseInt(input);
int[] coins = new int[coin_values.length];
for(int i = 0 ; i < coins.length ; i++){
coins[i] = value / coin_values[i];
value %= coin_values[i];
if(coins[i] != 0)
System.out.print(coins[i] + " " + coin_names[i] + " + ");
}
These are rounding errors by Java, they can always occur when using floats. In your case you keep editting the same value so the error gets bigger and bigger.
Use
System.out.println("Quantia em euros: ");
v = 1.20;
int cents = (int)(v*100);
e2 = cents/200;
cents = cents%200;
e1=cents / 100;
cents = cents % 100;
c50=cents/50;
cents = cents%50;
c20=(int)cents/20;
cents = cents %20;
c10=(int)cents/10;
cents = cents%10;
c5=(int)cents/5;
cents = cents % 5;
c2=(int)cents/2;
c1=cents%2;
Because rounding errors don't occur on ints.
In Java always use java.math.BigDecimal for monetary amounts.
You won't get strange rounding behaviour that you can't control.

Having An Issue With Randomly Generated Numbers - Java

I am working on this project from the Java Programming book by Joyce Farrell, and I am having an issue with the Randomly Generated number and the user's guesses not being checked correctly. For example the user has 3 guesses, lets say their first guess it 2 and the first randomly generated number is 2 the program will print out You lose. When the guess is actually correct. Please help me. I have added the details of the program plus what I have done so far.
Create a lottery game application. Generate three random numbers (see Appendix D for help in
doing so), each between 0 and 9. Allow the user to guess three numbers. Compare each of the
user's guesses to the three random numbers and display a message that includes the user's
guess, the randomly determined three-digit number, and the amount of money the user has
won as follows.
Matching Numbers Award($)
Any one matching 10
Two matching 100
Three matching, not in order 1000
Three matching, in exact order 1,000,000
No match 0
Make certain that your application accommodates repeating digits. For example, if a user
guesses 1, 2, and 3, and the randomly generated digits are 1, 1, and 1, do not give the user
credit for three correct guesses - just one. Save the file as Lottery.
My Source Code
// Filename: Lottery.java
// Written by: Andy A
// Written on: 14 January 2015
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Random ranNum = new Random();
// LIMIT Contains The Numbers From 0 - 9
// TIMES Contains The Number of Time ranNum Should Run
final int LIMIT = 9;
final int TIMES = 3;
// Users Guesses
int usersFirstGuess;
int usersSecondGuess;
int usersThirdGuess;
// Randomly Generated Numbers
final int GenFirst = ranNum.nextInt(LIMIT);
final int GenSecond = ranNum.nextInt(LIMIT);
final int GenThird = ranNum.nextInt(LIMIT);
// User is asked for 3 guesses
System.out.println("Please enter your first guess: ");
usersFirstGuess = userInput.nextInt();
System.out.println("Please enter your second guess: ");
usersSecondGuess = userInput.nextInt();
System.out.println("Please enter your third and final guess: ");
usersThirdGuess = userInput.nextInt();
// Winning Amounts
final double WinTen = 10;
final double WinHun = 100;
final double WinThund = 1000;
final double WinMillion = 1000000;
final int WinZero = 0;
// Shows the randomly generated numbers
for(int x = 0; x < TIMES; ++x)
System.out.print(ranNum.nextInt(LIMIT) + " ");
System.out.println();
// First Generated
if(GenFirst == usersFirstGuess ) {
System.out.println("You have won: $" + WinTen);
}
else if(GenSecond == usersSecondGuess) {
System.out.println("You have won: $" + WinTen);
}
else if(GenThird == usersThirdGuess) {
System.out.println("You have won: $" + WinTen);
}
}
}
You are printing newly generated numbers with ranNum.nextInt(LIMIT), however you are comparing the user input with the numbers stored in the GenXXX variables.
Solution: Print the variables instead.
System.out.println(GenFirst + " " + GenSecond + " " + GenThird);
If you still want to use a loop for printing you can store the numbers in an array.
// generate
final int[] generated = new int[TIMES];
for (int x = 0; x < TIMES; x++)
generated[x] = ranNum.nextInt(LIMIT);
// print
for (int x = 0; x < TIMES; x++)
System.out.print(generated[x] + " ");
This should do the trick.
// Filename: Lottery.java
// Written by: Andy A
// Written on: 14 January 2015
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Random ranNum = new Random();
// LIMIT Contains The Numbers From 0 - 9
// TIMES Contains The Number of Time ranNum Should Run
final int LIMIT = 9;
final int TIMES = 3;
// Users Guesses
int usersFirstGuess;
int usersSecondGuess;
int usersThirdGuess;
List<Integer> guesses = new ArrayList<>();
// Randomly Generated Numbers
final int GenFirst = ranNum.nextInt(LIMIT);
final int GenSecond = ranNum.nextInt(LIMIT);
final int GenThird = ranNum.nextInt(LIMIT);
// User is asked for 3 guesses
System.out.println("Please enter your first guess: ");
usersFirstGuess = userInput.nextInt();
guesses.add(usersFirstGuess);
System.out.println("Please enter your second guess: ");
usersSecondGuess = userInput.nextInt();
guesses.add(usersSecondGuess);
System.out.println("Please enter your third and final guess: ");
usersThirdGuess = userInput.nextInt();
guesses.add(usersThirdGuess);
// Winning Amounts
final double WinTen = 10;
final double WinHun = 100;
final double WinThund = 1000;
final double WinMillion = 1000000;
final int WinZero = 0;
// Shows the randomly generated numbers
System.out.println(GenFirst + " " + GenSecond + " " + GenThird);
List<Integer> lottery = new ArrayList<>();
lottery.add(GenFirst);
lottery.add(GenSecond);
lottery.add(GenThird);
if (guesses.equals(lottery)) {
System.out.println("You have won: $" + WinMillion);
} else {
int matchCount = 0;
for (Integer guessValue : guesses) {
if (lottery.contains(guessValue)) {
matchCount++;
lottery.remove(guessValue);
}
}
switch (matchCount) {
case 0:
System.out.println("You have won: $" + WinZero);
break;
case 1:
System.out.println("You have won: $" + WinTen);
break;
case 2:
System.out.println("You have won: $" + WinHun);
break;
case 3:
System.out.println("You have won: $" + WinThund);
break;
}
}
}
}
Exactly,
why are you printing
System.out.print(ranNum.nextInt(LIMIT) + " ");
when you should be just printing
System.out.print(GenThird + " ");
System.out.print(GenSecond + " ");
System.out.print(GenFirst + " ");
This is not the problem of the randomly generated numbers, but if your way of showing them to the user.
Before your if / else if statements, in the for-loop you are generating new random numbers. That means, the number compared to the users input (genFirst) can be 3, but the number shown to the user in the for loop is a new random number, for example 2.
To fix this problem, you should display the generated numbers like that:
for (int ranInt : new int[] { GenFirst, GenSecond, GenThird}) {
System.out.println(ranInt);
}
This piece of code creates an array of the generated numbers and loops through them printing them. Obviously, you can also print GenFirst, then print GenSecond and then print GenThird.
I hope this helps!
Maybe this will help!
import java.util.Scanner;
import java.util.Random;
public class Qellonumrat {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Random rand=new Random();
int random_integer=(int) rand.nextInt(10);
System.out.println("Guess the number: ");
int number=sc.nextInt();
while(true){
if(number == random_integer){
random_integer++;
System.out.println("Congrats you won!!!");
break;
}
else{
System.out.println("Try again");
break;
}
}
}
}

Categories

Resources