Recorded because I used the getNumericValue method for the first time.
-Receive the calculation formula with a character string of any length (all numbers used are 1 digit, operators are only'+' and'-') ・ Calculate the received character string as a numerical value ・ Output the calculation result
(Example) Input: "1 + 2 + 3" Output: 6
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
sc.close();
char [] c = line.toCharArray();
int sum = 0;
boolean add = true;
for(int i = 0; i < line.length(); i++) {
if(i % 2 == 0) {//Even numbers are calculated because numbers and operators alternate.,Odd numbers swap operators
if(add) {
int n = c[i];
sum += n;
} else {
int n = c[i];
sum -= n;
}
} else {
if(c[i] == '+') {
add = true;
} else {
add = false;
}
}
}
System.out.println(sum);
Input: "1 + 2 + 3" Output: 150
-When the numerical value put in the char type array is converted to int type, it is assigned by ASCII character code. → I want to take out the numbers in the array as they look!
if(add) {
int n = Character.getNumericValue(c[i]);
sum += n;
} else {
int n = Character.getNumericValue(c[i]);
sum -= n;
}
Input: "1 + 2 + 3" Output: 6
If you want to use the char type number as it is, use the Character type getNumericValue ().
if(c[i] == '+') {
add = true;
} else {
add = false;
}
In the above part, the comparison operator returns a boolean type, so you can determine the truth by assigning it directly to add.
add = c[i] == '+';
Recommended Posts