在C中,我们可以使用键盘中的关键字char
将输入作为字符
scanf("%c", &ch);
但是在Java中如何做到这一点?
我试过这个:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a character: ");
char c = scanner.next().charAt(0);
System.out.println("You have entered: "+c);
}
}
答案 0 :(得分:5)
您可以使用扫描仪从输入中读取:
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.
答案 1 :(得分:1)
您只需使用(char) System.in.read();
投射到char
即可将int
转换为char
答案 2 :(得分:0)
使用System类
char yourChar = System.in.read()
答案 3 :(得分:0)
以下是示例程序。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFromConsole {
public static void main(String[] args) {
System.out.println("Enter here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String value = bufferRead.readLine();
System.out.println(value);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
在互联网上搜索时,您可以轻松搞定。 StackExchange建议做一些研究并在达成之前付出一些努力。
答案 4 :(得分:0)
使用java你可以这样做:
使用扫描仪:
Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
使用BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
在这两种情况下,您需要传递默认输入,在我的情况下是System.in
答案 5 :(得分:0)
使用:
char ch=**scanner.nextChar**()
答案 6 :(得分:0)
我遇到了同样的困难,而这就是我所使用的:
} public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the string: ");
String input = scan.next();
System.out.print("Please enter the required symbol: ");
String symbol = scan.next();
char symbolChar = symbol.charAt(0);
这很好用。 我们的想法是从字符串中获取其中唯一的字符。
答案 7 :(得分:0)
qsort(dataset, total, sizeof(flow_data), num_compare);
答案 8 :(得分:0)
import java.util.Scanner;
class CheckVowel {
public static void main(String args[]) {
Scanner obj= new Scanner(System.in);
char a=obj.next().charAt(0);
switch(a) {
case 'a': //cases can be used together for the same statement
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
{
System.out.println("Vowel....");
break;
}
default:
System.out.println("Consonants....");
}
}
}
答案 9 :(得分:0)
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a character:");
String str = next();
char c = str.charAt(0);
System.out.println(c);
sc.close();
}
[Output of this program.][1]}