【问题标题】:Take a char input from the Scanner从扫描仪获取字符输入
【发布时间】:2012-12-06 05:36:23
【问题描述】:

我正在尝试找到一种从键盘获取char 输入的方法。

我尝试使用:

Scanner reader = new Scanner(System.in);
char c = reader.nextChar();

此方法不存在。

我尝试将c 作为String。然而,它并不总是适用于所有情况,因为我从我的方法调用的另一个方法需要 char 作为输入。因此,我必须找到一种方法来明确地将 char 作为输入。

有什么帮助吗?

【问题讨论】:

    标签: java input char java.util.scanner


    【解决方案1】:

    尝试以下。

    Scanner reader = new Scanner(System.in);
    char c = reader.next().charAt(0);
    

    这将从键盘获取一个字符。

    【讨论】:

      【解决方案2】:

      从用户输入读取字符的简单解决方案。 读取一个字符串。然后在字符串上使用 charAt(0)

      Scanner reader = new Scanner(System.in);
      String str = reader.next();
      char c = str.charAt(0);
      

      就是这样。

      【讨论】:

        【解决方案3】:
        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);

        【讨论】:

        • 只获取一个字符 char c = reader.next(".").charAt(0);
        【解决方案4】:

        只需使用...

        Scanner keyboard = new Scanner(System.in);
        char c = keyboard.next().charAt(0);
        

        这将获取下一个输入的第一个字符。

        【讨论】:

          【解决方案5】:

          你只需要写这个来获取 char 类型的值。

          char c = reader.next().charAt(0);
          

          【讨论】:

            【解决方案6】:

            有两种方法,您可以完全一个字符或严格一个字符。 当您准确使用时,无论您输入多少个字符,阅读器都只会读取第一个字符。

            例如:

            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值。

            【讨论】:

              【解决方案7】:

              您可以非常简单地解决“一次抓取键盘输入一个字符”的问题。通过使用它,不必全部使用 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);
                      }
                  }
              }  
              

              希望这有帮助,祝你好运!附:抱歉,我知道这是一篇较旧的帖子,但我希望我的回答能带来新的见解,并可以帮助其他也有这个问题的人。

              【讨论】:

                【解决方案8】:

                您应该使用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
                

                【讨论】:

                  【解决方案9】:
                  // 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');
                  }
                  }
                  

                  【讨论】:

                  • InputStreamReaderBufferedReader 有什么区别?你在你的代码中使用了它,但你没有解释。
                  【解决方案10】:

                  有三种方法可以解决这个问题:

                  • 在 Scanner 上调用 next(),并提取字符串的第一个字符(例如 charAt(0))如果要将行的其余部分作为字符读取,请遍历字符串中的其余字符。其他答案有这个代码。

                  • 使用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 时“释放”给应用程序。因此,如果您希望您的应用程序响应单个键盘敲击,这是行不通的。您需要执行一些特定于操作系统的本机代码来关闭或解决操作系统级别的控制台的行缓冲。

                  参考:

                  【讨论】:

                  • "这将导致 next() 标记为恰好是一个字符长的字符串。因此您可以重复调用 next().charAt(0) 来迭代人物。”我认为您的意思是 next() 只是因为您已经 setDelimiter("") 了?但是为您的第三点 +1。
                  • 不,我的意思是next().charAt(0)next 调用返回 String。所以如果你想迭代char的值,你需要调用charAt(0)来获取第一个字符。 (这是 Java,其中一个字符和一个字符串不是一回事。)请注意,OP 明确声明需要 char
                  【解决方案11】:

                  您应该使用自定义输入阅读器来获得更快的结果,而不是从读取字符串中提取第一个字符。 自定义 ScanReader 和说明链接:https://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8

                  字符扫描码:

                  BufferedInputStream br=new BufferedInputStream(System.in);
                  char a= (char)br.read();
                  

                  【讨论】:

                  • 您应该在答案中添加要点中的代码,因为它可能在一段时间内不可用。
                  • @Markus 添加用于扫描字符。
                  【解决方案12】:

                  最简单的方法是,首先将变量更改为字符串并将输入作为字符串接受。然后你可以根据输入变量使用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>
                  }
                  

                  【讨论】:

                    【解决方案13】:
                    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
                    

                    顺便说一句,您不能直接将字符作为输入。正如您在上面看到的,首先获取一个字符串,然后获取 charAt(0);找到并存储

                    【讨论】:

                      【解决方案14】:

                      试试这个: char c=S.nextLine().charAt(0);

                      【讨论】:

                        【解决方案15】:

                        试试这个

                        Scanner scanner=new Scanner(System.in);
                        String s=scanner.next();
                        char c=s.charAt(0);
                        

                        【讨论】:

                        • 但这会消耗整个字符串,你返回。
                        【解决方案16】:

                        要查找给定字符串中字符的索引,您可以使用以下代码:

                        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);
                        
                            }
                        
                        }
                        

                        【讨论】:

                          【解决方案17】:

                          你可以使用类型转换:

                          Scanner sc= new Scanner(System.in);
                          char a=(char) sc.next();
                          

                          这样,由于函数“next()”,您将在字符串中输入,但由于括号中提到的“char”,它将被转换为字符。

                          这种通过在括号中提及目标数据类型来转换数据类型的方法称为类型转换。它对我有用,我希望它对你有用:)

                          【讨论】:

                          • 您不能将String 类型转换为char
                          【解决方案18】:
                          import java.io.*;
                          
                          class abc // enter class name (here abc is class name)
                          {
                              public static void main(String arg[])
                              throws IOException // can also use Exception
                              {
                                  BufferedReader z =
                                      new BufferedReader(new InputStreamReader(System.in));
                          
                                  char ch = (char) z.read();
                              } // PSVM
                          } // class
                          

                          【讨论】:

                            【解决方案19】:

                            没有从 Scanner 获取字符的 API 方法。您应该使用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() 已经给你从第一个非白色字符开始的字符串吗?
                            • 但这会消耗整个字符串。
                            【解决方案20】:

                            这实际上不起作用:

                            char c = reader.next().charAt(0);
                            

                            这个问题有一些很好的解释和参考: Why doesn't the Scanner class have a nextChar method? “扫描器使用分隔符模式将其输入分解为标记”,这是非常开放的。例如当使用这个时

                            c = lineScanner.next().charAt(0);
                            

                            对于这行输入 “(1 + 9) / (3 - 1) + 6 - 2” 对 next 的调用返回 "(1",c 将被设置为 '(',你最终会在下一次调用 next() 时丢失 '1'

                            通常,当您想获得一个字符时,您想忽略空格。这对我有用:

                            c = lineScanner.findInLine("[^\\s]").charAt(0);
                            

                            参考: regex to match a single character that is anything but a space

                            【讨论】:

                            • 仅供参考"[^\\s]" === "\\S"
                            【解决方案21】:
                            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");
                            
                                }
                            }
                            

                            【讨论】:

                              【解决方案22】:

                              设置扫描仪:

                              reader.useDelimiter("");
                              

                              在此之后reader.next() 将返回一个单字符字符串。

                              【讨论】:

                                【解决方案23】:

                                你可以取Scanner.next的第一个字符:

                                char c = reader.next().charAt(0);
                                

                                完全使用你可以使用的一个字符:

                                char c = reader.findInLine(".").charAt(0);
                                

                                严格使用你可以使用的一个字符:

                                char c = reader.next(".").charAt(0);
                                

                                【讨论】:

                                • 实际上它占用了多个字符,但只作用于第一个字符
                                • @user1804697 只使用字符使用char c = reader.next("[a-zA-Z]").charAt(0);
                                • 在这种情况下,“完全”和“严格”有什么区别?
                                • @Reimeus 复制粘贴代码然后运行它的值到底是什么?
                                • 好吧,next() 版本会在乱码输入 bhjgfbergq35987t%$#%$# 上崩溃,而findInLine() 版本不会。我的问题实际上更多是关于“严格”和“确切”这两个词,而不是相应的代码片段。我不知道这些词不是同义词的上下文。
                                【解决方案24】:

                                在 Scanner 类中输入字符的最佳方法是:

                                Scanner sca=new Scanner(System.in);
                                System.out.println("enter a character");
                                char ch=sca.next().charAt(0);
                                

                                【讨论】:

                                  猜你喜欢
                                  • 1970-01-01
                                  • 2011-08-23
                                  • 1970-01-01
                                  • 2016-06-20
                                  • 2015-05-02
                                  • 1970-01-01
                                  • 2011-02-05
                                  相关资源
                                  最近更新 更多