Java Addition with characters [duplicate] - java

This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 6 years ago.
I am fairly new to java, about 3 weeks into my course. In my assignment, I needed to use charAt to separate the string into 14 parts. Now I need to use addition and add these together.
I have tried many times with no success. Every time I add them together and print it out it gives me a number way bigger than it should be.
char num1 = roulette.charAt(0);
char num2 = roulette.charAt(1);
char num3 = roulette.charAt(2);
char num4 = roulette.charAt(3);
char num5 = roulette.charAt(4);
char num6 = roulette.charAt(5);
When I add num1+num2+num3+num4+num5+num6, I get a number way bigger than it should be.
Am I missing something?

This is due to you adding the characters together, they will not turn into the number equivalent automatically. You will need to change them yourself, to do this you can use Integer.parseInt(char) and you can add them together like that. For example Integer.parseInt(String.valueOf('1') + Integer.parseInt(String.valueOf('2')) this will add 1 + 2 together correctly now resulting in 3 rather than appending 2 to the 1 making 12

If you want to add the characters then each character has a character code that will be used. so for example according to the ASCII Table 'a' = 97, 'b' = 98, 'c' = 99; so if you add these together you will get 294. ASCII Table https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html.
However, if each character represents a number and you want to add the numbers then you can do something like this:
char num1 = roulette.charAt(0);
int firstNum = Integer.parseInt(Character.toString(num1));
char num2 = roulette.charAt(1);
int secondNum = Integer.parseInt(Character.toString(num2));
char num3 = roulette.charAt(2);
int thirdNum = Integer.parseInt(Character.toString(num3));
char num4 = roulette.charAt(3);
int fourthNum = Integer.parseInt(Character.toString(num4));
char num5 = roulette.charAt(4);
int fifthNum = Integer.parseInt(Character.toString(num5));
char num6 = roulette.charAt(5);
int sixthNum = Integer.parseInt(Character.toString(num6));
int result = firstNum + secondNum + thirdNum + fourthNum + fifthNum + sixthNum;

You cannot cast your chars to integer first try like this
Integer.parseInt(num1) + Integer.parseInt(num2) +Integer.parseInt(num3)...
and so on.
EDIT
I just learned that you cannot use Integer.parseInt(num1) for Character.
You should cast your chars as below:
char a = '5';
int b = Integer.parseInt(String.valueOf(a));
int c=b+b;
System.out.println(c); //this will give 10

If you add characters to characters, it means you are adding their ascii values. But if you want to add the numeric value which is presented as a Character in the String, then you have to convert the character to integer first. See the example given below.
N.B. when you want to add a sequence of values, use loop.
Example
String roulette = "123456";
int sum = 0;
for (int i = 0; i < roulette.length(); i++) {
sum = sum + roulette.charAt(i);
}
System.out.println("Sum : " + sum);
sum = 0;
for (int i = 0; i < roulette.length(); i++) {
sum = sum + Integer.parseInt(String.valueOf(roulette.charAt(i)));
}
System.out.println("Sum : " + sum);
Output
Sum : 309
Sum : 21
Case 1: sum = sum + roulette.charAt(i);
Adding ascii values of the numbers. So the sum is 309.
ascii_value('1') - 49
ascii_value('2') - 50
...
ascii_value('5') - 53
ascii_value('6') - 54
Sum = 49 + 50 + 51 + 52 + 53 + 54 = 309
Case 2: sum = sum + Integer.parseInt(String.valueOf(roulette.charAt(i)));
Adding the numeric value instead of the ascii values. So the sum is 21.
Sum = 1 + 2 + 3 + 4 + 5 + 6 = 21

Related

How would I add two int that are in the same array to each other and convert them into an int. In the Luhn Algorithm

I am trying to add two parts of an array together to go into an int value. I am using Luhn algorithm to figure out of a credit card is a valid credit card. We are only using 6 digit credit card's just to make sure no one enter's a real credit card number. The part I am confused on is when I go to split a number that is above 10 and add it together. Example if the algorithm was to give me 12 I would need to separate it into 1 and 2 and then add them together to equal 3. I believe I am splitting it currently in the code but when I go to add them together I get some number that makes no since. here is a section of the code with some notes about it.
I have printed out numbers in certain places to show myself what is going on in certain places. I have also added in some comments that say that either the number that is printed out is what is expected, and some comments for when there isn't something I expected
int[] cardNumber = new int[]{ 1,2,3,4,5,5};
int doubleVariablesum = 0;
int singleVariablesum = 0;
int totalSum = 0;
int cutOffVar = 0;
String temp2;
for (int i = cardNumber.length - 1; i >= 0;) {
int tempSum = 0;
int temp = cardNumber[i];
temp = temp * 2;
System.out.println("This is the temp at temp * 2: " + temp);
temp2 = Integer.toString(temp);
if (temp2.length() == 1) {
System.out.println("Temp2 char 0: "+ temp2.charAt(0));
// this prints out the correct number
// Example: if there number should be 4 it will print 4
tempSum = temp2.charAt(0);
System.out.println("This is tempSum == 1: " + tempSum);
// when this goes to add temp2.charAt(0) which should be 4 it prints out //something like 56
} else {
System.out.println("TEMP2 char 0 and char 1: " + temp2.charAt(0) + " " + temp2.charAt(1));
// this prints out the correct number successfully spited
tempSum = temp2.charAt(0) + temp2.charAt(1);
System.out.println("This is tempSum != 1: " + tempSum);
// but here it when I try to add them together it is giving me something
// like 97 which doesn't make since for the numbers I am giving it
}
doubleVariablesum = tempSum + doubleVariablesum;
System.out.println("This is the Double variable: " + doubleVariablesum);
System.out.println();
i = i - 2;
}
Since you are converting the number to a string to split the integer, and then trying to add them back together. You're essentially adding the two characters numerical values together which is giving you that odd number. You would need to convert it back to an integer, which you can do by using
Integer.parseInt(String.valueOf(temp2.charAt(0)))
When adding char symbols '0' and '1' their ASCII values are added - not numbers 0 and 1.
It is possible to use method Character::getNumericValue or just subtract '0' when converting digit symbol to int.
However, it is also possible to calculate sum of digits in a 2-digit number without any conversion to String and char manipulation like this:
int sum2digits = sum / 10 + sum % 10; // sum / 10 always returns 1 if sum is a total of 2 digits
Seems like charAt() type casts into integer value, but the ascii one. Hence for the characters '0' and '1', the numbers 48 and 49 are returned resulting in a sum of 97. To fix this, you could just assign temp2 to (temp / 10) + (temp % 10). Which actually splits a two digit integer and adds their sum.
You need to be aware of the following when dealing with char and String
Assigning the result of charAt(index) to an int will assign the ASCII value and not the actual integer value. To get the actual value you need to String.valueOf(temp2.charAt(0)).
The result of concatenating chars is the sum of the ASCII values.
eg if char c = '1'; System.out.println(c + c); will print "98" not "11".
However System.out.println("" + c + c); will print "11". Note the "" will force String concatenation.

How to grab individual digits from a 4 digit interger

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

How to convert char to decimal using an ascii table?

I'm working on a java program to convert a 4 digit binary number to decimal. I need to enter the binary as a String, convert to a char, and then to a decimal. I cannot use something like:
int decimal = Integer.parseInt("1010", 2);
Here is my code so far:
import java.util.Scanner;
public class BinaryConvert2 {
public static void main(String[] args){
System.out.println("Please enter a 4 digit binary number: ");
Scanner s = new Scanner(System.in);
String binaryNumber = s.next();
char a, b, c, d;
a = binaryNumber.charAt(0);
a = (char) (a*2*2*2);
b = binaryNumber.charAt(1);
b = (char) (b*2*2);
c = binaryNumber.charAt(2);
c = (char) (c*2);
d = binaryNumber.charAt(3);
d = (char) (d*1);
System.out.println(binaryNumber + " in decimal is: " + a + b + c + d);
}
}
I'm trying to multiply the char values by powers of 2 so that it will convert to decimal, but when I run the program, I get weird answers such as :
Please enter a 4 digit binary number:
1010
1010 in decimal is: ?Àb0
The ascii (char) value of 0 is 48 and the value if 1 is 49,
so you need to subtract 48 from the value
a = binaryNumber.charAt(0);
int aInt = (a - 48) * 2 * 2* 2;
....
System.out.println(binaryNumber + " in decimal is: " + (aInt + bInt + cInt + dInt));
The problem is you are printing the a b c and d as chars so it will print what ever decimal value of a b c and d correspond to in the ascii table. If you want to print out decimals you will have to convert the value to decimal by subtracting 48 add them together and then print.
Has to be like this:
1010 = 8 + 0 + 2 + 0 = 10 then print 10. You are on the right track
get the numeric value and do multiplication, if you do with char it will use the ASCII value
int num = 0;
a = binaryNumber.charAt(0);
num += (Character.getNumericValue(a) * 2 * 2 * 2);
b = binaryNumber.charAt(1);
num += (Character.getNumericValue(b) * 2 * 2);
c = binaryNumber.charAt(2);
num += (Character.getNumericValue(c) * 2);
d = binaryNumber.charAt(3);
num += (Character.getNumericValue(d) * 1);
System.out.println(binaryNumber + " in decimal is: " + num);

A java console program that converts "BINARY" to "DECIMAL" without using a predefined method using for loop [duplicate]

This question already has answers here:
A java console program that converts decimal to binary without using a predefined method (for)
(2 answers)
Closed 6 years ago.
I made a java console program that prints the decimal value of the binary value inputted. Now, I have a problem with my program that
for e.g. output:
Enter input = 10011101 then the binary value is 3534200 instead of 157
After surfing the internet for the formula in converting binary value to decimal, this is the reference I took for making this program.
1*2^7 + 0*2^6 + 0*2^5 + 1*2^4 + 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0 = 157.
I tried the long version in making this program, in using for loop... I guess that's a dumb challenge? haha!
here's the code(w/ comments!):
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num = Integer.parseInt(new String(b.substring(b.length() - 1).trim()));
//num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
for(int a = i; a > 0; a--){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
num = Integer.parseInt(new String(b.substring(i - 1).trim())); //uhm dunno how to describe this, but you'll see
power = 2;
}
System.out.print(formula);
}
}
ever since I started using java, this is the only thing that I know. (refer to my last question since sep 4)
please help :(
You have a number of problems:
1) Integer.parseInt(new String(binary).trim()) does not do what you think it does. Therefore, your num is wrong.
2) You calculate your power wrong.
3) A general advice, put some empty lines to separate your code into small blocks that make sense. It will be easier on the eyes.
The fixed program should look like this:
public static void main(String[] args) throws IOException {
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num; //num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
power = 1;
num = Integer.parseInt(Character.toString(b.charAt(i-1)));
for(int a = i; a < b.length(); a++){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
}
System.out.print(formula);
}

Why is myArrayList.size(); producing incorrect/gigantic numbers?

Basically, I'm trying to write a program that converts a number from base 2 to base 10. What I tried doing was translating the process listed on this website under the "Doubling method" into a for loop, but for some reason the numbers I'm getting are way to big.
The basic formula is (2 * previousTotal) + (currentDigit of the ArrayList that holds the user's inputted binary number) = previousTotal.
So for 1011001 in binary, the math would be:
(0 x 2) + 1 = 1
(1 x 2) + 0 = 2
(2 x 2) + 1 = 5
(5 x 2) + 1 = 11
(11x 2) + 0 = 22
(22 x 2) + 0 = 44
(44 x 2) + 1 = 89
The console however, prints out 6185 as the result. I'm thinking it might have something to do with me using an ArrayList of characters, but the charWhole.size() returns 7, which is how many digits are in the user's binary number. As soon as I do charsWhole.get(w); however, I start getting big numbers such as 49. I'd really appreciate some help!
I wrote out this loop, and according to some print statements that I placed throughout the code and my variable addThis seems to be where the problem is. The console prints out a final total of 6185, when 1011001 in base 10 is actually 89.
public static void backto2(){
System.out.println("What base are you coming from?");
Scanner backToB10 = new Scanner(System.in);
int bringMeBack = backToB10.nextInt();
//whole
System.out.println("Please enter the whole number part of your number.");
Scanner eachDigit = new Scanner(System.in);
String theirNumber = eachDigit.nextLine();
String str = theirNumber;
ArrayList<Character> charsWhole = new ArrayList<Character>();
for (char testt : str.toCharArray()) {
charsWhole.add(testt);
}
System.out.println(theirNumber); // User's number
System.out.println(charsWhole); // User's number separated into elements of an ArrayList
System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.
int previousTotal = 0, addThis = 0, q =0;
for( int w = 0; w < charsWhole.size(); w ++) {
addThis = charsWhole.get(w); //current digit of arraylist PROBLEM
q = previousTotal *2;
previousTotal = q + addThis; // previous total gets updated
System.out.println(q);
System.out.println(addThis);
System.out.println(q + " and " + addThis + "equals " + previousTotal);
}
System.out.println(previousTotal);
You are attempting to add a character to an integer. The implicit conversion uses the ASCII value of the character, so that '1' gets converted to 49, not 1, because 49 is the code for the character '1'. Subtract '0' to get the actual integer value.
addThis = charsWhole.get(w) - '0';
This works because the digits 0-9 are represented in ASCII as the codes 48-57, so in effect you will, for '1', subtract 49 - 48 to get 1.
You'll still have to handle cases when the character is outside the range of allowable characters.
EDIT
Java uses Unicode, but for the purposes of the codes for the digits 0-9, the codes are the same (48 thru 57, or 0x30 thru 0x39) in both ASCII and Unicode.
The problem is that you're using the chars rather than the number value they represent. In the line
addThis = charsWhole.get(w);
the value of addThis is the ascii value of the character. For '0', this is 48. Use this instead:
addThis = Integer.parseInt(charsWhole.get(w));
Another suggestion to solve the same problem:
addThis = charsWhole.getNumericValue(w);
See here for more information.

Categories

Resources