首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加减法程序

问加减法程序
EN

Stack Overflow用户
提问于 2014-03-03 04:50:12
回答 1查看 2.3K关注 0票数 0

我对Java比较陌生,我正在尝试为我的计算机编程类编写一个程序,它将接受来自用户的字符串(字符串必须类似于1+2- 1),然后获取该字符串,使用分隔符去掉+/-符号,然后执行加法和减法,并返回字符串输入的总和。为此,我的程序必须运行一个while循环,每次发现一个整数时,它必须根据数字前面是+号还是-号来执行适当的函数。我尝试使用.findInLine让程序确定字符是+还是-,然后根据这个来加减后面的数字,但是在使用分隔符的情况下似乎不起作用,我不知道该怎么做。下面是我的代码:

代码语言:javascript
复制
import java.util.*;
import java.io.*;

public class Lesson17p1_ThuotteEmily
{
    public static void main(String args[])
    {
        Scanner kb=new Scanner(System.in);
        System.out.println("Enter something like 8 + 33 + 1,257 + 137");
        String s=kb.nextLine();

        Scanner sc=new Scanner(s);
        char c=sc.findInLine("\\+").charAt(0);
        sc.useDelimiter("\\s*\\+\\s*");

        double sum=0;
        while(sc.hasNextInt());
        {
            if(c=='+')
            {
                sum=sum+sc.nextInt();
                System.out.println(sum);
            }
        }

        System.out.println("Sum is: "+sum);
   }
}

我之前在程序中有-符号的代码,但暂时删除了它们,因为我想弄清楚如何让程序运行加法问题,然后我稍后会添加减法编程,使用与加法相同的方法。

我的代码可以很好地编译和运行,但是当它到达应该添加的部分,然后返回问题的总和时,它就会停止。它不会返回错误或任何东西,它只是冻结。我不太确定为什么会发生这样的事情。我可以删除一行中的find,但是我需要一个不同的方法,让程序来决定是加还是减,我正在努力想出任何东西。我还尝试重新排列代码,使其首先找到+或-号,然后使用分隔符去掉符号并继续进行加法或减法,但程序再次冻结。

您能提供的任何帮助都是非常感谢的!

EN

回答 1

Stack Overflow用户

发布于 2014-03-03 06:02:49

用注释重写了代码:

代码语言:javascript
复制
import java.util.Scanner;
import java.util.LinkedList;

public class AddSubstract {
  public static void main(String[] args) {
    Scanner userInputScanner = new Scanner(System.in);
    System.out.print("Type in an expression using + and - operators.\n>> ");
    String userInput = userInputScanner.nextLine();
    // our example input: "   35 - 245 + 34982  "

    userInput = userInput.trim();
    // input is now "35 - 245 + 34982"
    if(userInput.charAt(0) != '-') userInput = "+" + userInput;
    // we need to change the input to a set of operator-number pairs
    // input is now "+35 - 245 + 34982"
    int result = 0;
    // result
    byte sign = 0;
    // sign; 1 -> positive number, -1 -> negative number, 0 -> not yet checked
    int numberToPush = 0;
    for(char c : userInput.toCharArray()) {
      if(c == '+' || c == '-') {
        if(sign == 0) sign = (c == '+')?1:-1;
        else {
          result += sign*numberToPush;
          sign = (c == '+')?1:-1;
          numberToPush = 0;
        }
      } else if(c >= '0' && c <= '9') {
        numberToPush = ((int) c-'0') + 10*numberToPush;
      }
    }
    result += sign*numberToPush;
    System.out.println("The result is: "+result);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22133297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档