湖南省第六屆 中信軟體教育杯 大學生程式設計大賽試題 第二題 弟弟的作業
阿新 • • 發佈:2019-02-02
弟弟的作業 |
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 |
分析:簡單的字串處理題目
原始碼:
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); } }