I am trying to create a program where the user inputs a four digit code. I then need to separate the individual digits and apply some basic math separately.
For example user input: 1234 I need to grab numbers 1, 2, 3, 4, apply basic math to them, then return them as output as integers.
This is what I have so far:
public static void main(String[] args) {
int fourDigitPin;
int firstDigit;
int secondDigit;
int thridDigit;
int forthDigit;
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter your 4 digit pin number: ");
fourDigitPin = keyInput.nextInt();
firstDigit = fourDigitPin.charAt(0);
As you can see, I havent gotten to the math portion yet. I am attempting to use charAt to grab the numbers, but cannot as they are integers. Should I set the set input variable "fourDigitPin" as a string or char? Any help would be greatly appreciated.
CodePudding user response:
1st method:
public static void main(String[] args) {
String fourDigitPin;
int firstDigit;
int secondDigit;
int thirdDigit;
int forthDigit;
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter your 4 digit pin number: ");
fourDigitPin = keyInput.next();
firstDigit = fourDigitPin.charAt(0) - '0';
secondDigit = fourDigitPin.charAt(1) - '0';
thirdDigit = fourDigitPin.charAt(2) - '0';
forthDigit = fourDigitPin.charAt(3) - '0';
System.out.println(firstDigit " " secondDigit " " thirdDigit " " forthDigit);
}
2nd method:
public static void main(String[] args) {
String[] fourDigitPin;
int firstDigit;
int secondDigit;
int thirdDigit;
int forthDigit;
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter your 4 digit pin number: ");
fourDigitPin = keyInput.next().split("");
firstDigit = Integer.parseInt(fourDigitPin[0]);
secondDigit = Integer.parseInt(fourDigitPin[1]);
thirdDigit = Integer.parseInt(fourDigitPin[2]);
forthDigit = Integer.parseInt(fourDigitPin[3]);
System.out.println(firstDigit " " secondDigit " " thirdDigit " " forthDigit);
}
3rd method:
public static void main(String[] args) {
int fourDigitPin;
int firstDigit;
int secondDigit;
int thirdDigit;
int forthDigit;
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter your 4 digit pin number: ");
fourDigitPin = keyInput.nextInt();
forthDigit = fourDigitPin % 10;
fourDigitPin /= 10;
thirdDigit = fourDigitPin % 10;
fourDigitPin /= 10;
secondDigit = fourDigitPin % 10;
fourDigitPin /= 10;
firstDigit = fourDigitPin % 10;
fourDigitPin /= 10;
System.out.println(firstDigit " " secondDigit " " thirdDigit " " forthDigit);
}
CodePudding user response:
You should convert it to a string because you're expecting it to be four characters (not one).
Also, minor UI point: right now you don't verify that the user actually entered a four-digit number. You should do so before you get the individual digits so that you don't get an exception.
One more thing to be careful of: make sure that you don't "directly" cast the char back to an integer at any point because then it'll be cast to the equivalent ASCII value (not the actual value of the number).
CodePudding user response:
Take the input as a String rather than an int.
String number = keyInput.next();
Then
firstDigit = number.charAt(0);
secondDigit = number.charAt(1);
thirdDigit = number.charAt(2);
fourDigit = number.charAt(3);
For this, you would have to use as many variables as individual digits. Or you can use a loop.
for(int i=0;i<number.length();i ){
digit = number.charAt(i);
//More code
}
But a better soln would be to take modulo.
int n = keyInput.nextLine();
while(n>0){
lastDigit=n%10;
n/=10;
} //you get digits from the rear end as modulo returns remainder
CodePudding user response:
You better use "modulo" operator approach to get individual digit and then perform math on that digit. This operator will give you reminder.
Example:
int remainder = a % b;
Refer javadoc operators for more details.
Other approaches like charAt
might work in this case, because you know the pin is of size 4, but if the size is not known upfront and want to use your code for 5 digits or 3 digits, it will fail.
CodePudding user response:
final char[] chars = String.valueOf(fourDigitPin).toCharArray();
int firstDigit = Integer.parseInt(String.valueOf(chars[0]));
int secondDigit= Integer.parseInt(String.valueOf(chars[1]));
int thridDigit=Integer.parseInt(String.valueOf(chars[2]));
int forthDigit= Integer.parseInt(String.valueOf(chars[3]));
CodePudding user response:
tl;dr
String
.valueOf( 1_234 ) // Convert `int` to `String`.
.codePoints() // `IntStream` of Unicode code points, one integer for each character.
.filter( Character :: isDigit ) // Remove any non-digit.
.mapToObj( Character :: toString ) // Convert code point back to character of that digit.
.map( Integer :: valueOf ) // Parse that textual digit back to an integer. In this case, an `Integer` object.
.toList() // Make a list of our `Integer` objects, each element being a single digit from our original number.
.toString()
[1, 2, 3, 4]
Code points
The char
type in Java is legacy, and is essentially broken. As a 16-bit value, it cannot represent most characters.
Instead, use code point integer numbers.
Convert your int
to a String
.
String inputString = String.valueOf( inputInt ) ;
Verify the length.
if( inputString.length() != 4 ) { … }
Get an IntStream
of code point numbers.
IntStream codePoints = inputString.codePoints() ;
Loop those code point numbers, verifying it is a digit. If so, get the character. Convert that character to an int
. Add it to our collection of integers.
List< Integer > digits =
codePoints
.filter( Character :: isDigit )
.mapToObj( Character :: toString )
.map( Integer :: valueOf )
.collect( Collectors.toList() ) // In Java 16 , replace with .toList()
;
See this code run live at IdeOne.com.
[1, 2, 3, 4]
CodePudding user response:
It will be easy to improve your code's robustness by reading a string and testing its worthiness for further processing. Additionally, it will probably be easier to read your code if you store the digits in an array instead of enumerating each digit in a separate variable name. One indication that an array is more appealing is the fact that you have fewer variable names to misspell. You misspelled "third" as "thrid". Another is the fact that you have fewer parameters to pass if you have to pass parameters to some function. Yet another benefit is "rectangularization", which I'll define (redefine?) as being vertically aligned so as to spot typos more easily.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int digit[] = new int[4];
Scanner keyInput = new Scanner(System.in);
String pinstr;
do {
System.out.print("Enter your 4 digit pin number: ");
pinstr = keyInput.next();
if (pinstr.matches("^[0-9]{4}$"))
break;
System.err.println("You did not enter precisely 4 decimal digits");
} while (true);
digit[0] = pinstr.charAt(0) - '0';
digit[1] = pinstr.charAt(1) - '0';
digit[2] = pinstr.charAt(2) - '0';
digit[3] = pinstr.charAt(3) - '0';
for (int i=0; i<4; i )
System.out.println(String.format("Digit at offset %d is %d", i, digit[i]));
}
}