0

嗨,伙计们只是想知道您是否可以帮助我,您能告诉我我在这里做错了什么吗?我要做的是如果输入 r 则加 1,如果同时为小写和大写输入 L,则减 1。但该位置不断返回原件。请帮忙!!

    int position = 0;
    System.out.print("move: ");
    String car = Global.keyboard.nextLine();
    if (car == "r/")
        position =  + 1;
    if (car == "R")
        position = +1;
    if (car == "l")
        position =  -1;
    if (car == "L")
        position = -1;
        System.out.print(position);
4

5 回答 5

2

利用:

int position = 0;
System.out.print("move: ");
String car = Global.keyboard.nextLine();
if (car.equals("r"))
    position += 1;
if (car.equals("R"))
    position += 1;
if (car.equals("l"))
    position -= 1;
if (car.equals("L"))
    position -= 1;
    System.out.print(position);
于 2013-08-27T15:08:15.387 回答
0

使用以下样式之一:

position += 1
position -= 1

或者

position = position + 1
position = position - 1

从一个值中加或减 1。目前,您只是为其分配值 + / - 1。

于 2013-08-27T15:10:35.607 回答
0

用 car.equals("something") 替换每辆车 == "something"

像这样:

String car = Global.keyboard.nextLine();
if (car.equals("r"))
    position =  + 1;
if (car.equals("R"))
    position = +1;
if (car.equals("l"))
    position =  -1;
if (car.equals("L"))
    position = -1;
    System.out.print(position);
于 2013-08-27T15:11:23.343 回答
0

不要使用多个ifs(应该是if - else语句,因此您不会在每种情况下都检查每个)和Strings,请记住您可以switcha char

int position = 0;
//int dx = 1; For this case, the explanation is in a comment below.
System.out.print("move: ");
char car = Global.keyboard.nextChar();
switch(car) {
    case 'r':
    case 'R':
        position += 1; //Or position++ if you prefer, but I'd use this approach
                       //just in case you want to do position += 5 in the future
                       //or better yet, position += dx, being dx an int that
                       //defines the range of a single movement.
        break;
    case 'l':
    case 'L':
        position -= 1; //Same as with right, but position -= dx;
        break;
    default:
        System.out.println("Please, use r - R for (R)ight or l - L for (L)eft");
        break;
}
System.out.print(position);

另外,请注意我更改了您的职位更新。为了解决您当前的问题,==不应该用于比较Strings,因为它比较参考。改为使用equals

于 2013-08-27T15:13:21.997 回答
0

如果你想要一个 1 班轮,使用这个:

position += car.equalsIgnoreCase("r") ? 1 : car.equalsIgnoreCase("l") ? -1 : 0;
于 2013-08-27T15:09:11.313 回答