在if语句中创建对象并稍后使用它

2024-02-28

我正在为中缀表示法编写一个解析器。 在 if 语句中我声明了变量 newchild。否则我希望它抛出异常。但是当我超出范围时,编译器不再知道该变量。 我不能在 if 语句之前声明它,因为根据我们所处的情况,该变量被分配了不同的数据类型。

我可以做什么来解决这个问题?

public class ParserForInfixNotation {

public Node parse(List<String> tokenList) {

    Stack<String> myStack = new Stack<String>();
    int i =1;
    while(i <= tokenList.size()){                           //wir gehen alle Eintraege in der Liste durch
        if(Character.isDigit(tokenList.get(i).charAt(1))){
            int value = Integer.parseInt(tokenList.get(i));     //falls der Eintrag eine Zahl ist, wird ein neuer Leaf erstellt
            Leaf res = new Leaf(value);
        }
        else if(tokenList.get(i) == "("){                       // falls der Eintrag eine Klammer ist, wird geschaut, ob in der Klammer ein Unary oder Binary OpNode definiert ist
            if (tokenList.get(i+1) == "-") {
                                                                // Fall Unary
                int j = i+1;
                                                                //am Liebsten ein rekursiver Aufruf auf parser mit nem TeilString des Oberen Strings, der genau den naechsten Node beschreibt
                int anzahlklammern = 0;
                boolean end = false;
                if((Character.isDigit(tokenList.get(j).charAt(1))) || (tokenList.get(j+1) == ")")){
                    Leaf newchild = new Leaf(Integer.parseInt(tokenList.get(j)));
                }
                else if(tokenList.get(j) == "("){
                    while(!end){
                        if(tokenList.get(j) == ")" && anzahlklammern == 1){
                            end = true;
                        }
                        else if(tokenList.get(j) == ")" && j > i+3){                    //die Klammer muss mindestens 2 Stellen enthalten
                            anzahlklammern--;
                            j++;
                        }
                        else if(tokenList.get(j) == "("){
                            anzahlklammern++;
                            j++;
                        }
                        else if ((Character.isDigit(tokenList.get(j).charAt(1))) || tokenList.get(j) == "+" || tokenList.get(j) == "*" || tokenList.get(j) == "-"){
                            j++;
                        }
                        else{
                            throw new IllegalArgumentException();
                        }
                    }
                    List<String> neu = new ArrayList<>();

                    for (int l = i+2; l<j;l++){
                        neu.add(tokenList.get(l));
                    }
                    Node newchild = parse(neu);
                }
                else {
                    throw new IllegalArgumentException();
                }

                UnaryOpNode res = new UnaryOpNode('-',newchild);
            }
            else if((tokenList.get(i+1) == "(") || (Character.isDigit(tokenList.get(i+1).charAt(1)))){ //Fall Binary
                if (Character.isDigit(tokenList.get(i+1).charAt(1)) && (tokenList.get(i+2) == "+" || tokenList.get(i+2) == "*")){
                    Leaf newchildleft = new Leaf(Integer.parseInt(tokenList.get(i+1)));
                    if(tokenList.get(i+2) == "+"){
                        Character operator = '+';
                    }
                    else if(tokenList.get(i+2) == "*"){
                        Character operator = '*';
                    }
                    int j = i+3;
                    if(Character.isDigit(tokenList.get(j).charAt(1))){
                        Leaf newchildright = new Leaf(Integer.parseInt(tokenList.get(j)));
                    }
                    else if(tokenList.get(j) == "("){
                        boolean end = false;
                        int anzahlklammern =0 ;
                        while(!end){
                            if(tokenList.get(j) == ")" && anzahlklammern == 1){
                                end = true;
                            }
                            else if(tokenList.get(j) == ")" && j > i+5){                    //die Klammer muss mindestens 2 Stellen enthalten
                                anzahlklammern--;
                                j++;
                            }
                            else if(tokenList.get(j) == "("){
                                anzahlklammern++;
                                j++;
                            }
                            else if ((Character.isDigit(tokenList.get(j).charAt(1))) || tokenList.get(j) == "+" || tokenList.get(j) == "*" || tokenList.get(j) == "-"){
                                j++;
                            }
                            else{
                                throw new IllegalArgumentException();
                            }
                        }
                        List<String> neu = new ArrayList<>();

                        for (int l = i+4; l<j;l++){
                            neu.add(tokenList.get(l));
                        }
                        Node newrightchild = parse(neu);
                    }
                    else{
                        throw new IllegalArgumentException();
                    }
                }
                else if(tokenList.get(i+1) == "("){
                    int j= i+1;
                    boolean end = false;
                    int anzahlklammern =0 ;
                    while(!end){
                        if(tokenList.get(j) == ")" && anzahlklammern == 1){
                            end = true;
                        }
                        else if(tokenList.get(j) == ")" && j > i+3){                    //die Klammer muss mindestens 2 Stellen enthalten
                            anzahlklammern--;
                            j++;
                        }
                        else if(tokenList.get(j) == "("){
                            anzahlklammern++;
                            j++;
                        }
                        else if ((Character.isDigit(tokenList.get(j).charAt(1))) || tokenList.get(j) == "+" || tokenList.get(j) == "*" || tokenList.get(j) == "-"){
                            j++;
                        }
                        else{
                            throw new IllegalArgumentException();
                        }
                    }
                    List<String> neu = new ArrayList<>();

                    for (int l = i+2; l<j;l++){
                        neu.add(tokenList.get(l));
                    }
                    Node newleftchild = parse(neu);
                    if(tokenList.get(j+1) == "+"){
                        Character operator = '+';
                    }
                    else if(tokenList.get(j+1) == "*"){
                        Character operator = '*';
                    }
                    else{
                        throw new IllegalArgumentException();
                    }
                    if(tokenList.get(j+2)== "("){
                        int k= j+3;
                        end = false;
                        anzahlklammern =0 ;
                        while(!end){
                            if(tokenList.get(k) == ")" && anzahlklammern == 1){
                                end = true;
                            }
                            else if(tokenList.get(k) == ")" && k > j+5){                    //die Klammer muss mindestens 2 Stellen enthalten
                                anzahlklammern--;
                                k++;
                            }
                            else if(tokenList.get(k) == "("){
                                anzahlklammern++;
                                k++;
                            }
                            else if ((Character.isDigit(tokenList.get(k).charAt(1))) || tokenList.get(k) == "+" || tokenList.get(k) == "*" || tokenList.get(k) == "-"){
                                k++;
                            }
                            else{
                                throw new IllegalArgumentException();
                            }
                        }
                        List<String> neu2 = new ArrayList<>();

                        for (int l = j+4; l<k;l++){
                            neu.add(tokenList.get(l));
                        }
                        Node newrightchild = parse(neu2);
                    }
                    else if(Character.isDigit(tokenList.get(j+2).charAt(1))){
                        Leaf newrightchild = new Leaf(Integer.parseInt(tokenList.get(j+2)));
                    }
                    else{
                        throw new IllegalArgumentException();
                    }
                }
                BinaryOpNode res = new BinaryOpNode(operator, newleftchild, newrightchild);
            }
            else{
                throw new IllegalArgumentException();
            }
        }
        else{
            throw new IllegalArgumentException();
        }
    }



    return res; 
}

这是关于scope。变量的作用域是它所在的块declared,以及其中的块。该块是否是某个块的块并不重要if语句、其他语句或只是为了定义范围而放在那里的块。

你正在经历这样的情况:

{
    Leaf leaf = new Leaf();
}

doSomethingWith(leaf); // compiler error - there is no `leaf` in this scope.

您可以使用以下方法修复它:

 Leaf leaf;
 {
      leaf = new Leaf();
 }
 doSomethingWith(leaf);

如果有可能分配给leaf不会发生——例如,如果它在if块,然后你会得到一个编译器错误说variable leaf may not have been initialized。您可以通过首先初始化一些后备值来解决此问题。它通常为空:

 Leaf leaf = null;
 if(...) {
      leaf = new Leaf();
 }
 doSomethingWith(leaf);

但现在你的代码必须应对以下可能性:leaf == null- 这会导致代码要么过于复杂,要么脆弱。找到避免分配 null 的方法,或者如果不能的话,隔离易受攻击的代码块,以便该范围之外的任何内容都不需要处理 null 变量的可能性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在if语句中创建对象并稍后使用它 的相关文章

  • 将 allMatch、noneMatch 和 anyMatch 合并到单个流上

    我想要以下逻辑 我知道它不起作用 因为它多次消耗流 但我不知道如何实现它 Stream
  • Java中如何合并两个数组?

    它不是连接而是合并两个数组 使它们成为名称值对的数组 firstarray a aa aaa secondarray b bb bbb result a b aa bb aaa bbb 最好的方法是什么 in Java public sta
  • 从SQLite列中获取所有数字字符串并进行总和计算

    我是 Android 和 SQLite 的新手 我在 SQLite 中有一个只有数字的 AMOUNT 列 我可以在 ListView 中显示它 但我无法找到任何我理解的方法来将它们全部添加并显示在 TextView 中 这是数据库助手 im
  • Spring MVC - 自动查找验证器

    假设我有一个像这样的示例实体类 public class Address 和相应的验证器 Component public AddressValidator implements Validator Override public bool
  • Eclipse 与 IntelliJ 热部署

    我的应用程序配置 Tomcat 8 Spring Spring MVC Hibernate 在 Eclipse 中 我创建了 Tomcat 服务器 并将我的应用程序添加到资源中 JSP JS CSS 和 JAVA 类热部署的工作原理就是这样
  • Java中如何对对象数组进行排序?

    我的数组不包含任何字符串 但它包含对象引用 每个对象引用都通过 toString 方法返回名称 id 作者和发布者 public String toString return name n id n author n publisher n
  • java中%%是什么意思?

    我是一名 PHP 程序员 想知道这行代码的含义 System out printf exp 3f is 3f n x Math exp x 3f 3f n 和逗号 x 是什么意思 它与C类似printf http java sun com
  • JSF-2 应用程序中的服务器端计时器

    在我正在开发的 JSF 2 应用程序中 当用户执行操作时 我需要启动服务器端计时器 这个计时器必须与应用程序本身相关 因此它必须在用户会话关闭时继续存在 为了解决这个问题 我想使用 java util Timer 类在应用程序范围的 bea
  • 如何对 jar 文件资源使用 File.separator?

    我正在尝试读取位于 jar 文件中的属性文件 我想使用 File separator 因为应用程序将在多个平台上运行 我正在构建路径如下 jarFilePath jar file jarFile getAbsolutePath jarPro
  • Android Studio:如果设置项目的背景颜色,ListView OnClick 动画将不起作用

    在我的项目中 我在 ListView 内设置了项目 由插入 ConstraintLayout 中的多个元素组成 的背景颜色 但如果背景颜色不是至少一点透明 则单击和长按的默认动画会消失 事实上 随着透明度的降低 点击元素的效果越来越不明显
  • Spark SQL 失败,因为“常量池已超过 JVM 限制 0xFFFF”

    我在 EMR 4 6 0 Spark 1 6 1 上运行此代码 val sqlContext SQLContext getOrCreate sc val inputRDD sqlContext read json input try inp
  • 检查更新时 Maven 无限期挂起

    我正在使用 Maven 构建一个项目 我是新手 并且它挂起 mvn package INFO Scanning for projects INFO INFO Building Presentation Reports INFO task s
  • 如何在 PuTTY 中保存并运行 Java 文件?

    我是 AWS 亚马逊网络服务 的新手 所以这可能是一个基本问题 我在 AWS 上创建了一个 EC2 实例 我有一台 Windows 计算机 因此我使用 PUTTY 来连接 Linux 实例 连接到我的 EC2 实例后 我使用以下命令编写 J
  • @Transactional 注解属于哪里?

    如果您将 Transactional in the DAO类和 或其方法 或者注释使用 DAO 对象调用的服务类是否更好 或者注释两个 层 是否有意义 我认为事务属于服务层 它是了解工作单元和用例的人 如果您将多个 DAO 注入到需要在单个
  • 字符串化 JavaScript 对象

    我正在寻找字符串化一个对象 我想要这样的输出 1 valeur dalebrun usager experttasp date 2013 08 20 16 41 50 2 valeur test usager experttasp date
  • Tomcat下的Spring CXF Soap Web服务:找不到服务

    我正在尝试使用 CXF 和 Spring 设置一个在 Tomcat 上运行的简单 CXF Web 服务 我有一个 Web 应用程序初始化程序来引导 CXF servlet public class WebAppInitializer ext
  • java charAt() 和startsWith() 哪个更快? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我的问题是 如果我想检查特定索引中字符串的一个字符 仅检查一个字符 哪种方法非常有效charAt or startsWith 我的意思是 据我所
  • 为什么 CompletableFuture 的 thenAccept() 不在主线程上运行

    我在 CompletableFuture 的 SupplyAsync 中处理长时间运行的操作 并将结果放入 thenAccept 中 有时 thenAccept 在主线程上执行 但有时它在工作线程上运行 但我只想在主线程上运行 thenAc
  • Java 中的连接路径

    In Python我可以连接两条路径os path join os path join foo bar gt foo bar 我正在尝试在 Java 中实现相同的目标 而不用担心是否OS is Unix Solaris or Windows
  • 可空日期列合并问题

    我在 Geronimo 应用程序服务器上使用 JPA 和下面的 openjpa 实现 我也在使用MySQL数据库 我在更新具有可为空 Date 属性的对象时遇到问题 当我尝试合并 Date 属性设置为 null 的实体时 不会生成 sql

随机推荐