Java addition giving wrong answer - java

I am trying to add four integers ie 4+3+2+1 but i get the value 202
class Task3{
public static void main (String args[]){
String x=(args[0]);
int I = Integer.parseInt (x);
char c1 = x.charAt(0);
char c2 = x.charAt(1);
char c3 = x.charAt(2);
char c4 = x.charAt(3);
System.out.println("First and last digit is: " + c1 +"," + c4);
if (c1 > c4)
System.out.println("The first digit is larger");
else
System.out.println("The second digit is larger");
int sum = c1 + c2 + c3 + c4;
System.out.println(sum);
}
}

replace char c1 = x.charAt(0); with Character.getNumericValue(x.charAt(0))

This is because you are adding numeric values of UNICODE code points, not digits represented by the corresponding characters.
In order to get a digit from a character code, call Character.digit(c1, 10) (ten indicates that you want a decimal digit).
int c1 = Character.digit(x.charAt(0), 10);
int c2 = Character.digit(x.charAt(1), 10);
int c3 = Character.digit(x.charAt(2), 10);
int c4 = Character.digit(x.charAt(3), 10);

Change
int sum = c1 + c2 + c3 + c4;
to
int sum = c1 + c2 + c3 + c4 - 4 * '0';
Since c1, c2, c3, c4 are all characters, so a digit say. 4 is taken as '4' that is basically the ASCII value, so to get 4 and not '4' you need to subtract '0' from each of c1, c2, c3, c4, so 4 * '0' subtracted

You are trying to sum up the chars ASCII codes and not the digit values. You have to retrieve the corresponding digit for each character and then evaluate you addition result:
class Task3
{
public static void main (String args[])
{
String x=(args[0]);
int I = Integer.parseInt (x);
char c1 = x.charAt(0);
char c2 = x.charAt(1);
char c3 = x.charAt(2);
char c4 = x.charAt(3);
int i1 = Character.digit(c1, 10);
int i2 = Character.digit(c2, 10);
int i3 = Character.digit(c3, 10);
int i4 = Character.digit(c4, 10);
System.out.println("First and last digit is: " + i1 +"," + i4);
if (i1 > i4)
System.out.println("The first digit is larger");
else
System.out.println("The second digit is larger");
int sum = i1 + i2 + i3 + i4;
System.out.println(sum);
}
}

The reason of the wrong output others already explained it now one of the way to get the correct output
int sum =0;
while(I>0){
int rem = I%10;
sum+=rem;
I = I/10;
}
System.out.println(sum);

I presume you are passing "4321" or similar to the program.
c1 will not be the number 1 but actually the Unicode number representing the character '1' which is actually 31 (in hexadecimal). The latest addition is adding these Unicode numbers.
See http://unicode-table.com/en/ for the list of unicode numbers to characters and also http://docs.oracle.com/javase/tutorial/i18n/text/unicode.html for more details of characters in Java.

Related

Java Char addition makes no sense (to me)

So I have this code here:
char a = '1';
char b = '2';
System.out.println(a+b); \\ Outputs 99
I want to know why, since this code:
char a = '1' + '2';
System.out.println(a); \\ Outputs c
I want to enhance my primitive mind, please help a kindred spirit.
characters hold an value in real;
when you write
char a = 49;
char k = '1'; // both of them holds same character because '1' code in ascii 49
and when you treat two variable in arithmetic operation and if one of them type is(byte, short, or char) these types promote in int so
System.out.println(a+b); // both of them promote int
char c = a + b; // assign c, 99 which represents 'c'
They are being added as their decimal numeric ASCII value.
The portion of the code that does a+b implicitly is adding them as integers. So, if you run the following code:
class Example {
public static void main(String[] args) {
char ch = '1';
char ch2 = '2';
int num = ch;
int num2 = ch2;
System.out.println("ASCII value of char " + ch + " is: " + num);
System.out.println("ASCII value of char " + ch2 + " is: " + num2);
}
}
You will see that the output of each char is
ASCII value of char 1 is: 49
ASCII value of char 2 is: 50
So when you do this System.out.println(a+b); they get added as their integer value which turns out to be 99

Sum the digits in a string

I wrote a program that sums the int values in a String. I'm getting the wrong output though. I can't quite figure out the issue. The expected output should be 23 and 29 but I am getting 263 and 269. Any suggestions would be helpful; it seems it is putting a 6 between my outputs for some reason.
public class ParseString
{
String str;
public ParseString(String x)
{
this.str = x;
}
public int sumOfAllDigits()
{
int total = 0;
char[] arr = new char[this.str.length()];
for(int i = 0; i < this.str.length(); i++)
{
arr[i] = this.str.charAt(i);
}
for(int i = 0; i < arr.length; i++)
{
if(arr[i] >= '0' && arr[i] <= '9')
{
total = total + arr[i];
}
}
return total;
}
public class TestParseString
{
public static void main(String[] args)
{
String s1 = "AB458JK2L#4";
ParseString ps1 = new ParseString(s1);
System.out.println("Sum of all digits in \"" + s1 + "\" is: ");
System.out.println(ps1.sumOfAllDigits());
System.out.println();
String s2 = "8927KL3PY";
ParseString ps2 = new ParseString(s2);
System.out.println("Sum of all digits in \"" + s2 + "\" is: ");
System.out.println(ps2.sumOfAllDigits());
}
}
It's not that a 6 is inserted into your sum; it's that your sum is 240 too high. There are 5 digits in each of your test strings. What is missing here is what goes on in the conversion between char and int. A '0' is not 0; when a char is widened to an int for summing, it takes the ASCII value, which for numbers is the represented number plus 48. E.g. '0' -> 48, '1' -> 49, etc.
An extra 48 added 5 times yields an extra 240.
Because the digits are coded in order starting with '0' at 48, you can subtract '0' to take away the unwanted 48.
total = total + arr[i] - '0';
As an aside, as already mentioned in the comments on the question, toCharArray() gets you the char[] for a String more easily than manually copying each character.
The problem lies here:
total = total + arr[i];
arr[i] is a char. When you use the + operator on it, with the other operand being an int, you are actually adding the ASCII value of the character, which is 48 to 57 for 0 to 9.
You think you are doing this:
4 + 5 + 8 + 2 + 4
But actually the program is doing:
52 + 53 + 56 + 50 + 52
So that's why you get such a large number.
You need to parse the characters to get the correct output. One way to do this is to just subtract 48!
total = total + (arr[i] - 48);
Or you can convert it to a string first, then parse it as an int:
total = total + Integer.parseInt(Character.toString(arr[i]));

Calculating the ISBN Number check digit using Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to calculate any ISBN-13 Number's Check Digit, I'm not too worried if the ISBN number is valid or invalid, but what I've been trying to do is get the code to work. There are obviously flaws in my interpretation of the algorithm, suggestions on how to fix it are welcome but the primary problem is receiving user input that is too large for an integer variable but I also want to avoid the decimals of the double value.
I already tried to use the BigDecimal and BigNumber but I simply don't have enough experience to be able to understand them completely. This is the algorithm to find d13 (the Check Digit): 10-(d1 +3d2 +d3 +3d4 +d5 +3d6 +d7 +3d8 +d9 +3d10 +d11 +3d12)%10.
The Code is a mess I know. I've used this website as a reference to what I want to do and I've been using this ISBN number as my practice: 9780132130806.
Again my question is how can I print the final ISBN number without decimals and how can I possibly fix my algorithm? (I'd also really appreciate any tips on a website that helps with teaching JOption as that is the prefered method i use because it looks a bit cleaner to me than using the scanner)
import javax.swing.JOptionPane;
import java.math.BigInteger;
public class ISBN
{
//George Sayegh Calculate check Digit ISBN
public static void main(String[] args)
{
//Define Variables
double ISBN12, D1, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11, D12 = 0, D13;
double A = 100000000000L;
double B = 10000000000L;
double C = 1000000000;
double D = 100000000;
double E = 10000000;
double F = 1000000;
double G = 100000;
double H = 10000;
double I = 1000;
double J = 100;
double K = 10;
double L = 1;
//Get ISBN #
String ISBN12text = JOptionPane.showInputDialog("Please enter the first 12 digits of your ISBN number");
ISBN12 = Double.parseDouble(ISBN12text);
//Calculate D1
D1 = ((ISBN12 - (ISBN12 % A)) / A);
//Calculate D2
D2 = ((ISBN12 - (ISBN12 % B)) / B);
//Calculate D3
D3 = ((ISBN12 - (ISBN12 % C)) / C);
//Calculate D4
D4 = ((ISBN12 - (ISBN12 % D)) / D);
//Calculate D5
D5 = ((ISBN12 - (ISBN12 % E)) / E);
//Calculate D6
D6 = ((ISBN12 - (ISBN12 % F)) / F);
//Calculate D7
D7 = ((ISBN12 - (ISBN12 % G)) / G);
//Calculate D8
D8 = ((ISBN12 - (ISBN12 % H)) / H);
//Calculate D9
D9 = ((ISBN12 - (ISBN12 % I)) / J);
//Calculate D10
D10 = ((ISBN12 - (ISBN12 % K)) / K);
//Calculate D11
D11 = ((ISBN12 - (ISBN12 % L)) / L);
//Get D13
D13 = 10 - (D1 + (3 * D2) + D3 + 3 * D4 + D5 + 3 * D6 + D7 + 3 * D8 + D9 + 3 * 10 + D11 + 3 * D12) % 10;
JOptionPane.showMessageDialog(null, D1 +""+ D2 +""+ D3 +""+ D4 +""+ D5 +""+ D6 +""+ D7 +""+ D8 +""+ D9 +""+ D10 +""+ D11 +""+ D12 +""+ 13);
}
}
Try this extremely simple algorithm (written in Python, but it should be very easy to convert to Java). The comments hopefully explain enough. Should convert to not more than 10 lines (not including blank lines for readability)
#// Valid ISBN-12 string from user (12 numbers, doesn't matter what other characters)
isbn12 = '978-0-306-40615' #// Input it from the user, hardcoded Wikipedia example for testing
coeff = 1 #// Multiple used in calculating sum
sum = 0
for d in isbn12: #// Equivalent to for(char d : isbn12.toCharArray())
#// this next block is just a tryParse or an isDigit check
#// if the character is a digit, parse it to an int
#// else continue to next iteration
try:
#// just reassigning the value because-
#// Hey, this is Python!
d = int(d)
except ValueError:
continue
#// Add to sum after multiplying with coeff
sum += d * coeff
#// If coeff was 1, change to 3 and vice versa
#// Equivalent to coeff == 1 ? 3 : 1 in Java
coeff = 3 if coeff == 1 else 1
#// END FOR LOOP
#// Get positive number to be added to make ISBN divisible by 10
#// The extra % 10 at the end is for changing 10 to 0 without if
check_digit = (10 - sum % 10) % 10
(The extra // at the start of each comment is to make SO code formatting think it is a comment)
Here's a much simpler implementation based on this Wikipedia example. It lacks sanity checks---such as whether the input string is a valid ISBN13---but should be enough to get you going. I hope it helps.
Note that the input is an ISBN-13 string with the check digit removed (e.g. 978013213080 instead of 9780132130806); the program prints the check digit on the output; you should be able modify it if this is not what you want.
public class CheckISBN13 {
/* We assume isbnString is a *valid* ISBN-13 with the check digit removed. */
public static int[] stringToInt(String isbnString) {
int[] isbnInt = new int[12];
int j = 0;
for (int i = 0; i < isbnString.length(); ++i) {
if (Character.isDigit(isbnString.charAt(i))) {
isbnInt[j++] = Character.getNumericValue(isbnString.charAt(i));
}
}
return isbnInt;
}
public static int getCheckDigit(int[] isbnInt) {
int val = 0;
for (int i = 0; i < isbnInt.length; ++i) {
int coeff = (i % 2 == 0 ? 1 : 3);
val += coeff * isbnInt[i];
}
return 10 - (val % 10);
}
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Usage: java CheckISBN13 978-0-306-40615");
System.exit(-1);
}
String isbnString = args[0];
int[] isbnInt = stringToInt(isbnString);
System.out.println("Check digit: " + getCheckDigit(isbnInt));
}
}

Not getting the result what I want in java by using array and string?

Input:-
agxgw
3
2 4
2 5
7 14
Output:-
Yes
No
Yes
I just answer with “Yes” or “No” using the following rule: I will just select two integers a and b, if the element at the position a is same as the element as position b in the non-ending chant. Answer Yes, otherwise say No.
Code:
import java.util.Scanner;
public class Gf {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String k=sc.next();
int k1=k.length();
int a=sc.nextInt();
for (int i =0; i <a; i++) {
int b=sc.nextInt();
int b1=b%k1;
int c=sc.nextInt();
int c1=c%k1;
if(k.charAt(b1)==k.charAt(c1)) {
System.out.println("yes");
} else {
System.out.println("No");
}
}
}
}
String#charAt is zero-index based, and the values in b1 and c1 assume it's one-index based.
Solution: decrease b1 and c1 before evaluating k#charAt. Do this only if their values are greater than zero.
int b=sc.nextInt();
int b1=b%k1;
int c=sc.nextInt();
int c1=c%k1;
b1 = b1 == 0 ? k1 - 1 : b1 - 1;
c1 = c1 == 0 ? k1 - 1 : c1 - 1;
Once you get the char b1 and c1.
then you just need to find weather chars in string k = "agxgw" are at position b1 and c1 are same or not. Now string k is small but integers b1 and c1 can be bigger than its length.
So just calculate the mod of of string length b1 and c1 and then compare if chars are same or not.
for example:
mod can be calculated with % operator.
m1 = b1 % stringlength of k
m2 = c1 % stringlength ok k
now char m1 and m2 are smaller than stringlength of k
so just compare if both are same or not.
you can rewrite part of your code like this:
int b = sc.nextInt() - 1;
int b1 = b % k1;
int c = sc.nextInt() - 1;
int c1 = c % k1;
The reason is that the index of Java's array starts with zero.

Decimal Conversion error

I am writing a program that will convert octal numbers to decimals. It compiles right and everything but there is something majorily wrong with my conversion code. It seems perfectly logic to me, however somehow when I run the program the conversions are wrong (i.e. 1 is converted to 36) can someone point out what is going wrong?
public static int convert(int octal)
{
int d1=0,d2=0,d3=0,d4=0,d5=0,d6=0,d7=0,d8=0;
if(octal >=9999999){
d8 = (octal-(octal%10000000));}
if(octal >=999999){
d7 = (octal-(octal%1000000));}
if(octal >=99999){
d6 = (octal-(octal%100000));}
if(octal >=9999){
d5 = (octal-(octal%10000));}
if(octal >= 999){
d4 = (octal-(octal%1000));}
if(octal >= 99){
d3 = (octal-(octal%100));}
if(octal >= 9){
d2 = (octal-(octal%10));}
if(octal >= 0){
d1 = (octal-(octal%1));}
octal = (d8 * 8^7) + (d7 * 8^6) + (d6 * 8^5) + (d5 * 8^4) + (d4 * 8^3) + (d3 * 8^2) + (d2 * 8^1) + (d1 * 8^0);
return octal;
}
this is just my convert method, my main method is what collects the
int octal;
This is the problem:
8^7
The ^ operator doesn't do what you think it does. It does binary XOR...
However, I'd say that the whole design is distinctly suspect. An int value isn't "in" octal or any other base - it's just an integer. The number ten is the number ten, whether that's exressed as "10" in decimal, "A" in hex or "12" in octal. If you've got a sequence of characters which you want to parse as octal digits, the input to the method should be a String, not an int.
Since your method accepts an integer (commonly represented in a String representation as decimal), and what you're outputting is also an integer, you've not really turned into "an octal integer", you've changed it into some other integer completely. You're trying to correctly convert your integer into an octal, and then incorrectly interpreting that octal as a decimal.
If wish to convert an integer into it's octal string representation, you could simply use the following method:
public static String convert(int number) {
Integer.toOctalString(number);
}
And, if you truly want to return an int that represents that octal String parsed as if it was decimal, you could simply do this:
public static int convert(int number) {
return Integer.parseInt(Integer.toOctalString(number));
}
If you have repetitive code, you might consider a loop.
public static void main(String... args) {
for (long i = 7, j = 7; i > 0; i = i * 10 + 1, j = j * 8 + 1) {
long c = convert(i);
if (c != j)
throw new AssertionError(i + ": " + c + " != " + j);
System.out.println(i + " = > " + j);
}
}
public static long convert(long octal) {
long ret = 0;
for (long i = 1000000000000000000L, j = 1L << (3 * 18); i > 0; i /= 10, j >>= 3)
ret += j * (octal / i % 10);
return ret;
}
prints
7 = > 7
71 = > 57
711 = > 457
7111 = > 3657
71111 = > 29257
711111 = > 234057
7111111 = > 1872457
71111111 = > 14979657
711111111 = > 119837257
7111111111 = > 958698057
71111111111 = > 7669584457
711111111111 = > 61356675657
7111111111111 = > 490853405257
71111111111111 = > 3926827242057
711111111111111 = > 31414617936457
7111111111111111 = > 251316943491657
71111111111111111 = > 2010535547933257
711111111111111111 = > 16084284383466057
7111111111111111111 = > 128674275067728457
You have an underlying misconception that's going to keep messing you up.
There is no such thing as an "octal number", per se. An int isn't decimal, or roman numerals, or octal - it's just a number.
An "octal number" really means "a string containing the octal representation of a number".

Categories