Using char at to split up a interger
I am trying to split up a four digit integer so i can perform math on each integer to "encrypt" it. This is what i have so far.
Code Java:
import javax.swing.JOptionPane;
public class Project5e
{
public static void main(String[] args)
{
String input;
int number1;
int number2;
int number3;
int number4;
input = JOptionPane.showInputDialog("What is your four digit number?");
number1 = (int)(input.charAt(0));
number2 = (int)(input.charAt(1));
number3 = (int)(input.charAt(2));
number4 = (int)(input.charAt(3));
System.out.print(number1);
}
}
i know i only have number1 in the output......that is just to test. When i run that and put 1234 for the input i get the number 49 for number 1. Any help is appreciated. I dont know if my current code is just wrong or if i am approaching the entire thing totally wrong.
Re: Using char at to split up a interger
49 is the ascii value for the char "1". Java is assuming you want to convert the primitive char into the ascii value of its content.
Your best bet would be to either to read the whole number in as a string, then convert it,. or to convert from char to a String then to an Integer for each char.
Re: Using char at to split up a interger
Ok, so if i read in the entire int 1234 and put it into a string and then convert it. How do i split it up into 4 separate variables so i can apply a algorithm to each individual number?
Edit: is there a way to use the "char.at" command but for integers?
Re: Using char at to split up a interger
You use the charAt method to get the char. You can then use a method in the Character class to convert the char '1' to the int 1.
Re: Using char at to split up a interger
Other than all of the above suggestions, you can separate the four digit integer like;
Code :
int x=1234;
while(x/10!=0){
int temp=x%10;
x=x/10;
System.out.println(temp);
}
System.out.println(x);
Re: Using char at to split up a interger
this should help you. it asks user to type in 4 digits which is first stored as a string.
then the parseInt and charAt etc. applies the first character of the string to variable 'number1', the 2nd character of the string to variable 'number2' etc. etc.
Code :
import java.util.Scanner;
public class StringtoInt {
public static void main(String[] args) {
String input;
int number1, number2, number3, number4;
Scanner scan = new Scanner(System.in);
System.out.println("Enter 4 digits: ");
input = scan.nextLine();
number1 = Integer.parseInt(String.valueOf(input.charAt(0)));
number2 = Integer.parseInt(String.valueOf(input.charAt(1)));
number3 = Integer.parseInt(String.valueOf(input.charAt(2)));
number4 = Integer.parseInt(String.valueOf(input.charAt(3)));
}
}
Hope this helps.