code
package javahomework; import javax.swing.JOptionPane; public class HW17 { static int toNumber(char array[], int begin, int end) { String temp = ""; for (int i = begin; i < end; i++) temp += array[i]; return Integer.parseInt(temp); } static long sum_number(String input) { int index = 0; long sum = 0; char a[] = input.toCharArray(); for (int i = 0; i < a.length; i++) { switch (a[i]) { case '+': // A+B sum += toNumber(a, 0, i) + toNumber(a, i + 1, a.length); break; case '-': // A-B sum += toNumber(a, 0, i) - toNumber(a, i + 1, a.length); break; } index++; } return sum; } public static void main(String args[]) { String input = JOptionPane.showInputDialog(null, "Please input 1+2 or 1-2"); JOptionPane.showMessageDialog(null, String.valueOf(sum_number(input))); } }
沒有留言:
張貼留言