How to keep leading zero when incrementing string [duplicate] - java

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 1 year ago.
I need to generate a sequence as follows:
PAY000000 - The first three characters(PAY) remain the same and the 000000 should be incremented by one:
I have tried the following method to generate a sequence number:
public String generateSequence(String currentPayment) {
String chunkNumeric = currentPayment.substring(3, 9);
return "PAY" + (Integer.parseInt(chunkNumeric) + 1);
}
Expected:
currentPayment: PAY000000 Expected value: PAY000001
currentPayment: PAY000001 Expected value: PAY000002
Actual Result:
currentPayment: PAY000001 Actual value: PAY2
The issue is when I pass PAY000001 as parameter the Integer.parseInt(chunkNumeric) remove all the leading zeros that is PAY2 generated instead of PAY000002.
Any idea how I can increment the string while keeping the leading zero?

You should instead maintain the sequence as a number, i.e. an integer or long, and then format that number with left padded zeroes:
public String generateSequence(int paymentSeq) {
return "PAY" + String.format("%06d", paymentSeq);
}
int seq = 1;
String nextSeq = generateSequence(seq);

Related

How to increment the string value? [duplicate]

This question already has answers here:
How to increment the number in a String by 1?
(7 answers)
Closed 5 years ago.
For example:
public static void main(String[] args)
{
String a="1";
int inc= Integer.parseInt(a+1);
System.out.println(inc);
}
I'm getting 11 but i want to get 2. How can i do it in a very efficient way?
Integer.parseInt(a+1); parses the String that results from concatenating the value of the String a ("1") to the int literal 1, which is "11".
Change it to
int inc = Integer.parseInt(a) + 1;
This way "a" would be parsed to the integer 1 and then 1 would be added to it to give you the value 2.
Since a is a String object this operation is not giving the desired input
Integer.parseInt(a+1);
because will be equivalent to do
Integer.parseInt("1"+"1");
or
Integer.parseInt("11");
you need to parse the string first and then increment
Integer.parseInt(a)+1

How to add Leading Zero with getMonth in Java (Android) [duplicate]

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Adding a leading zero to a large string in Java
(2 answers)
Closed 8 years ago.
I'm using an int variable:
month = dp.getMonth() + 1;
currently getting an output of "2" and when I do the following:
if (month<10){
month = '0'+month;
};
I get: 50.
Your problem is that your '0' char is being coerced to an integer. Since '0' has an ASCII value of 48, you're getting 48 + 2 = 50.
Note that what you're trying to do won't work - you can't add a leading 0 to month, as month is a number. A leading zero only makes sense in a string representation of a number.
As explained in this answer, here's how to produce a zero-padded number:
String.format("%02d", month);

How can I consider the value of 0 before a number while doing some operations [duplicate]

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 8 years ago.
I'm working on a question in JAVA where I need to perform some operation, say addition or subtraction on a number which is in the below format:
0001
I want to consider the 0's also when I add it with a other number, like
0001 + 1 = 0002
0562 + 0001 = 0563
but when I'm trying to do the same, I'm not able to output the number with 0's in the front. I have tried taking the number as String but it's not working. Kindly help on how can i consider taking 0 also in the front of a number.
My code:
Scanner in = new Scanner(System.in);
String UserInput;
String a;
System.out.println("Enter number: ");
a=in.next();
if (a.length()==4 && a.matches(".*\\d+.*")) {
UserInput=a;
}
UserInput = String.valueOf(Integer.parseInt(UserInput) + 1);
System.out.println(s1);
The Result:
Input:
0001
Output:
2
Use System.out.format(String format, Object... args) to format the resulting integer with four digits:
int updatedInt = Integer.parseInt(UserInput) + 1;
System.out.format("%04d%n", updatedInt);
See http://docs.oracle.com/javase/tutorial/java/data/numberformat.html.

Creating a random 4 digit number, and storing it to a string [duplicate]

This question already has answers here:
How to Convert an int to a String? [duplicate]
(6 answers)
Closed 8 years ago.
I'm trying to create a method which generates a 4 digit integer and stores it in a string.
The 4 digit integer must lie between 1000 and below 10000. Then the value must be stored to PINString.
Heres what I have so far. I get the error Cannot invoke toString(String) on the primitive type int. How can I fix it?
public void generatePIN()
{
//generate a 4 digit integer 1000 <10000
int randomPIN = (int)(Math.random()*9000)+1000;
//Store integer in a string
randomPIN.toString(PINString);
}
You want to use PINString = String.valueOf(randomPIN);
Make a String variable, concat the generated int value in it:
int randomPIN = (int)(Math.random()*9000)+1000;
String val = ""+randomPIN;
OR even more simple
String val = ""+((int)(Math.random()*9000)+1000);
Can't get any more simple than this ;)
randomPIN is a primitive datatype.
If you want to store the integer value in a String, use String.valueOf:
String pin = String.valueOf(randomPIN);
Use a string to store the value:
String PINString= String.valueOf(randomPIN);
Try this approach. The x is just the first digit. It is from 1 to 9.
Then you append it to another number which has at most 3 digits.
public String generatePIN()
{
int x = (int)(Math.random() * 9);
x = x + 1;
String randomPIN = (x + "") + ( ((int)(Math.random()*1000)) + "" );
return randomPIN;
}

Add leading zeroes to number in Java? [duplicate]

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 8 years ago.
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)
static String intToString(int num, int digits) {
StringBuffer s = new StringBuffer(digits);
int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;
for (int i = 0; i < zeroes; i++) {
s.append(0);
}
return s.append(num).toString();
}
String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)
In your case it will be:
String formatted = String.format("%03d", num);
0 - to pad with zeros
3 - to set width to 3
Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.
Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:
static String intToString(int num, int digits) {
assert digits > 0 : "Invalid number of digits";
// create variable length array of zeros
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
// format number as String
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(num);
}
How about just:
public static String intToString(int num, int digits) {
String output = Integer.toString(num);
while (output.length() < digits) output = "0" + output;
return output;
}
In case of your jdk version less than 1.5, following option can be used.
int iTest = 2;
StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
sTest.append(String.valueOf(iTest));
System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

Categories