Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java计算负数_Java_Calculator - Fatal编程技术网

用Java计算负数

用Java计算负数,java,calculator,Java,Calculator,好的。。。我想绕开计算负数的概念。我是自学成才的,我遇到了很多困难。如何实施负投入 我的代码: public class MainSystem { public static void main(String[] args) { try (Scanner console = new Scanner(System.in)) { String input; System.out.print(">>> ");

好的。。。我想绕开计算负数的概念。我是自学成才的,我遇到了很多困难。如何实施负投入

我的代码:

public class MainSystem {

    public static void main(String[] args) {
        try (Scanner console = new Scanner(System.in)) {
            String input;

            System.out.print(">>> ");
            input = console.nextLine();
            splitEntry(input);

            System.out.println("The console is now closed.");
        }
    }

    private static void splitEntry(String input) {

        String function = "[+\\-*/]+"; //placing them in an index
        String[] token = input.split(function);//and this
        double num1 = Double.parseDouble(token[0]);
        double num2 = Double.parseDouble(token[1]);
        //double answer;
        String operator = input.toCharArray()[token[0].length()] + "";

        if (operator.matches(function) && (token[0] + token[1] + operator).length() == input.length()) {
            System.out.println("Operation is " + operator + ", your first number is " + token[0] + " your second number is " + token[1]);
        } else {
            System.out.println("Your entry of " + input + " is invalid");
        }
        if (operator.matches(function)
                && (token[0] + token[1] + operator).length() == input.length()) {
            double result = 0;
            if (operator.equals("+")) { // this is simplified by using formatters 
                result = num1 + num2;
            } else if (operator.equals("-")) {
                result = num1 - num2;
            } else if (operator.equals("*")) {
                result = num1 * num2;
            } else if (operator.equals("/")) {
                result = num1 / num2;
            }
            System.out.printf("Your first number %.2f %s by your second number %.2f = makes for %.2f%n", num1, operator, num2,
                    result);
        }
    }
}
我如何允许我的计算器放置-2+5并得到答案3


每次我这么做,程序都会崩溃?如何计算负数好的,我想我有办法。很抱歉回答晚了,我希望你仍然可以使用它。 首先让我解释一下,我修改了很多代码

扫描输入
输入将被读取为一个完整的字符串,就像在代码中一样。但是,我不是将代码拆分为
字符串[]
,而是逐个“检查”字符,并尝试确定它们是运算符还是数字

如果我找到一个数字或运算符,我会把它放在列表中而不是数组中,因为列表可以动态增长,我还不知道有多少个数字和运算符

private static ArrayList<String> getSequence(String input) {
    String number = "[\\d,.]+";     // RegEx to detect any number 12 or 1.2 or 1,2
    String function = "[+\\-*/]+";  // RegEx to detect any operator +-*/ 
    char[] inputChars = input.toCharArray();   // converting the input String into an array
    ArrayList<String> sequence = new ArrayList<>();  // this is the list, that will be returned
    String lastNumber = "";     // a number can consist of multiple chars, so this String is like a buffer for us where we "collect" every char until the number is complete

    for (char c : inputChars) {  // now we loop through every char in the char[]
        System.out.println("checking " + c);
        if ((new String("" + c)).matches(function)) {  // we convert our char into a String and try to match it with the "function" RegEx
            System.out.println("its an operator");
            if (!lastNumber.isEmpty()) {
                sequence.add(lastNumber); // if we detect an operator, we must check if we still have a number in our buffer. So we add the last number to our list
            }
            sequence.add("" + c);  // and we add our operator to our list
            lastNumber = "";       // we just saw an operator, so the "lastNumber" buffer should be cleared
        } else if ((new String("" + c)).matches(number)) {  // if we detect a digit/number
            System.out.println("its part of a number");
            lastNumber += c; // since this char is part of a number, we add it to the "lastNumber" buffer
            // now we need to continue, since we don't know if the number is already finished 
        }
    }
    // if we finished analyzing the char array, there might be a last number in our buffer
    if (!lastNumber.isEmpty()) {  
        sequence.add(lastNumber);  // the last number will be added too
    }
    return sequence;  // now our sequence is complete and we return it
}
评估序列
接下来我们调用方法
evaluate(sequence)
来评估我们的列表。这很接近你的方式,我只是做了一些调整

 private static void evaluate(ArrayList<String> sequence) {
    double number1 = 0.0;    // the first number is also a intermediary result
    while (true) {           // we actually don't know how long the equation is, so here we have an infinite-loop. Usually not a good idea!
        try {                // we try to evaluate the next String of our sequence
            number1 = getNextNumber(sequence);  // get the next number 
            System.out.println("number1 = " + number1);
            char operator = getNextOperator(sequence);  // get the next operator
            System.out.println("operator = " + operator);
            double number2 = getNextNumber(sequence);
            System.out.println("number2 = " + number2);  // get the second number
            switch (operator) {   // I replaced your if statements with that switch (but it is actually the same)
                case '+':
                    number1 += number2;  // we add the second number to the first number and "store" the result in the first number
                    break;
                case '-':
                    number1 -= number2;
                    break;
                case '*':
                    number1 *= number2;
                    break;
                case '/':
                    number1 /= number2;
                    break;
            }
        } catch (java.lang.IndexOutOfBoundsException e) {  // here we break out of the loop. We can be 100% sure that at some point we reached the end of the list. So when we are at the end of the list and try to access the "next" element of the list (which does of course not exist) we get that IndexOutOfBoundsException and we know, we are finished here
            System.out.println("result is " + number1);
            break;  // break out of the loop
        }
    }
}
这里使用了一个很好的技巧:
sequence.get(0)
将查看列表中的第一个元素并返回其值。但是
sequence.remove(0)
将返回其值,同时从列表中删除元素。因此,原来的第一个元素将不再存在,先前的第二个元素将成为第一个

因此,首先我们的列表看起来像
{-”,“2”}
,在调用
getNextOperator()
之后,它看起来像
{“2”}
,因为我们删除了操作符

我们在获取下一个数字时也会这样做:

private static double getNextNumber(ArrayList<String> sequence) {
    String sign = "[+-]+";   // regex to test if a string is only a sign (+ or -)
    String number = "[\\d,.]+";  //regex to test if a String is a number (with or without . or  ,
    double number1 = 0;
    if (sequence.get(0).matches(sign) && sequence.get(1).matches(number)) {
        // first one should be a sign and the second one a number
        number1 = Double.parseDouble(sequence.remove(0) + sequence.remove(0));
    } else if (sequence.get(0).matches(number)) {
        // its a normal number
        number1 = Double.parseDouble(sequence.remove(0));
    }
    return number1;
}
私有静态双getNextNumber(ArrayList序列){
String sign=“[+-]+”;//用于测试字符串是否只是符号(+或-)的正则表达式
String number=“[\\d,.]+”;//用于测试字符串是否为数字的正则表达式(带或不带.或,
双数1=0;
if(sequence.get(0).matches(符号)和sequence.get(1.matches(数字)){
//第一个应该是符号,第二个应该是数字
number1=Double.parseDouble(sequence.remove(0)+sequence.remove(0));
}else if(sequence.get(0).matches(number)){
//这是一个正常的数字
number1=Double.parseDouble(sequence.remove(0));
}
返回编号1;
}
好的,就是这样。现在你只需要把它放在一起,在你的主函数中调用它,如下所示:

public static void main(String[] args) {
    try (Scanner console = new Scanner(System.in)) {
        String input;

        System.out.print(">>> ");
        input = console.nextLine();
        ArrayList<String> sequence = getSequence(input);  // analyze input and get a list
        evaluate(sequence);  // evaluate the list
        System.out.println("The console is now closed.");
    }
}
publicstaticvoidmain(字符串[]args){
try(扫描仪控制台=新扫描仪(System.in)){
字符串输入;
系统输出打印(“>>>”);
input=console.nextLine();
ArrayList sequence=getSequence(输入);//分析输入并获取列表
评估(序列);//评估列表
System.out.println(“控制台现在关闭”);
}
}
嗯,很抱歉更改了这么多。我想不出另一种(可能更有效)的方法来实现这一点。这个计算器现在不是很“智能”,而且有很多事情它无法处理(比如字母或大括号)但我希望这只是一个开始。至少现在它应该可以处理负数和正数,并且应该能够处理更长的方程


干杯!

stacktrace会有帮助。
它为什么会崩溃?
它会告诉你为什么。也许阅读stacktrace是个好主意?顺便说一句,请修复你的代码…一个
main
方法中的类?你在这里没有得到任何错误
splitEntry(input);
输入没有任何价值。我想结束您的问题:为什么您不能通过执行
Float num1=new Float(令牌[0])将您的令牌转换为Float
?在这种情况下,它保留了符号和值,也为您提供了正确的结果。其中有许多我不太了解的新概念,但我想我最好开始学习,谢谢。如果这个答案中有什么您不理解的地方,请毫不犹豫地问。有了您的计算器,您有一个非常有趣的项目,bu这也很难:)我再次修改了我的全部代码。我再次需要你的帮助@当然,如果您有一个与此问题无关的问题,只需打开一个新问题并将更改后的代码张贴在那里。@Integral如果您愿意,我还打开了一个关于StackOverflow的聊天。所以我们不需要一直使用评论
private static double getNextNumber(ArrayList<String> sequence) {
    String sign = "[+-]+";   // regex to test if a string is only a sign (+ or -)
    String number = "[\\d,.]+";  //regex to test if a String is a number (with or without . or  ,
    double number1 = 0;
    if (sequence.get(0).matches(sign) && sequence.get(1).matches(number)) {
        // first one should be a sign and the second one a number
        number1 = Double.parseDouble(sequence.remove(0) + sequence.remove(0));
    } else if (sequence.get(0).matches(number)) {
        // its a normal number
        number1 = Double.parseDouble(sequence.remove(0));
    }
    return number1;
}
public static void main(String[] args) {
    try (Scanner console = new Scanner(System.in)) {
        String input;

        System.out.print(">>> ");
        input = console.nextLine();
        ArrayList<String> sequence = getSequence(input);  // analyze input and get a list
        evaluate(sequence);  // evaluate the list
        System.out.println("The console is now closed.");
    }
}