Reputation: 65
I am trying to write a small text-based game in Java. I had previously written this in C++, but I used "getch()" in C++, and I have no idea what the java equivalent. I am fairly new, and so am not very experienced, but I am able to learn. Is there a Java equivalent to "getch()" in Java? It needs to return the ASCII value of the key. Ideas?
Upvotes: 2
Views: 11245
Reputation: 5637
You could use a BufferedReader to replicate getch()
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class myclass
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Press Enter to continue");
try
{
int ascii = br.read();
System.out.println("ASCII Value - "+ascii);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output
Enter any character to continue
<press a then hit Enter>
ASCII Value - 97
Upvotes: 3
Reputation: 116
You'll probably want to use
InputStreamReader inStream = new InputStreamReader(System.in);
int charValue = inStream.read();
then switch on the character value from there.
As someone else mentioned, Java works on UTF-16, but for characters [a-zA-z0-9] and normal punctuation, you won't notice a difference.
Javadoc for the InputStreamReader: InputStreamReader Javadoc
Upvotes: 0
Reputation: 19093
In general, you read input from System.in. You can read from this stream in lots of ways, but one option is to use java.util.scanner.
Try something like:
import java.util.Scanner;
Scanner keyboard = new Scanner(System.in);
byte mybyte = keyboard.nextByte();
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
Upvotes: 0