gpt4 book ai didi

java - 局部变量 user_input 从内部类内部访问;需要宣布最终

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:03 25 4
gpt4 key购买 nike

import java.util.Scanner;

public class Testing {

public static void main(String [] args) {

Scanner user_input = new Scanner( System.in );

String start;
System.out.print("(Don't put capital letters) ");

String color;
System.out.print("Enter Your Favorite Color: ");
color = user_input.next ( );

String animal;
System.out.print("Enter Your Favorite Animal: ");
animal = user_input.next ( );

String preference;
preference = color + " and that your favorite animal is a " + animal;

System.out.println("From the information I gathered, I figured out that you like the color " + preference);

class A {
public void Main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you want to hear a joke?");
String a = user_input.next ( );

if (a.equalsIgnoreCase("yes")) ;
System.out.println("What did the fish say when he ran into a wall? Dam");

if(a.equalsIgnoreCase("no")) ;
System.out.println("Oh..."); }

}
}
}

这就是错误

Testing.java:29: error: local variable user_input is accessed from within inner class; needs to be declared final
String a = user_input.next ( );
^

1 个错误

我刚刚弄乱了代码,错误不断增加,所以我决定询问比我更有经验的人。我只使用了一天java,这是我创建的第一个程序,我已经搜索了至少2个小时的解决方案,但找不到,所以我决定询问。我之前编译过它,但它没有“user_input.next”,所以它的行为就像“class A”下面的整行代码都是不可见的,它不允许我输入任何内容,使其毫无用处。我然后输入 user_input 以便我可以输入一些内容,但是出现了大量错误,但这是不断弹出的一个错误。

最佳答案

该错误很可能是由于您声明扫描仪 (input),然后使用其他类中的扫描仪 (user_input)

试试这个代码

import java.util.Scanner;

public class Testing
{
public void input1()
{
Scanner user_input = new Scanner( System.in );

System.out.print("(Don't put capital letters) ");

String color;
System.out.print("Enter Your Favorite Color: ");
color = user_input.next();

String animal;
System.out.print("Enter Your Favorite Animal: ");
animal = user_input.next();

String preference;
preference = color + " and that your favorite animal is a " + animal;

System.out.println("From the information I gathered, I figured out that you like the color " + preference);
}

public void input2()
{
Scanner input = new Scanner(System.in);
System.out.println("Do you want to hear a joke?");
String a = input.next();

if(a.equalsIgnoreCase("yes"))
{
System.out.println("What did the fish say when he ran into a wall? Dam");
}
else if(a.equalsIgnoreCase("no"))
{
System.out.println("Oh...");
}
}

public static void main(String[] args)
{
Testing tS = new Testing();
tS.input1();
tS.input2();
}
}

这段代码中有两个方法; 输入1输入2。这些方法包含您尝试与命令控制台进行的两个对话。然后在 main 方法中初始化该类并运行这两个方法。

关于java - 局部变量 user_input 从内部类内部访问;需要宣布最终,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34240696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com