Код: Выделить всё
System.out.print("What is the first name of the Hungarian poet Petőfi? ");
String correctAnswer = "Sándor";
Scanner sc = new Scanner(System.in);
String answer = sc.next();
sc.close();
if (correctAnswer.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("The answer (" + answer + ") is incorrect, the correct answer is " + correctAnswer);
}
Код: Выделить всё
What is the first name of the Hungarian poet Petőfi? Sándor
Correct!
Код: Выделить всё
What is the first name of the Hungarian poet Petőfi? Sándor
The answer (S?ndor) is incorrect, the correct answer is Sándor
- (для смены кодовой страницы на UTF-8): это нужно только в том случае, если слово Petőfi отображается неправильно, но не помогает при вводе.
Код: Выделить всё
CHCP 65001
Код: Выделить всё
[Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding
- Передача StandardCharsets.UTF_8 или «UTF-8» в сканер.
- Использование InputStreamReader (с передачей кодировки или без нее) вместо Scanner.
- Передача параметра командной строки -Dfile.encoding=UTF-8 .
- Добавление строки System.setProperty("file.encoding", "UTF-8");
- Использование PowerShell вместо cmd
При преобразовании в байты (
Код: Выделить всё
Arrays.toString(input.getBytes())
По умолчанию буквы без акцентов получают свои обычные коды ASCII. Акцентированные буквы имеют длину 3 байта, все отрицательные значения. До изменения кодовой страницы байты Шандора следующие: [83, -17, -65, -67, 110, 100, 111, 114].
[*]Когда код страница изменяется на UTF-8, тогда буквы без акцента остаются прежними, а все буквы с акцентом становятся одним символом длиной 0. После изменения кодовой страницы байты выглядят так: [83, 0, 110, 100, 111, 114 ].
[*]То же самое в Eclipse: [83, -61, -95, 110, 100, 111, 114]
[*]Строка Sándor на самом деле кодируется в Java следующим образом: [83, -61, -95, 110, 100, 111, 114]
Это работает в Git Bash, но буква ő (и все остальные символы с диакритическими знаками, а не только этот) неправильно отображается в этом терминале:
Код: Выделить всё
What is the first name of the Hungarian poet Pet▒fi? Sándor
Correct!
Код: Выделить всё
What is the first name of the Hungarian poet Pet▒fi? Péter
The answer (P▒ter) is incorrect, the correct answer is S▒ndor
Код: Выделить всё
Console console = System.console();
String answer = console.readLine();
Код: Выделить всё
What is the first name of the Hungarian poet Petőfi? Sándor
The answer (Sándor) is incorrect, the correct answer is Sándor
Для перекрестной проверки я попробовал то же самое в Python, и он без проблем работает как в терминале Windows, так и в IDE:
Код: Выделить всё
answer = input('What is the first name of the Hungarian poet Petőfi? ')
correct_answer = 'Sándor'
if answer == correct_answer:
print('Correct')
else:
print('The answer (' + answer + ') is incorrect, the correct answer is ' + correct_answer)
Подробнее здесь: https://stackoverflow.com/questions/791 ... al-in-java