I'm trying to get the user name as an input, but whenever I run the code, it doesn't show properly. I tried adding Charset.forName("UTF-8");
but it did not solve the problem.
It shows the same problem in Git Bash and Powershell.
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in, Charset.forName("UTF-8"));
System.out.print("What is your name? ");
String name = scanner.nextLine();
System.out.println("Hello " + name);
}
}
Console:
What is your name? João
Hello Jo?o
I also tried running "chcp 65001" before running the code and it returns:
What is your name? João
Hello Joo
And then I added this code to try to fix it and I got a different error
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class input {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out), true, "UTF-8"));
System.out.print("What is your name? ");
String name = scanner.nextLine();
System.out.println("Hello " + name);
} catch (UnsupportedEncodingException e) {
throw new InternalError("VM does not support mandatory encoding UTF-8");
}
}
}
Console:
What is your name? João
Hello Jo´┐¢o