在Java 11中还有另一种方法可以做这个简单的循环吗?

问题描述 投票:0回答:1

所以,我学习Java已经两天了,在编译下面的代码时遇到了一条错误消息。我试图做的是一个简单的程序,该程序从系统输入中获取名称,然后想要知道该名称是否为您想要使用的名称。工作完美。因此,我想对其进行修改:如果这不是所需的名称,则您应该能够根据需要多次输入该名称。这就是为什么我在其中具有布尔值“ confirmed”以及while循环的原因。编译后,即使我明确声明并使用了布尔值,我也会收到“已确认”布尔值的错误消息“未使用确定的局部变量的值”。我试过简单地移动初始声明,它没有任何改变。有人知道如何解决该问题或重新执行我的循环,这样就不会有任何问题吗?

Fyi,我正在将VS Code与Java扩展包一起使用。

import java.util.*;

public class Name{

public static void main(String[] args){

    Scanner sc = new Scanner(System.in);

    try{

    boolean confirmed = false;

    while(confirmed = false){
    System.out.println("What's your name again?");
    String enteredName = sc.nextLine();
    System.out.println("So, your name is " + enteredName + "?\nEnter 'yes' to confirm or 'no' to type a new name.");
    String confirmation = sc.nextLine();

    if(confirmation.equalsIgnoreCase("yes") || confirmation.equalsIgnoreCase("yes.")){
    System.out.println("Confirmed, " + enteredName + ".\n\nNow launching.");
    confirmed = true;
    }

    else if(confirmation.equalsIgnoreCase("no") || confirmation.equalsIgnoreCase("no.")){
    System.out.println("Please enter a new name.");
    confirmed = false;    
           }

        }

    }
    finally{
     sc.close();
    }
}

}

java variables boolean java-11
1个回答
0
投票

使用单个等号是一项赋值,如果要检查是否相等,请使用两个等号

// Sets value of confirmed to false then returns the new value
if (confirmed = false)

// Checks if confirmed is currently equal to false
if (confirmed == false)

// Checks if not confirmed (preferred syntax)
if (!confirmed)
© www.soinside.com 2019 - 2024. All rights reserved.