gpt4 book ai didi

java - 在多种方法中使用一个整数

转载 作者:行者123 更新时间:2023-11-29 04:34:20 25 4
gpt4 key购买 nike

所以我正在做一些事情。为了简短起见,我有两个类(class)。一个类是执行所有程序的地方,另一个类是我编写将要使用的代码的地方。我在我的类中有一个 x 和一个 y 整数,所有程序都在其中执行,我需要将执行的方法将 x 或 y 增加或减少 1。我有一个 switch 语句,该人有四个选择,并根据他们做出的选择决定 x 或 y 的值是上升还是下降。

import java.util.Scanner;
public class Walking {
public void NorthSouthEastWest(){
int x = 0;
int y = 0;
boolean direction = false;
Scanner input = new Scanner(System.in);

do{String userDirection = input.nextLine();

switch(userDirection){
case "North":
direction = true;
y++;
break;
case "South":
direction = true;
y--;
break;
case "East":
direction = true;
x++;
break;
case "West":
direction = true;
x--;
break;
default:
}
}while(direction == false);

但是当我运行程序时,我在输入 switch 语句的命令之前和之后打印出 x 和 y,而 x 和 y 不会改变。我不确定为什么。有什么解决办法吗?

最佳答案

原语和原语包装器在 Java 中是不可变的,因此一个好的解决方案是将它们包装到一个可变的对象中。

下面是一个使用 Location 类的示例,该类包含您的 xy 坐标。

import java.util.Scanner;

public class Test {
public static void main(String[] args) {
Location location = new Location();
Walking walking = new Walking();
walking.northSouthEastWest(location);

System.out.println(location.x);
System.out.println(location.y);
}
}

class Location {
int x;
int y;
}

class Walking {
public void northSouthEastWest(Location location) {
boolean direction = false;
Scanner input = new Scanner(System.in);

do {
String userDirection = input.nextLine();

switch (userDirection) {
case "North":
direction = true;
location.y++;
break;
case "South":
direction = true;
location.y--;
break;
case "East":
direction = true;
location.x++;
break;
case "West":
direction = true;
location.x--;
break;
}
} while (!direction);
}
}

如果您不想使用自定义的 Location 类对象,您也可以使用包含两个元素的 int[] 数组。

关于java - 在多种方法中使用一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42360834/

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