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

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

Related

How to return the 3 middle characters of an odd string using the substring method?

I'm trying to return the middle 3 characters of a word using the substring method but how do I return the middle 3 letters of a word if the word can be any size (ODD only)?
My code looks like this.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputWord;
inputWord = scnr.next();
System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring(2,5));
}
}
The reason I have a 2 and 5 in the substring method is because I have tried it with the word "puzzled" and it returned the middle three letters as it was supposed to do. But if I try, for instance "xxxtoyxxx", It prints out "xto" instead of "toy".
P.S. Please don't bash me I'm new to coding :)
Consider the following code:
String str = originalString.substring(startingPoint, startingPoint + length)
To determine the startingPoint, we need to find the middle of the String and go back half the number of characters as the length we want to retrieve (in your case 3):
int startingPoint = (str.length() / 2) - (length / 2);
You could even build a helper method for this:
private String getMiddleString(String str, int length) {
if (str.length() <= length) {
return str;
}
final int startingPoint = (str.length() / 2) - (length / 2);
return "[" + str.substring(startingPoint, startingPoint + length) + "]";
}
Complete Example:
class Sample {
public static void main(String[] args) {
String text = "car";
System.out.println(getMiddleString(text, 3));
}
private static String getMiddleString(String str, int length) {
// Just return the entire string if the length is greater than or equal to the size of the String
if (str.length() <= length) {
return str;
}
// Determine the starting point of the text. We need first find the midpoint of the String and then go back
// x spaces (which is half of the length we want to get.
final int startingPoint = (str.length() / 2) - (length / 2);
return "[" + str.substring(startingPoint, startingPoint + length) + "]";
}
}
Here, I've put the output in [] brackets to reflect any spaces that may exist. The output of the above example is: [ppl]
Using this dynamic approach will allow you to run the same method on any length of String. For example, if our text String is "This is a much longer String..." our output would be: [ lo]
Considerations:
What if the input text has an even number of characters, but the length is odd? You would need to determine if you want to round the length up/down or return a slightly off-center set of characters.
I think what you can do is to calculate the string length then divided by 2. This gives you the string in the middle, then you can subtract one to the start and add 2 to the end. If you want to get the first two for an odd string, then subtract 2 to the start index and add 1 to the end.
String word_length = inputWord.length()/2;
System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring((word_length-1, word_length+2));
Hope this helps.
This will get the middle of the string, and return the characters at the middle, and +- 1 from the middle index.
public static String getMiddleThree(String str) {
int position, length;
if (str.length() % 2 == 0) {
position = str.length() / 2 - 1;
length = 2;
} else {
position = str.length() / 2;
length = 1;
}
int start = position >= 1 ? position - 1 : position;
return str.substring(start, position + 1);
}
The work left you have to do is make sure the end position is not greater than the length of the string, otherwise, choose the position as the final index

sum of numbers given date of birth in dialog box

The point of this question was to get a dialogue box open, have it ask your name and date of birth in yyyy format; then give you the sum of your date of birth digits. For example, if you were born in 1999, the program would output "X: the sum of digits in your date of birth are 28".
Here is my current code. I'm stuck on the part with computing the sum of the numbers.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Age {
public static void main(String[] args) {
String name;
String inputString;
int age;
name = JOptionPane.showInputDialog("What is " + "your name");
inputString = JOptionPane.showInputDialog("Enter the year " + "of your birth in yyyy format");
//this is where the calculations will go//
JOptionPane.showMessageDialog(null, "Hello " + name + " your age is" + inputString);
System.exit(0);
}
}
Another way to get this using Java 8 is:
inputString.chars() // get a stream of int with the char code point values
.mapToObj(c -> (char) c) // convert each element to its char representation
.mapToInt(Character::getNumericValue) // convert each char to int
.sum(); // sum all elements in the stream
I would also recommend to validate the input to avoid exceptions. You can use a regex like:
if(inputString.matches("\\d{4}")){
// do your sum
}else{
// warn the user
}
You should check each character of the year and sum its integer representation, like this:
int sum = 0;
for(int i = 0; i < inputString.length(); i++){
sum += Integer.parseInt(""+inputString.charAt(i));
}
System.out.println(sum);
You can check it out on tio.run

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.

Java: Finding Percent Difference

I am trying to figure out how to find the percent difference between the original (no space) string of text and the disemvoweled (no space) string of text. I am attempting to do this by using the equation ((newAmount-reducedAmount)/reducedAmount) but I am having no luck and am ending up with a value of zero, as shown below.
Thank you!
My Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
System.out.println("Welcome to the disemvoweling utility!"); // Initially typed "disemboweling" xD
System.out.print("Enter text to be disemvoweled: ");
String inLine = console.nextLine();
String vowels= inLine.replaceAll("[AEIOUaeiou]", ""); // RegEx for vowel control
System.out.println("Your disemvoweled text is: " + vowels); // Prints disemvoweled text
// Used to count all characters without counting white space(s)
int reducedAmount = 0;
for (int i = 0, length = inLine.length(); i < length; i++) {
if (inLine.charAt(i) != ' ') {
reducedAmount++;
}
}
// newAmount is the number of characters on the disemvoweled text without counting white space(s)
int newAmount = 0;
for (int i = 0, length = vowels.length(); i < length; i++) {
if (vowels.charAt(i) != ' ') {
newAmount++;
}
}
int reductionRate = ((newAmount - reducedAmount) / reducedAmount); // Percentage of character reduction
System.out.print("Reduced from " + reducedAmount + " to " + newAmount + ". Reduction rate is " + reductionRate + "%");
}
}
My output: (Test string is without quotes: "Testing please")
Welcome to the disemvoweling utility!
Enter text to be disemvoweled: Testing please
Your disemvoweled text is: Tstng pls
Reduced from 13 to 8. Reduction rate is 0%
You used an integer data type while calculating percentage difference while performing integer division. You need to type cast one of the variables on the right hand side of the equation to perform double division and then store them in double. The reason for doing this is java integer type can't hold the real numbers.
Also, multiple it by 100 to get the percentage.
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);
If you want a fraction between 0 and 1, then
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);
Your formula gives you a value between zero and one.
An integer cannot hold fractions so it always shows zero.
Multiply by 100 to get a regular percentage value.
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reduction

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