需要帮助整理这个运动功能

时间:2013-08-27 15:06:13

标签: java

大家好,我想知道你是否可以帮助我,你能不能告诉我这里我做错了什么,我想要做的是如果输入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);

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

如果你想要1个衬垫,请使用:

position += car.equalsIgnoreCase("r") ? 1 : car.equalsIgnoreCase("l") ? -1 : 0;

答案 2 :(得分:0)

使用以下其中一种风格:

position += 1
position -= 1

position = position + 1
position = position - 1

从值中添加或减去1。目前,您只需为其指定值+ / - 1。

答案 3 :(得分:0)

用car.equals(“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);

答案 4 :(得分:0)

不要使用多个if s(应该是if - else语句,所以你不要在每种情况下都不要吝啬)和String s,请记住你可以{{ 1}} switch

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