弟弟的作业
题目描述
Rock的弟弟刚做完了“100以内数的加减法”这部分的作业,请你帮他检查一下。每道题目(包括弟弟的答案)的格式为a + b = c或者a – b = c,其中a和b是作业中给出的,均为不超过100的非负整数;c是弟弟算出的答案,可能是不超过200的非负整数,也可能是单个字符"?",表示他不会算。
输入
输入数据包含多组,每组数据占一行,每行包含一道题目,格式保证符合上述规定,且不包含任何空白字符。输入的所有整数均不含前导0。
输出
输出仅一行,包含一个非负整数,即弟弟答对的题目数量。
样例输入 Copy
1+2=3
3-1=5
6+7=?
99-0=99
样例输出 Copy
2
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int sum = 0;
while (scan.hasNext()) {
String str = scan.nextLine();
if (!str.contains("?")){
int x = str.indexOf('+');
int y = str.indexOf('-');
int z = Integer.parseInt(str.substring(str.indexOf('=') + 1));//提取等号后一位的数字字符串并转换为数字型
boolean flag = true;//判断弟弟计算是否正确
if (x != -1) {
if (Integer.valueOf(str.substring(0, x))
+ Integer.valueOf(str.substring(x + 1,
str.lastIndexOf('='))) == z)
flag = true;
else
flag=false;
} else {
if (Integer.valueOf(str.substring(0, y))
- Integer.valueOf(str.substring(y + 1,
str.lastIndexOf('='))) == z)
flag = true;
else
flag=false;
}
if (flag == true) {
sum++;//计数
}
}
}System.out.println(sum);
}
}
简易版
题目描述
Rock的弟弟刚做完了“100以内数的加法”这部分的作业,请你帮他检查一下。每道题目(包括弟弟的答案)的格式为a + b = c,其中a和b是作业中给出的,均为不超过100的非负整数;c是弟弟算出的答案,是不超过200的非负整数。
输入
输入数据包含多组,每组数据占一行,每行包含一道题目,格式保证符合上述规定,且不包含任何空白字符。输入的所有整数均不含前导0。
输出
对于每个输入算式,如果算式正确输出“Yes”,否则输出“No”。
样例输入 Copy
1+2=3
3-1=5
样例输出 Copy
Yes
No
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
int x = str.indexOf('+');
int y = str.indexOf('-');
int z = Integer.parseInt(str.substring(str.indexOf('=') + 1));
boolean flag = true;
if (x != -1) {
if (Integer.valueOf(str.substring(0, x))
+ Integer.valueOf(str.substring(x + 1,
str.lastIndexOf('='))) == z)
flag = true;
else
flag=false;
} else {
if (Integer.valueOf(str.substring(0, y))
- Integer.valueOf(str.substring(y + 1,
str.lastIndexOf('='))) == z)
flag = true;
else
flag=false;
}
if (flag == true) {
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
}
//就简易在不用考虑字符串最后一位是不是“?”