the instructions are: Enter an integer (32 bit) and sum its digits, you may be given a negative or positive integer. When reading in a negative integer, sum the digits but ignore the – sign.
this is what I have. Somehow I can’t get it to ignore the negative signs when the integer is negative.
import java.util.Scanner;
public class Exercise2_6M {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter amount
System.out.print("Enter an integer:");
int integer = input.nextInt();
if (integer < 0)
integer = -integer;
// Calculations
int rinteger = Math. abs (integer);
int lastinteger = integer % 10;
int X = integer / 10;
int secondinteger= X % 10;
int firstinteger = X /10;
int finalinteger = firstinteger + secondinteger + lastinteger;
// Display results
System.out.println("Sum all digits in " + rinteger + " is " + finalinteger);
}
}
To ignore the negative sign:
Edit:
I didn’t notice that your code already did this. To make the code show the negative sign at the end, get rid of the following lines:
since you’re already doing
Then, replace all instances other than the fist of
integerin the calculations sections with rinteger, like thisFinally, when displaying the results, use integer instead of rinteger to restore the minus sign, or just put in a minus sign manually if
integer<0.Your code is also flawed if integer is more than 3 digits, as others have pointed out, but that’s a separate issue.
To add more than 3 digits, you’ll need a loop. Try this: