用java编程100道问题//10弟弟的作业,口算训练

弟弟的作业

题目描述

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

//就简易在不用考虑字符串最后一位是不是“?”

大吉大利今晚AC

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值