How to conver a string value to an integer - java

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

Related

if condition not working with length function

I've used the length function to calculate the length of digits in an integer input in my program. But when I enter the condition in if syntax, it specifically accepts 1234567890 as input. More clearly, if I enter any random 10 digit no. it shows error whereas on entering 1234567890 it works.
My code snippet:
import java.util.*;
public class tryy {
public static void main(String[] args) {
System.out.println("Mobile Number");
Scanner sc1= new Scanner(System.in);
int number = sc1.nextInt();
int length = String.valueOf(number).length();
if (length != 10){
System.out.println("Invalid Mobile number!");
System.exit(0);
}
}
}
Output when entering any 10 digit random number:
Mobile Number
6483928564
Exception in thread "main" java.util.InputMismatchException: For input string: "6483928564"
at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at tryy.main(tryy.java:6)
The reason is that you have input value more than Integer.MAX_VALUE,check the Integer documentation,we can find that the max value of Integer is 2147483647,while your input is 6483928564,it's greater than the max value,which cause this problem.
In order to solve this problem,you can use long instead of int(keep in mind that long type also may face this issue)
long number = sc1.nextLong();
Here is your Solution
Maximum value that a integer variable in java can accept is 2147483647
Use Double or Long Int
The problem is that, you are assigning a big number for integer type, so try long or another type.
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Mobile Number");
Scanner sc1= new Scanner(System.in);
// int number = sc1.nextInt();
long number = 6483928564L;
int length = String.valueOf(number).length();
if (length != 10){
System.out.println("Invalid Mobile number!");
System.exit(0);
}
else
{
System.out.println("No problem!");
}
}
}
If you are not performing any calculations, then you can take the input as String, and check the length of it.
It will solve your dependency on data types' storage capacity.
You can also do pattern validations, for a phone number, if you take the input as a string.
But if you want to do calculations, then you can change the variable type to a higher type and it will solve your problem.

Reverse number using only loops;no Arrays,convert to String just beginner...Bug:Zero [duplicate]

This question already has answers here:
Reverse number using only loops;no Arrays,convert to String just beginner…Bug:Zero
(2 answers)
Closed 7 years ago.
first sorry about my English(not my native language).
I am new in programming (currently learning Java) and just finishing lecture about looping.
I had a task to reverse random number from 1 to 9999, and got stuck with a bug zero:
example: 23100 output:132 and solution is 00132
Since I still don't know Arrays, convert to String(manipulation),object solution etc…. I couldn't find beginner solution for this problem.
Since this page helped me a lot, I decided to, maybe help someone: this is beginners solution to problem:
123 reverse 321
12300 reverse to 00321 // bug problem with zero solved
now I am still stuck with problem : 00123 and output 32100 not 321
but hope solve this soon
Best regards
import java.util.Scanner;
public class MP{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("enter number:\n");
int x=input.nextInt();
int temp=x;
int z;
while(temp>0){
z=temp%10;
if(z==0){
System.out.printf("%d",0);
}else{
System.out.printf("%d",z);
}
temp=temp/10;
}}}
Since you are the beginner why don't you work with String as with String?
It should suit your purpose:
import java.util.Scanner;
public class MP {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter number:\n");
String x = input.next();
for (int i=x.length();i>0;) {
char c=x.charAt(--i);
if (c<='9'&&c>='0')System.out.print();
}
System.out.println();
}
}
String lm = "00123";
StringBuffer bn = new StringBuffer(lm.replaceAll("^0+(?=\\d+$)", ""));
lm = bn.toString();
System.out.println(bn.reverse());
I did for strings it will not when we convert int to string as given is in hex format it will take 38 into string as 00123 is equivalent to 38 in integer.Hope you like my work.
Happy coding.
Well whenever you try to store 00123 as an integer it is stored as 123 [ EDIT: apparently Java assumes that those leading zeros means that you are inputting a hexadecimal number (base-16 rather than base-10) so the result will be not 123, but 291]. So then when you reverse it, the leading zeros are left out. It seems to me that the only way to do what you are trying to accomplish would be, unfortunately, to use either arrays or Strings (I would recommend using a String).
That being said, if you are avoiding using a String/array simply because you don't know how to use them, then have no fear; Strings are fairly easy to use. A problem you might be running into is that people tend to not make their code very easy to understand. If that is the case, we share the same pains. I will try to make an example that is easy to understand:
It would look something like this:
import java.util.Scanner;
public class MP{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("enter number:\n");
String temp = input.next(); //use next() to look for a String
int digit = temp.length()-1; //starting at the last digit
while (digit >= 0){
char z = temp.charAt(digit); //get the current digit
System.out.print(z); //Print that digit
digit = digit - 1; //Go backwards one digit
}
}
}
Eventually you should be able to write a much shorter program for the same thing:
import java.util.Scanner;
public class MP{
public static void main(String[] args){
System.out.print("enter number:\n");
String temp = new Scanner(System.in).next();
for (int i=temp.length()-1; i>=0; i--){
System.out.print(temp.charAt(i));
}
}
}

How to read an integer that starts with zero?

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.

How can I take a user's input and use it as an integer?

I am a very new Java user who just installed Eclipse two days ago. I am getting my feet wet by writing a program that ask's the user what grade they got on a test in percentage form and returning back what their grade is in letter form. I was also wondering how I can set this integer in an if-else statement so taht if the test grade is greater than or equal to 90, the program will return A for a grade. So on and so forth until 50 or below which would return an F. So far, all I have is this:
import java.util.Scanner;
public class gradechecker {
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
String test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
test_grade = user_input.next();
if(test_grade <= 90) {
}
}
}
To grab a integer value from the user, you use .nextInt().
In this case,
test_grade = user_input.nextInt();
test_grade gets the value entered from the user. However, test_grade is declared as a String variable. You'll need to change that to a int.
What August and azurefrog said are correct in terms of one part of your question, you want to use user_input.nextInt() instead of user_input.next() to get an int input from the user.
For the second part of your question, consider the best order to check the input and how to check the input.
I would consider using >= instead. Check for an A first, then B, etc. If something is >= 80 but you've already determined that it's not >= 90, you know it'll be a B. And remember to check if the user entered an invalid number as well. Remember to use if...else if...else to logically join the comparisons, otherwise you could end up with the wrong result.
Edit: As was pointed out, test_grade needs to be an int instead of a String.
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
You must use int to get the percentage in integer form
int test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
to get an input use input.nextInt... check the http://www.java-made-easy.com/java-scanner.html
test_grade = user_input.nextInt();
//Check for the conditions similar to this
if(test_grade >= 90) {
// assign the grade here
String grade = A;
// print the grade
System.out.println("your grade is"+grade)
}

How to display the middle digit in java

I am trying to get java to display the middle digit of a 1-4 digit integer, and if the integer has an even number of digits i would get it to display that there is no middle digit.
I can get the program to take get the integer from the user but am pretty clueless as how to get it to pick out the middle digit or differentiate between different lengths of integer.
thanks
Hint: Convert the integer to a String.
Java int to String - Integer.toString(i) vs new Integer(i).toString()
You may also find the methods String.length and String.charAt useful.
This sounds like it might be homework, so I will stay away from giving an exact answer. This is much more about how to display characters than it is about integers. Think about how you might do this if the questions was to display the middle letter of a word.
Something like this?
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (!s.hasNextInt()) {
s.next();
System.out.println("Please enter an integer.");
}
String intStr = "" + s.nextInt();
int len = intStr.length();
if (len % 2 == 0)
System.out.println("Integer has even number of digits.");
else
System.out.println("Middle digit: " + intStr.charAt(len / 2));
}
}
Uhm, I realized I might just have done someones homework... :-/ I usually try to avoid it. I'll blame the OP for not being clear in this case

Categories

Resources