Answers:
您可以从中提取第一个字符Scanner.next
:
char c = reader.next().charAt(0);
消耗正好一个字符,你可以使用:
char c = reader.findInLine(".").charAt(0);
要严格使用一个字符,可以使用:
char c = reader.next(".").charAt(0);
char c = reader.next("[a-zA-Z]").charAt(0);
没有API方法可从扫描仪获取字符。您应该使用String并对返回的String scanner.next()
调用String.charAt(0)
方法。
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
为了安全使用空格,您还可以先调用trim()
字符串以删除所有空格。
Scanner reader = new Scanner(System.in);
char c = reader.next().trim().charAt(0);
reader.next()
从第一个非白色字符开始给您字符串?
有三种方法可以解决此问题:
调用next()
Scanner,然后提取String的第一个字符(例如charAt(0)
)。如果您想将行的其余部分读取为字符,请遍历String中的其余字符。其他答案有此代码。
用于setDelimiter("")
将分隔符设置为空字符串。这将导致next()
标记化为恰好一个字符长的字符串。因此,您可以反复调用next().charAt(0)
以迭代字符。然后,您可以将定界符设置为其原始值,然后以正常方式继续扫描!
使用Reader API而不是Scanner API。该Reader.read()
方法提供从输入流读取的单个字符。例如:
Reader reader = new InputStreamReader(System.in);
int ch = reader.read();
if (ch != -1) { // check for EOF
// we have a character ...
}
当您通过控制台从控制台读取数据时System.in
,输入通常由操作系统缓冲,并且只有在用户键入ENTER时才“释放”到应用程序。因此,如果您打算让应用程序响应单个的键盘击键,那么它将无法正常工作。您可能需要做一些特定于操作系统的本机代码,才能在操作系统级别关闭或解决控制台的行缓冲。
参考:
您可以非常简单地解决“一次抓住一个键盘输入一个字符”的问题。通过使用此方法,不必全部使用Scanner,也不必清除输入缓冲区作为副作用。
char c = (char)System.in.read();
如果您所需要的只是与C语言“ getChar()”函数相同的功能,那么它将非常有用。“ System.in.read()”的最大优点是,每次抓取字符后都不会清除缓冲区。因此,如果您仍然需要所有用户输入,则仍然可以从输入缓冲区中获取其余信息。该"char c = scanner.next().charAt(0);"
方法确实捕获了字符,但将清除缓冲区。
// Java program to read character without using Scanner
public class Main
{
public static void main(String[] args)
{
try {
String input = "";
// Grab the First char, also wait for user input if the buffer is empty.
// Think of it as working just like getChar() does in C.
char c = (char)System.in.read();
while(c != '\n') {
//<do your magic you need to do with the char here>
input += c; // <my simple magic>
//then grab the next char
c = (char)System.in.read();
}
//print back out all the users input
System.out.println(input);
} catch (Exception e){
System.out.println(e);
}
}
}
希望这会有所帮助,并祝你好运!PS对不起,我知道这是一篇较旧的文章,但我希望我的回答能带来新的见解,并可能对其他也遇到此问题的人有所帮助。
这实际上不起作用:
char c = reader.next().charAt(0);
这个问题有一些很好的解释和参考: 为什么Scanner类没有nextChar方法? “扫描程序使用定界符模式将其输入分解为令牌”,这很开放。例如当使用这个
c = lineScanner.next().charAt(0);
对于这行输入“(1 + 9)/(3-1)+ 6-2”,对next的调用将返回“(1”,c将被设置为'(',而您最终将丢失'下次调用next()时为1'
通常,当您想要获取字符时,您会忽略空格。这为我工作:
c = lineScanner.findInLine("[^\\s]").charAt(0);
"[^\\s]" === "\\S"
在Scanner类中输入字符的最佳方法是:
Scanner sca=new Scanner(System.in);
System.out.println("enter a character");
char ch=sca.next().charAt(0);
import java.util.Scanner;
public class userInput{
public static void main(String[] args){
// Creating your scanner with name kb as for keyBoard
Scanner kb = new Scanner(System.in);
String name;
int age;
char bloodGroup;
float height;
// Accepting Inputs from user
System.out.println("Enter Your Name");
name = kb.nextLine(); // for entire line of String including spaces
System.out.println("Enter Your Age");
age = kb.nextInt(); // for taking Int
System.out.println("Enter Your BloodGroup : A/B/O only");
bloodGroup = kb.next().charAt(0); // For character at position 0
System.out.println("Enter Your Height in Meters");
height = kb.nextFloat(); // for taking Float value
// closing your scanner object
kb.close();
// Outputting All
System.out.println("Name : " +name);
System.out.println("Age : " +age);
System.out.println("BloodGroup : " +bloodGroup);
System.out.println("Height : " +height+" m");
}
}
您应该使用自定义输入阅读器以获得更快的结果,而不是从读取String中提取第一个字符。自定义ScanReader的链接和说明:https ://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8
扫描Char的代码:
BufferedInputStream br=new BufferedInputStream(System.in);
char a= (char)br.read();
有两种方法,你可以采取正好一个字符或严格的一个字符。完全使用时,阅读器将仅输入第一个字符,而不管您输入了多少个字符。
例如:
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.findInLine(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
当您输入一组字符(例如“ abcd”)时,读者将只考虑第一个字符,即字母“ a”
但是,当您严格使用时,输入内容应仅为一个字符。如果输入的字符多于一个,则阅读器将不接受该输入
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.next(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
假设您输入“ abcd”,则不输入任何内容,并且变量c将具有Null值。
package Pack;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
char c = reader.next(".").charAt(0);
}
}
仅获得一个字符char c = reader.next(“。”)。charAt(0);
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
您应该使用scanner.next()获取字符串,并在返回的字符串上调用String.charAt(0)方法。
范例:
import java.util.Scanner;
public class InputC{
public static void main(String[] args) {
// TODO Auto-generated method stub
// Declare the object and initialize with
// predefined standard input object
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a character: ");
// Character input
char c = scanner.next().charAt(0);
// Print the read value
System.out.println("You have entered: "+c);
}
}
输出
Enter a character:
a
You have entered: a
Scanner key = new Scanner(System.in);
//shortcut way
char firstChar=key.next().charAt(0);
//how it works;
/*key.next() takes a String as input then,
charAt method is applied on that input (String)
with a parameter of type int (position) that you give to get
that char at that position.
You can simply read it out as:
the char at position/index 0 from the input String
(through the Scanner object key) is stored in var. firstChar (type char) */
//you can also do it in a bit elabortive manner to understand how it exactly works
String input=key.next(); // you can also write key.nextLine to take a String with spaces also
char firstChar=input.charAt(0);
char charAtAnyPos= input.charAt(pos); // in pos you enter that index from where you want to get the char from
顺便说一句,您不能直接将char作为输入。如上所示,首先获取一个String,然后获取charAt(0); 找到并存储
要查找给定字符串中字符的索引,可以使用以下代码:
package stringmethodindexof;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* @author ASUS//VERY VERY IMPORTANT
*/
public class StringMethodIndexOf {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String email;
String any;
//char any;
//any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER").charAt(0);
//THE AVOBE LINE IS FOR CHARACTER INPUT LOL
//System.out.println("Enter any character or string to find out its INDEX NUMBER");
//Scanner r=new Scanner(System.in);
// any=r.nextChar();
email = JOptionPane.showInputDialog(null,"Enter any string or anything you want:");
any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER");
int result;
result=email.indexOf(any);
JOptionPane.showMessageDialog(null, result);
}
}
最简单的方法是,首先将变量更改为String并接受输入作为字符串。然后,可以使用if-else或switch语句基于输入变量进行控制,如下所示。
Scanner reader = new Scanner(System.in);
String c = reader.nextLine();
switch (c) {
case "a":
<your code here>
break;
case "b":
<your code here>
break;
default:
<your code here>
}