有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

蓝色鹈鹕爪哇教科书第17课项目附录

所以我的老师给了我一个作业(如下所示),我试着去做,但就是想不出来,下面是作业:

考虑下面的程序,允许从键盘输入8 + 33+1345+137,扫描对象然后使用加号(和任何相邻的空白)作为定界符,并产生这些数字的总和(1523)。p>

import java.io.*;

import java.util.*; 

public class Tester 

{ 

 public static void main(String args[]) 

 { 

 Scanner kb = new Scanner(System.in); 



 System.out.print("Enter something like 8 + 33 + 1,345 +137 : "); 

 String s = kb.nextLine( ); //Best to store in a String and then create a new Scanner 

 //object; otherwise, it can get stuck waiting for input. 

 Scanner sc = new Scanner(s); 

 //Set delimiters to a plus sign surrounded by any amount of white space...or... 

 // a minus sign surrounded by any amount of white space. 

 sc.useDelimiter("\\s*\\+\\s*"); 



 int sum = 0; 

 while(sc.hasNextInt( )) 

 { 

 sum = sum + sc.nextInt( ); 

 } 

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



 } 

}

现在将程序修改为允许加号或减号

^^^^这就是任务^^^

以下是我的源代码:

//I can't get it to work if I use subtraction and addition at the same time but they work separately

import java.util.Scanner;

public class AddEmUp {

    public static void main(String[] args) {

        //Here we create a String
        Scanner kb = new Scanner(System.in);
        System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
        String s = kb.nextLine();

        //Now we convert the String to a scanner because we will be using Scanner methods
        Scanner sc = new Scanner(s);

        //Creates sum
        int sum = 0;

        //Does it's magic if it is addition
        if (s.contains("+")) {
            sc.useDelimiter("\\s*\\+\\s*");
            while (sc.hasNextInt()) {
                sum = sum + sc.nextInt();
            }
        }

        //Does it's magic if it is subtraction
        if (s.contains("-")) {
            sc.useDelimiter("\\s*\\-\\s*");
            while (sc.hasNextInt()) {
                sum = sc.nextInt();
                sum = sum - sc.nextInt();
            }
        }

        //Prints the magic
        System.out.println("Sum is: " + sum);
    }
}

有人能帮我解决这个问题吗(我源代码中的第一条注释)


共 (1) 个答案

  1. # 1 楼答案

    我将帮助你以一种(希望)与你迄今为止所学到的一致的方式来回答这个问题。由于您尚未了解数组,并且正在使用带有分隔符模式的Scanner,因此我们必须解决这个约束

    首先,为了学校作业的目的,我们可以有把握地假设你的输入将遵循特定的模式,大致如下:(number)(operator)(number)(operator)(number)...等等;此外,您可能不担心输入检查(确保没有字母/符号等)或负数,因此我们将忽略这些场景。因为您只处理+-,所以分隔符分别是"\\s*\\+\\s*""\\s*\\-\\s*"。由于这些值不会改变(它们是常量),而且(在实际程序中)会在不同的地方多次使用,因此我们通常将它们存储在它们自己的final变量中:

    final String PLUS = "\\s*\\+\\s*"; // by convention, constants in java are named with all caps
    final String MINUS = "\\s*\\-\\s*";
    

    现在,让我们看看您的示例输入:8 + 33 + 1345 - 137。如何解释混合运算符

    int sum = 0;
    Scanner sc = new Scanner(s); // s = "8 + 33 + 1345 - 137"
    //What now?
    

    您仍然可以通过一个循环完成此操作,但需要一些中间步骤

    // start with +
    sc.useDelimiter(PLUS);
    while(sc.hasNext()){
        String temp = sc.next();
    }
    // first pass, temp = "8"
    // first pass, temp = "3"
    // first pass, temp = "1345 - 137" (!!!)
    

    在上面的例子中,temp首先是"8"(注意这里是String),然后是下一遍的"33",然后是第三遍的"1345 - 137"。您通常会使用Integer.parseInt()String转换为int,如下所示:

    // start with +
    sc.useDelimiter(PLUS);
    while(sc.hasNext()){
        String temp = sc.next();
        sum += Integer.parseInt(temp);
    }
    // first pass, temp = "8"
    // first pass, temp = "3"
    // first pass, temp = "1345 - 137", code breaks at Integer.parseInt(temp)
    

    然而,这段代码在第三遍时中断,因为"1345 - 137"显然不是整数值。这就是在temp中存储值的地方;可以使用嵌套循环计算表达式的减法部分!在输入中检查+-是正确的,下面是一个更合适的位置:

    // start with +
    sc.useDelimiter(PLUS);
    while(sc.hasNext()){
        String temp = sc.next();
        // check if there are - signs in temp
        if(temp.contains("-")){
            // if there are, evaluate the subtraction expression
            // for this example, temp = "1345 - 137"
            Scanner sc2 = new Scanner(temp);
            sc2.useDelimiter(MINUS);
            int diff = sc2.nextInt(); // diff = 1345
            while(sc2.hasNext()){
                diff -= sc2.nextInt(); // diff = 1345 - 137 = 1208
            }
            sum += diff; // adds the result to the sum
        } else {
            sum += Integer.parseInt(temp); // there is no - sign, so skip ahead and just add to the sum
        }
    }
    

    您会注意到,我没有检查输入在循环之前的开头是否包含+符号;这是因为我假设,即使您输入类似1 - 5 - 9的内容,当调用sc.next()时,扫描器仍将返回至少整个字符串,该字符串仍将进入内部循环,表达式仍将被计算。我已经很长时间没有使用Scanner了,所以如果这个假设不正确,你必须修正它