This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Integer with leading zeroes
The program I am coding requires me to label an item with an inventory number of 012345 and store it in a int variable.
This is a stripped down example of what I am doing:
int test = 012345;
System.out.println(test);
this prints as:
5349
How do I get it to print out as 012345 rather than 5349?
EDIT: I am entering this into the parameter of a constructor for a custom class i am initializing. Then I use a method to return what the current number is, then print it to the terminal window.
You get a wrong number because when you prepend zero to an integer literal, Java interprets the number as an octal (i.e. base-8) constant. If you want to add a leading zero, use
int test = 12345;
System.out.println("0"+test);
You can also use the formated output functionality with the %06d specifier, like this:
System.out.format("%06d", num);
6 means "use six digits"; '0' means "pad with zeros if necessary".
As already said, int value with leading zero is considered as octal value. If you don't need to have test as int, why not make it string? Like
String test= new String("012345");
And if you want to use int for test, you can do not prepend 0, rather just use the number and prepend 0 at the time of printing.
In case if you're wondering how will you find how many leading zero are to be prepended, you may do like this
int lengthOfItemID=6;
int test=12345;
String test1=new String("000000"+test);
System.out.println(test1.substring(test1.length()-lengthOfItemID));
Pardon syntax mistakes, been years I last worked with java.
You can get the right result by using Integer.parseInt. That will make your string into a decimal string. (found here). The JAVA API here states that it takes a string and returns a signed decimal.
Related
This question already has answers here:
Java output formatting for Strings
(6 answers)
Closed 11 months ago.
Given these variables:
int a = 1, b = 123, c = 55, d= 1231;
Is there a way in Java to print them with a set width of 5, say. In case number is less than five digits - only print dashes.
1----,123--,55---,1231-
I am aware that these can be achieved with some loops and if statements, looking for something similar to setw() from C++
System.out.println(String.format("%-5.5s", s).replace(" ", "-"));
In short, you can't do it directly. Java has functionality broadly similar to that of C's "printf" formatting.
You can set a field width, you can justify left or right, but your fill characters are limited to zero and space.
Documentation
If the format uses the general "%s" directive, and the corresponding argument is of a class under your control, then you can implement a 'formatTo' method to do the conversion. So a wrapper class might be useful to you.
I want to pull an int from a getMethod() that is in binary format. Does anyone know how to use: int i = 0b10101010;(taken from a previous post on Stack Overflow thank you all) with a variable.
int i = 0bgetMethod(); does not work in any of the multiple ways I have tried it (0b + var, etc). I do not have the actual value, so I cannot hard code the 1's & 0's.
Any help would be appreciated. This is for an assembler, this binary number is selecting the register in the register file, passed in string format to preserve it until I parse it.
A digital computer stores all int(s) in binary (even those you encode in decimal). You can use Integer.toBinaryString(int) to see the binary representation of any int.
If you need to parse a binary String, you can use Integer.parseInt(String, int) where the first argument is the String to be parsed and second argument is a radix (for binary that would be 2).
code: int i = Integer.parseInt(Micro.RegSel, 2); produces an error(the method is not applicable for enumbody).
Micro.RegSel is an enum implements enumbody that results in a string of 4 1's & 0's. If I simply print it, it prints out dropping all the leading zeros. I need the leading zeros. My code needs a total of 32bits, and this is part of it.
one of the switch statements has: Micro.RegSel.setFourBit("0011"); This will print "11". printing the string directly from the enum: 0011
int i = Integer.parseInt(Micro.RegSel.getFourBit().toString(), 2); produces a java.lang.NumberFormatException even though Micro.RegSel.getFourBit().toString() prints all 4 digits
After trying several options (that's where I asked my question) and reading the stack trace, I realized that the problem was the default was "xxxx" for the opcodes that do not select a register.
so I rewrote it like this:
int i = 0;
String j = Micro.RegSel.getFourBit().toString();
if(j.matches("[\d]")){
i = Integer.parseInt(j, 2);
}
It works like I need it to. Thanks
This question already has answers here:
Extract Integer Part in String
(9 answers)
Closed 7 years ago.
Is there a way to get a Integer variable from a String object, something like:
String string = "Render.SCREEN_WIDTH_TILES";
// SCREEN_WIDTH_TILES is a Render Integer value referenced in other class
I want the string variable to hold the reference to the specified int.
What I want from that string value is to "transform it" into a int value,
Is it possible to do this?
I can't find a way to handle an integer value as a variable in a string.
You seem to be misunderstanding how Integer.parseInt(s) works. The documentation clearly states:
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign - (\u002D) to indicate a negative value or an ASCII plus sign + (\u002B) to indicate a positive value.
The parameter to Integer.parseInt(s) must be a string that contains a number. Such as:
Integer.parseInt("12345")
Integer.parseInt("-45")
But not:
Integer.parseInt("Hello world")
Integer.parseInt("this will not work 4 you")
And certainly not: Integer.parseInt("Render.SCREEN_WIDTH_TILES - 1");
This question has been answered so please close it...
Thanks for the clarifications!!
I looked at the question above but there is an use case which we should consider before closing the issue:
I have a situation where I raise an order and the system generates a reference number as: 0000002443
I store that number as a string.
When the system sends the order out, it sends two documents. One as a requisition with the above reference number and the other as a Purchase order with a reference: 0000002444
I need to be able to store the first reference number (i.e. 0000002443) as an Integer keeping the preceding zeroes and add +1 and store as a PO reference number (i.e.0000002444) to verify the orders later.
If I keep the first reference number as a String then I won't be able to add 1 to the reference number to get the PO reference Number.
It's a Follow up question:
https://stackoverflow.com/questions/15025136/converting-string-to-integer-but-preceding-zero-is-being-removed
Integers do not have leading zeros (as it says in that other question)
You'd need to convert it to an int, add one, and then pad it back into a String:
def ref = '0000002443'
def refPlusOne = "${ref.toInteger() + 1}".padLeft( ref.length(), '0' )
Simply put, an integer doesn't have a number of leading zeroes. It doesn't even have information about whether it's decimal, hex, or anything like that. It's just an integer.
If you really need to follow your existing design, I suggest you parse it as an integer, add one, and then repad with as many zeroes as you need to get back to the original length.
To be honest, if it's really just meant to be a number, it would be better if you stored it as a number instead of using a string at all.
e have a date form that can accept 2 or 4 digit years. I am not trying to code for exceptions...just instances where the year is either 2 or 4 digits long. I'm using lastIndexOf to find the last instance of "/", and if the third character after the slash is numeric, I assume a 4-digit year. Otherwise it's a two digit year.
I've already tested and validated that this is the only line giving me an issue right now,
if (inputLine.lastIndexOf.isNumeric("/"))+3 {
year = inputLine.trim().substring(inputLine.lastIndexOf("/")+1,input.lastIndexOf("/")+4).trim);
else year = "0000";
I keep getting compilation errors. For the lines in which I'm adding to the index Value, I've got a bad operand for the binary operator. Additionally, the variable lastIndexOf can't be found.
I'm calling the list below at the head of the program, and as far as I can tell from the java documentation, io and lang pull in the appropriate methods and classes.
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.lang.*;
For the if statement, although my parens are balanced, I don't know if adding the additional characters (e.g., index value + 3) is being done within the right level of the nested parens. That being said, I've tried top add those integers pretty much to no avail.
if (inputLine.lastIndexOf.isNumeric("/"))+3 {
year = inputLine.trim().substring(inputLine.lastIndexOf("/")+1,input.lastIndexOf("/")+4).trim);
else year = "00/00/0000";
I'm wondering a couple thigs: First, can I do this in a single statement, or is it better to define the index in one statement, then define index+offset-value in a subsequent statement?
When I'm using multiple methods and classes operating on a single field (e.g., .trim().substring.Indexof() etc., what is the order in which Java parses those? I'd like to undestand how these statements are being parsed so I've got a better understanding of the best way to manipulate the variables and test the output.
You are using the +3 incorrectly. You're putting it outside of the if(condition) statement, somewhere where it doesn't make any syntactic sense - it's gobbledygook in your code.
Also, if you're trying to test if the result of inputline.lastIndexOf('/') is numeric, it won't mean anything. If the specified character does not occur, lastIndexOf won't throw an exception; it will just return -1. You want to test if the result is greater than/equal to zero.
You can't use trim() and then use an index from the original string. You need to trim() the string and then use an index from the trimmed string (otherwise the index could be completely incorrect)
Perhaps using SimpleDataFormat with a dd/MM/yyyy format or using split would be a better choice.
String[] parts = inputLine.trim().split("/");
String day = parts[0], month = parts[1], year = parts[2];
To use trim() and lastIndexOf()
String trimmed = inputLine.trim();
int last = trimmed.lastIndexOf("/");
year = trimmed.substring(last+1);
Regarding the last part of your question
When you do method chaining like .trim().substring.Indexof() each method is invoked in left-to-right order. So:
String myString = " string ";
int index = myString.trim.substring(3).indexOf('n');
is the comparable to:
String myString = " string ";
String trimmedString = myString.trim(); // "string"
String subString = trimmedString.substring(3) // "ing"
int index = subString.indexOf('n'); // 1