您的位置:首页 > 编程语言 > PHP开发

湖南省第六届 中信软件教育杯 大学生程序设计大赛试题 第二题 弟弟的作业

2011-08-28 10:43 429 查看
 
弟弟的作业
Time Limit: 1000ms, Special Time Limit:2500ms,Memory Limit:65536KB

Total submit users: 24, Accepted users:22

Problem 10931 : No special judgement
Problem description
  你的弟弟刚做完了“100以内数的加减法”这部分的作业,请你帮他检查一下。每道题目(包括弟弟的答案)的格式为a+b=c或者a-b=c,其中a和b是作业中给出的,均为不超过100的非负整数;c是弟弟算出的答案,可能是不超过200的非负整数,也可能是单个字符"?",表示他不会算。
Input
  输入文件包含不超过100行,以文件结束符结尾。每行包含一道题目,格式保证符合上述规定,且不包含任何空白字符。输入的所有整数均不含前导0。
Output
  输出仅一行,包含一个非负整数,即弟弟答对的题目数量。
Sample Input
1+2=3
3-1=5
6+7=?
99-0=99
Sample Output
2
Problem Source
  The Sixth Hunan Collegiate Programming Contest
 

题目连接:http://acm.hunnu.edu.cn/online/?action=problem&type=show&id=10931

 

分析:简单的字符串处理题目

 

源代码:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

int count = 0;

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {

String str = scanner.next();

int opIndex = str.indexOf("+");// 返回出现操作符+ -的字符串位置-1表示没有找到

if (opIndex == -1) {

opIndex = str.indexOf("-");

}

int eqPos = str.indexOf("=");

// System.out.println(opIndex);

// System.out.println(eqPos);

String aStr = str.substring(0, opIndex);// 取a的字符串

String bStr = str.substring(opIndex + 1, eqPos);// 取b的字符串

String resultStr = str.substring(eqPos + 1);// 结果的字符串

int a = Integer.parseInt(aStr);

int b = Integer.parseInt(bStr);

int c;

if (!resultStr .endsWith("?") ) {

c = Integer.parseInt(resultStr);

} else {

c = -32768;

}

char op = str.charAt(opIndex);

// System.out.println(op);

if (op == '+' && c == a + b) {

count++;

} else if (op == '-' && c == a - b) {

count++;

}

// System.out.println(aStr);

// System.out.println(bStr);

// System.out.println(resultStr);

}

System.out.println(count);

}

}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐