Как я могу сохранить слово в переменной в программе компаса

Мне нужна помощь, чтобы сохранить слово в переменной и вывести мое сообщение из моей программы компаса. Мне нужно написать программу, в которой пользователь вводит направление компаса, а затем печатает сообщение. Я не знаю, почему это не выводит направление, мне нужно преобразовать целое число в строку /

Образец вывода:

Input compass direction(Eg.S45E):
S45E
Start facing South.Turn 45 degrees towards East.

Код:

// Initializes the BufferReader for user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//initiates first do-while loop

String word = null;
String word2 = null;

System.out.println("Compass Directions");
System.out.println("==================");
System.out.println("Input a compass direction "
                    + "(E.g. S45E):");
String userInput = br.readLine();

/*gets unicode from users first given letter 
to find direction */
int direction = userInput.charAt(0);
//finds unicode at the last character entered
int direction2 = userInput.charAt(3);

//check direction input and prints it
if (direction == 78)
    word="North";
else if (direction == 83)
    word="South";
else if (direction == 87)
    word="West";
else if (direction == 69)
    word="East";

//gets degree #1
char degrees1 = userInput.charAt(1);
//gets degree #2
char degrees2 = userInput.charAt(2);

if (direction2 == 78)
    word2="North";
else if (direction2 == 83)
    word2="South";
else if (direction2 == 87)
    word2="West";
else if (direction2 == 69)
    word2="East";

System.out.println("Start facing "+word+" turn "+degrees1+degrees2+" degrees to the "+word2);

2 ответа

Решение

Все гораздо проще, если разбить проблему на части, например -

// Convert the character representing a direction, into a cardinal direction.
private static String getDirection(char direction) {
  if (direction == 'N' || direction == 'n') {
    return "North";
  } else if (direction == 'S' || direction == 's') {
    return "South";
  } else if (direction == 'E' || direction == 'e') {
    return "East";
  } else if (direction == 'W' || direction == 'w') {
    return "West";
  }
  return "Unknown";
}

public static void main(String[] args)
    throws InterruptedException {
  // Construct a scanner.
  Scanner scanner = new Scanner(System.in);

  // The output message format.
  String fmt = "Start facing %s.Turn %s degrees towards %s.";
  // Loop forever.
  for (;;) {
    // Print directions.
    System.out.println("Compass Directions");
    System.out.println("==================");
    System.out.println("Input a compass direction "
        + "(E.g. S45E):");
    // Check that System.in hasn't been closed.
    if (!scanner.hasNextLine()) {
      break;
    }
    // Get input.
    String line = scanner.nextLine();
    String start = getDirection(line.charAt(0));
    String end = getDirection(line.charAt(line
        .length() - 1));
    String msg = String.format(fmt, start,
        line.substring(1, line.length() - 1), end);
    System.out.println(msg);
  }
}

Лучшим вариантом может быть цикл по входной строке по одному символу за раз, но вместо множества операторов if используйте блок переключателей:

String direction = "";
String word2 = br.ReadLine();
foreach (char c in word2.toCharArray();
{
  switch (c)
  {
    case 'N':
      direction = "North";
      break;
    case 'S':
      direction = "South";
      break;
    ... // Do the rest here
  }
}

Пример должен быть скорректирован для нескольких направлений (NE, NW SW, NNE и т. Д.), Но это должно обеспечить более работоспособную отправную точку.

Другие вопросы по тегам