How to read an integer that starts with zero? - java

This is a program to read an integer:
public static void main(String argv[]) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.println(x);
}
But if I enter an input like this: 000114 it will be read like 114.How to read integer starts with zeroes?

Zeros are ignored at the start of an int. If you need the zeros to be displayed, store the number as a String instead. If you need to use it for calculations later, you can convert it to an int using Integer.parseInt(), so your code should look like this:
String x = input.next();
System.out.println(x);
//if you need x to be an int
int xInt = Integer.parseInt(x);
Keep in mind that, in this example, xInt will lose the zeros.

Perhaps you should read the input as a string and not as an integer if you really need to have the leading zeroes.

That is the expected outcome when reading an int with leading 0s because 000114 isn't an int when represented like that.
If you need it to be 000114 then you should read it as a string.

Related

Java input/output confusion

I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.

How to print ASCII value of an int in JAVA

I've searched for this on the internet but was unable to find a precise solution, one possible solution I found was to read the integer as a String, and use charAt method and then cast the character to int to print the ascii value.
But is there any other possible way to do it other than the above stated method?
int a=sc.nextInt();
//code to convert it into its equivalent ASCII value.
For example, consider the read integer as 1, and now I want the ASCII value of 1 to be printed on the screen,which is 49
I assume you're looking for this:
System.out.print((char)a);
The easy way to do that is:
For the Whole String
public class ConvertToAscii{
public static void main(String args[]){
String number = "1234";
int []arr = new int[number.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = number.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
For the single Character:
String number="123";
asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value

what is equivalent to isEmpty() for integers?

Below is the script I have at the moment
import java.util.Arrays;
import java.util.Scanner;
public class SeeWhatTo
{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in); //define scan
int a = scan.nextInt();
int sum =0;
while (a>0 )
{
sum = sum +a;
a = scan.nextInt();
}
System.out.println(sum); //print out the sum
}
}
Currently, it stores an input value in a and then adds it to sum and once a negative or zero is given as an input, it suspends itself and outputs the sum.
I was wondering if there's an integer equivalent of isEmpty so that i can do while (! a.isEmpty() ) so when there's no input but an enter, then it would stop and prints out the sum.
A natural followup from that would be, is there a way to assign an input integer to a and check if it is empty or not at the same time in the while condition as in while ( ! (a=scan.nextInt()).isEmpty() )
Scanner can do 2 things:
Read line-by-line (nextLine).
Read token-by-token (next or e.g. nextInt).
These are really two different functionalities of Scanner, and if you're reading tokens then your Scanner basically doesn't know about empty lines.
If you call nextInt, Scanner does two things:
Finds the next token (default: delimited by any whitespace).
Tries to turn it in to an int.
The tokenizing behavior is an important feature of Scanner. If you enter 1 2\n and call nextInt twice, you get 1 and 2. However, if you enter an empty line, the tokenizing Scanner just skips it as whitespace and keeps looking for another token.
So the straightforward answer is "no": you can never get an "empty" int from a call to nextInt in a simply way and still retain the token-by-token behavior. (That's beyond the fact that a primitive variable in Java can't be "empty".)
One easy way to do what you're asking is to use line-by-line reading instead and call parseInt yourself:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String line;
while (!(line = systemIn.nextLine()).isEmpty()) {
sum += Integer.parseInt(line);
}
But you lose the tokenizing behavior. Now, if you enter 1 2\n, an exception is thrown because nextLine finds 1 2.
You can still read token-by-token with nextInt, but it's more complicated, using a second Scanner:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String nextLine;
while (!(nextLine = systemIn.nextLine()).isEmpty()) {
Scanner theInts = new Scanner(nextLine);
while (theInts.hasNextInt()) {
sum += theInts.nextInt();
}
}
Here, we can enter 1 2\n, get 1 2 as our next line, then ask the second Scanner to tokenize it.
So yes, you can program the functionality you're looking for, but not in an easy way, because Scanner is more complicated.
edit
Possibly another way is to use a delimiter on the line separator:
// use System.getProperty("line.separator") in 1.6
Scanner systemIn = new Scanner(System.in).useDelimiter(System.lineSeparator());
int sum = 0;
while (systemIn.hasNextInt()) {
sum += systemIn.nextInt();
}
Now, nextInt tokenizes the same way as nextLine. This will break the loop for any input that's not an int, including empty tokens. (Empty tokens aren't possible with the default delimiter.) I'm never really sure if people actually expect Scanner's default delimiting to work the way it does or not. It's possible creating a Scanner in this way makes it behave closer to what people seem to expect for reading the console, just line-by-line.
There isn't an equivalent in the sense that you describe, since String is a variable-length collection of characters, and having zero characters is still a valid String. One integer cannot contain zero integers, since by definition, it is already an integer.
However, your problem revolves around how Scanner works, rather than how int works.
Take a look at scan.hasNextInt(), which returns true if there is an int to read, and false otherwise. This may give you what you want, using something like:
Scanner scan = new Scanner(System.in);
int sum = 0;
while(scan.hasNextInt())
{
int a = scan.nextInt();
sum = sum + a;
}
System.out.println(sum);

How to get number of digits in an integer with leading zeros in java?

This question includes numbers with leading zeros and numbers which normally counted as hexadecimal(like 09).Assume user input is integer,because i pass number to some function as integer.
For example
if user inputs 5 i should get 1
if user inputs 0005 i should
get 4
if user inputs 09 i should get 2
(Note)Below method does not work:
String.valueOf(integer).length()
The user input will probably be a String already, so you could just use String.length(). For example:
public static void main(String... args) {
Scanner in = new Scanner(System.in);
String number = in.next();
int numDigits = number.length();
System.out.println(numDigits);
}
If the input were an integer, it couldn't have leading zeros. If the initial input had zeros and you converted it to an integer at some point, you lost this information.
This only works if the number you want is a String. You don't have 0005 integer numbers unless it is not an integer, it is a String instead.
You have to save those numbers as a String instead of a int for this to work. Then you can use the .length() method

How to conver a string value to an integer

I want to convert a string value to an integer but I can't. My statement checked
=Integer.parseInt(input);
has an error, please help and thanks a lot in advance.
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
String input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLine();
if(input.length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =Integer.parseInt(input);
System.out.println(checked);
}
}
Use checked =Long.parseLong(input); instead of checked =Integer.parseInt(input);
12 digit numbers are very large and so you can not store it in int.So you need to store in Long
12 digits number is a really big number...Integer can't store it. That is you error - so you need another type to store the number.
I recommend you to use Long : Long.parseLong(input);
That should solve the problem.
Your issue is this line:
input = reader.nextLine();
try this:
checked = Long.parseLong(input);
use
checked= Long.parseLong(input)
instead of
Integer.parseInt
it can't handle a 12 digit long number
You're getting an error because the string value that you are giving as input is more than 2147483647. This is the max int can store (you can sysout Integer.MAX_VALUE to check this). If you intend to input a bigger number, may be you can use long (max value 9223372036854775807)
System.out.println(Integer.MAX_VALUE); // =2147483647 (2^31 - 1)
System.out.println(Long.MAX_VALUE); // =9223372036854775807 (2^63 - 1)
Depending on the input size, you might want to choose the correct data type.
Please see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for further details.
Here is the corrected program(assuming that your trying to find whether a User-inputted number is less than 12 and displaying the number
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
long input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLong();
if(String.valueOf(input).length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =(long)(input);
System.out.println(checked);
}
}

Categories

Resources