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.
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);
}
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).
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
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.
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]));
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]
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]));
}
}
Related
I am trying to get 3 numbers separated by a space after user's input. I can get the first number and the last one dividing by 10, but I really have no idea how to get the middle number
I tried to take the remainder of the first two numbers and then divide them by ten, but IDEA says that the answer is always zero
public static void main(String[] args) {
System.out.println("Input the number");
int number = read.nextInt();
int a = number%10;
int b = (number%10)/10; // the answer is always 0
int c = number / 100;
System.out.println(c + " " + b + " " + a);
}
Anything modulo 10 will return a result in the range of 0 to 9, and (integer) dividing that by 10 will return 0. You need to reverse the order - first divide the 10 to remove the last digit, and then take the remainder from 10 to keep the middle digit:
int b = (number / 10) % 10;
I suggest using this instead of %. Because you can split and get any digit of number using this code:
int x=158;
char[] xValueInString = Integer.toString(x).toCharArray();
for(int i=0; i<xValueInString.length; i++){
System.out.println(xValueInString[i]);
}
You missed scanner in your code, add Scanner before reading number, try this with little change
public static void main(String[] args) {
System.out.println("Input the number");
Scanner read = new Scanner(System.in);
int number = read.nextInt();
int a = number%10;
int b = (number/10)%10; // the answer is always 0
int c = number/100;
System.out.println(c + " " + b + " " + a);
}
I have upload this code already but it was having some problems and now I have update my code this program does not provide me exact reverse number when I enter 123 it return me 321 but if I enter 001 or 100 it just return me 1 in both case help me to solve this issue
public class Employee {
void fun(int choice) {
int number = choice;
int remander = 0;
int reverse = 0;
while (number >= 1) {
remander = number % 10;> taking remainder here
reverse = reverse * 10 + remander;
number = number / 10;
}
System.out.println(reverse);
}
public static void main(String args[]) {
Employee ob=new Employee();
int choice;
System.out.println("Enter number you want to return");
Scanner obj=new Scanner(System.in);
choice= obj.nextInt();
ob.fun(choice);
}
}
`
Here's a one-liner you can use to convert int to Stream of String numbers, reverse it and return as a String:
Stream.of(Integer.toString(choice).split("")).reduce((c1,c2)->c2+c1).get();
First point: be careful about adding leading 0s to the number. If the number is an integer literal, the leading 0s will actually cause the integer to be interpreted as octal. In this case, 001 octal does, in fact, equal 1 in decimal too, but only due to luck. If you picked another number, it would not give you the result you're expecting; for example, the following code actually prints 63 (not 77):
public class HelloWorld{
public static void main(String []args){
int x = 0077;
System.out.println(x);
}
}
On the other hand, if you're parsing an integer out of a string or using a scanner, the leading 0s will simply be stripped off. For example, the following prints 77:
System.out.println(Integer.parseInt("0077"));
Unfortunately, in neither case will you get 0077, so the leading 0s won't make any difference when you go to do the reverse operation.
Also, think about what happens for 100:
reverse = reverse * 10 + remander;
Reverse is 0 to start with (and 0 * 10 == 0) and 100 % 10 == 0 because 100 is evenly divisible by 10. Put another way, the statement is equal to:
reverse = 0 * 10 + 0;
which clearly equals 0.
You can't do this using Scanner.nextInt() because there is no way to tell if leading zeroes were included once they are converted to an int. And the octal situation is not relevant since Scanner does not process ints that way. So you use either an all String solution and verify the characters are digits or use a hybrid of both math and String methods. I did the latter. The following:
reads in a String
converts to an int
calculates the number of leading zeroes by using the log10 of the
int and the length of the entered string.
Allocates a StringBuilder to hold the result.
Scanner input = new Scanner(System.in);
String val = input.nextLine();
int numb = Integer.valueOf(val);
int len = val.length();
// exponent of the entered number rounded up to the next int.
// This computes the number of digits in the actual int value.
int exp = (int) Math.log10(numb) + 1;
// now reverse the integer and store in the StringBuilder
StringBuilder sb = new StringBuilder();
while (numb > 0) {
sb.append(numb % 10);
numb /= 10;
}
// and append the leading zeros.
System.out.println(sb + "0".repeat(len - exp));
for input of 00001000
prints 00010000
Note that you are still constrained on input by Integer.MAX_VALUE.
I have been tasked with the assignment of creating a method that will take the 3 digit int input by the user and output its reverse (123 - 321). I am not allowed to convert the int to a string or I will lose points, I also am not allowed to print anywhere other than main.
public class Lab01
{
public int sumTheDigits(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + num % 10;
num = num/10;
}
return sum;
}
public int reverseTheOrder(int reverse)
{
return reverse;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Lab01 lab = new Lab01();
System.out.println("Enter a three digit number: ");
int theNum = input.nextInt();
int theSum = lab.sumTheDigits(theNum);
int theReverse = lab.reverseTheOrder(theSum);
System.out.println("The sum of the digits of " + theNum + " is " + theSum);
}
You need to use the following.
% the remainder operator
/ the division operator
* multiplication.
+ addition
Say you have a number 987
n = 987
r = n % 10 = 7 remainder when dividing by 10
n = n/10 = 98 integer division
Now repeat with n until n = 0, keeping track of r.
Once you understand this you can experiment (perhaps on paper first) to see how
to put them back in reverse order (using the last two operators). But remember that numbers ending in 0 like 980 will become 89 since leading 0's are dropped.
You can use below method to calculate reverse of a number.
public int reverseTheOrder(int reverse){
int result = 0;
while(reverse != 0){
int rem = reverse%10;
result = (result *10) + rem;
reverse /= 10;
}
return result;
}
I seen this question posted but got stuck and need a bit help to finish. The program is used to count from one number to another using any base the user inputs.
Example: If the user inputs 5 & 10 with a base of 0123456789 it will output
5 6 7 8 9 10
From what I have so far I can enter 5 and get the next number 6. But 9 to 10 does no work and only gives me 0. When i enter 19 i get 20. When i enter 99 i only get 00.
So what i need is to fix 9 to 10 and 99 to 100
static String nextNum(String base, String n) {
int i = n.length() - 1;
char digit = n.charAt(i)
int pos = base.indexOf(digit);
if (pos + 1 < base.length()) {
n = n.substring(0, i) + base.charAt(pos + 1);
} else if (i > 0) {
n = nextNum(base, n.substring(0, i)) + base.charAt(0);
} else if (pos == base.length() - 1) {
n = n.substring(0, i) + base.charAt(0) + n.substring(i + 1);
} else {
n = "" + base.charAt(1) + base.charAt(0);
}
return n;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter base: ");
String base = input.nextLine();
System.out.print("Please enter first number: ");
String n = input.nextLine();
System.out.print("Please enter second number: ");
String m = input.nextLine();
System.out.println(nextNum(base, n));
}
You're almost there, but your thinking got fuzzy around the base case. Assuming that you're working with base 10 and the digits 0123456789, your algorithm so far does this:
(first if) If the last digit is not 9, adds one to the last digit
(first else if) If the last digit is 9 and the length of the string is at least 2, use recursion to add one to the string without the last 9, and append a 0 at the end.
So far, great. If neither of these two is true, there is only one possibility left (assuming the input is valid): the string is "9". Given that there's only one possible string at that point, you shouldn't have another else if; the problem should be much simpler than you made it. I'll let you work out the rest.
I recall having posted a concept of adding 2 numbers represented in strings a little while back. I am adding a simplified version of what I mentioned in that answer. User ajb's remarks are spot on about the approach you were taking. So, I won't repeat the same thing.
static String nextNum(String base, String n) {
// 2 cases
// one requires carry over
if(n.charAt( n.length() - 1 ) == base.charAt( base.length()-1 ) ) {
// note: carry is set to 1
int last = n.length() - 1, carry = 1;
int systemBase = base.charAt(base.length() - 1) - '0';
systemBase++; // equals 10 for base=0123456789
// equals 4 for base=0123
String newString = "";
int curIndx = n.length() - 1;
while(curIndx >= 0) {
int digit = n.charAt(curIndx) - '0';
// add carry over value
digit += carry;
carry = digit / systemBase;
digit = digit % systemBase;
newString = digit + newString;
curIndx--;
}
//if there is something left in carry
if(carry != 0)
newString = carry + newString;
return newString;
}
// no carry over
else {
// just need to add one to last character
// increment last character by 1
int last = n.charAt(n.length() - 1) - '0'; // actual value of last
last++; // increment by 1
return ( n.substring(0, n.length()-1) + last );
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter base: ");
String base = input.nextLine();
System.out.print("Please enter first number: ");
String n = input.nextLine();
System.out.println(nextNum(base,n));
}
If base = 0123456789, num = 99, then nextNum = 100. If base = 0123456789, num = 9, then nextNum = 10.
I have seen this question asked a few times, but all of the responses have included functionality that I haven't learned yet in this class and am I sure there must be a way to do it with only what I have learned. No arrays, etc... just loops and prior. I am not really looking for the answer, but just some direction. I have included the code I have already done. The program needs to be able to hand negative numbers, the sum and then print in the proper order. Right now my code does everything except print in the proper order. I understand why it is printing in reverse order (because the loop gets rid of and then prints the last number in the int), but I can't seem to figure out a way to change it. I have tried converting it to a string, char and just can't get it. Please take a look, and provide some guidance if you don't mind. thank you in advance.
public static void main(String[] args) {
int num;
int sum;
int temp;
System.out.print("Enter an integer, positive or negative: ");
num = keyboard.nextInt();
System.out.println();
if (num < 0)
num = -num;
sum = 0;
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
System.out.print(temp % 10 + " ");
}
System.out.println(" and the sum is " + sum);
}
}
Not knowing what they've taught you in class so far, an easy albeit inefficient thing to do is to recreate the number as string.
String numbers = "";
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
// System.out.print(temp % 10 + " ");
numbers = (temp % 10) + " " + numbers;
}
System.out.println(numbers + "and the sum is " + sum);
You were already grabbing the ones digit with (temp % 10) and then right shifting the original number with num = num / 10. There are other data structures you could use like a Stack or a LinkedList that are more natural to use in a situation like yours, or you could use a StringBuilder to append the digits to the end and then use the reverse() method to get them back in the correct order, but those data structures probably come after Arrays which you mentioned you didn't know.
Given those constraints, I used String concatenation. In general here is what happens:
String numbers = "";
num = 123;
digit = num % 10; // digit=3
num /= 10; // num=12
numbers = digit + " " + numbers; // numbers="3 " uses old value on right side of the equals
// next iteration
digit = num % 10; // digit=2
num /= 10; // num=1
numbers = digit + " " + numbers; // numbers="2 3 " see how the digit is put to the left of the old value
// last iteration
digit = num % 10; // digit=1
num /= 10; // num=0
numbers = digit + " " +numbers; // numbers="1 2 3 " notice there is an extra space at the end which is ok for your example
Set a counter, loop num/10, if result>0 counter++. In the end, counter+1 will be the number of digits
System.out.println("Please enter numbers: ");
int number_entered = input.nextInt();
int sum = 0;
String reserve = "";
if (number_entered < 0 ) {
number_entered = number_entered * -1;
}
for (number_entered = number_entered; number_entered > 0; number_entered/=10){
int lastdgt = number_entered%10;
sum += lastdgt;
reserve = lastdgt + " " + reserve + " ";
}
System.out.println(reserve);
System.out.println("The sum is = " + sum );
}
}