Java 在其他类中返回更新值时遇到问题
所以我要做的是让我的Test1类在使用方法menuSelection时打印出newText的更新值。我们可以这样说:menuOption=1;我想将newText变量更新为0,这样当我在Test1类中打印它时,它会打印出0。问题是,即使在我使用menuSelection方法之后,它也不会更新我的newText变量,因为它只打印出1Java 在其他类中返回更新值时遇到问题,java,class,return-value,Java,Class,Return Value,所以我要做的是让我的Test1类在使用方法menuSelection时打印出newText的更新值。我们可以这样说:menuOption=1;我想将newText变量更新为0,这样当我在Test1类中打印它时,它会打印出0。问题是,即使在我使用menuSelection方法之后,它也不会更新我的newText变量,因为它只打印出1 导入java.util.Scanner public class Test { public static int newText = 1;
导入java.util.Scanner
public class Test {
public static int newText = 1;
public static int menuSelection(){
Scanner scan = new Scanner(System.in);
int menuOption = scan.nextInt();
while((menuOption < 0)||(menuOption > 2)) {
System.out.print("Not a valid option, please press 1 or 2 ");
menuOption = scan.nextInt();
}
if(menuOption == 1 ){
newText = 0;
}
if(menuOption == 2){
newText = 1;
}
return newText;
}
}
你的方法是这样写的
public static int menuSelection(){
但在main方法中没有得到返回值
所以你可以在这一行修改你的代码
原样
未来
但是,如果要更改静态值newText
,则需要更改变量名。
我想你对范围感到困惑
问题在于您没有从方法调用中分配值。一个更基本的问题是使用静态值在类之间传递信息
您不应该使用静态字段
传递值。在大多数情况下,也不应该使用静态方法(但也有例外)。只需使用实例或本地字段(视情况而定)执行以下操作
public class MenuTest {
public static void main(String[] args) {
// instantiate an instance of the class.
Test mt = new Test();
int newText = 1;
System.out.print(newText);
// invoke the method and get the return value.
newText = mt.menuSelection();
System.out.println(newText);
}
}
class Test {
public int menuSelection() {
Scanner scan = new Scanner(System.in);
int returnValue = 0;
int menuOption = scan.nextInt();
while ((menuOption < 0) || (menuOption > 2)) {
System.out.print(
"Not a valid option, please press 1 or 2 ");
menuOption = scan.nextInt();
}
if (menuOption == 1) {
returnValue = 0;
}
if (menuOption == 2) {
returnValue = 1;
}
return returnValue;
}
}
公共类菜单测试{
公共静态void main(字符串[]args){
//实例化类的实例。
测试mt=新测试();
int newText=1;
系统输出打印(新文本);
//调用该方法并获取返回值。
newText=mt.menuSelection();
System.out.println(newText);
}
}
课堂测试{
public int menuSelection(){
扫描仪扫描=新扫描仪(System.in);
int返回值=0;
int menuOption=scan.nextInt();
而((菜单选项<0)| |(菜单选项>2)){
系统输出(
“无效选项,请按1或2”);
menuOption=scan.nextInt();
}
如果(菜单选项==1){
返回值=0;
}
如果(菜单选项==2){
返回值=1;
}
返回值;
}
}
我将newText
字段重命名为returnValue
,以强调它与在main中使用的局部变量完全不同。在if子句之前放置一个断点,以查看实际传递到方法中的值。
Test.menuSelection();
newText = Test.menuSelection();
public class MenuTest {
public static void main(String[] args) {
// instantiate an instance of the class.
Test mt = new Test();
int newText = 1;
System.out.print(newText);
// invoke the method and get the return value.
newText = mt.menuSelection();
System.out.println(newText);
}
}
class Test {
public int menuSelection() {
Scanner scan = new Scanner(System.in);
int returnValue = 0;
int menuOption = scan.nextInt();
while ((menuOption < 0) || (menuOption > 2)) {
System.out.print(
"Not a valid option, please press 1 or 2 ");
menuOption = scan.nextInt();
}
if (menuOption == 1) {
returnValue = 0;
}
if (menuOption == 2) {
returnValue = 1;
}
return returnValue;
}
}