Pobieranie danych ze skanera

Próbuję znaleźć sposób na pobranie char wejścia z klawiatury.

Próbowałem użyć:

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

Ta metoda nie istnieje.

Próbowałem wziąć c jako String. Jednak nie zawsze będzie działać w każdym przypadku, ponieważ inna metoda, którą wywołuję z mojej metody, wymaga char jako wejścia. Dlatego muszę znaleźć sposób, aby jawnie przyjąć znak jako wejście. Jakaś pomoc?
Author: Radiodef, 2012-12-19

19 answers

Możesz wziąć pierwszy znak z Scanner.next:

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

Aby skonsumować dokładnie jeden znak, którego mógłbyś użyć:

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

Aby spożywać ściśle jeden znak, który możesz użyć:

char c = reader.next(".").charAt(0);
 138
Author: Reimeus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-15 20:58:51

Konfiguracja skanera:

reader.useDelimiter("");

Po Tym reader.next() zwróci łańcuch jednoznakowy.

 45
Author: hoat4,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-18 08:42:26

Nie ma metody API, aby uzyskać Znak Ze skanera. Należy pobrać łańcuch za pomocą scanner.next() i wywołać metodę String.charAt(0) na zwracanym łańcuchu.

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

Aby być bezpiecznym z białymi spacjami, możesz również najpierw wywołać trim() na łańcuchu, aby usunąć dowolne białe spacje.

Scanner reader = new Scanner(System.in);
char c = reader.next().trim().charAt(0);
 16
Author: PermGenError,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-06 00:51:38

Istnieją trzy sposoby podejścia do tego problemu:

  • Wywołaj next() na skanerze i wyodrębnij pierwszy znak łańcucha (np. charAt(0)) Jeśli chcesz odczytać resztę linii jako znaki, powtórz pozostałe znaki w łańcuchu. Inne odpowiedzi mają ten kod.

  • Użyj setDelimiter(""), aby ustawić ogranicznik na pusty łańcuch. Spowoduje to tokenizację next() do łańcuchów o długości dokładnie jednego znaku. Więc możesz wielokrotnie wywołaj next().charAt(0), aby iterować znaki. Następnie można ustawić ogranicznik na jego pierwotną wartość i wznowić skanowanie w normalny sposób!

  • Użyj API Reader zamiast API Scanner. Metoda Reader.read() dostarcza pojedynczy znak odczytywany ze strumienia wejściowego. Na przykład:

    Reader reader = new InputStreamReader(System.in);
    int ch = reader.read();
    if (ch != -1) {  // check for EOF
        // we have a character ...
    }
    

Podczas odczytu z konsoli przez System.in, Wejście jest zazwyczaj buforowane przez system operacyjny i "uwalniane" do aplikacji tylko wtedy, gdy typy użytkowników ENTER. Jeśli więc chcesz, aby aplikacja odpowiadała na poszczególne uderzenia klawiatury, nie będzie to działać. Aby wyłączyć lub obejść buforowanie linii konsoli na poziomie systemu operacyjnego, konieczne jest wykonanie kodu natywnego specyficznego dla systemu operacyjnego.

Odniesienie:

 9
Author: Stephen C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-13 00:02:53

To faktycznie nie działa:

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

Jest kilka dobrych wyjaśnień i odniesień w tym pytaniu: Dlaczego Klasa skanera nie ma metody nextChar? "Skaner dzieli Dane wejściowe na tokeny za pomocą wzorca ogranicznika", który jest dość otwarty. Na przykład przy użyciu tego

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

Dla tej linii wejścia "(1 + 9) / (3 - 1) + 6 - 2" wywołanie do next zwraca "(1", c zostanie ustawione na " ( ", a w końcu stracisz ' 1 ' przy następnym wywołaniu do next ()

Zazwyczaj, gdy chcesz uzyskać znak, chcesz zignorować białe znaki. To mi się udało:

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

Odniesienie: regex dopasowujący pojedynczy znak, który jest niczym innym niż spacją

 3
Author: gary69,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:22

Najlepszym sposobem na wprowadzenie znaku w klasie skanera jest:

Scanner sca=new Scanner(System.in);
System.out.println("enter a character");
char ch=sca.next().charAt(0);
 2
Author: Sahil Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-14 16:37:17
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");

    }
}
 1
Author: HellPreacher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-15 14:24:24

Powinieneś użyć własnego czytnika wejściowego, aby uzyskać szybsze wyniki, zamiast wydobywać pierwszy znak z czytanego ciągu. Link do niestandardowego skanera i Wyjaśnienie: https://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8

Kod do skanowania znaku:

BufferedInputStream br=new BufferedInputStream(System.in);
char a= (char)br.read();
 1
Author: NIKUNJ KHOKHAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-16 06:23:40
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);

    }
}

Aby uzyskać tylko jeden znak char C = reader.następny(".").charAt (0);

 0
Author: Rakesh Kumar B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-16 14:20:05
// 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');
}
}
 0
Author: John Born,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-19 17:32:31

Powinieneś uzyskać ciąg za pomocą skanera.next() i wywołują String.metoda charAt (0) Na zwracanym łańcuchu.
Exmple:

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


        }

Wyjście

Enter a character: 
a
You have entered: a
 0
Author: AbdoCosmos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-19 19:58:50
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
 -1
Author: vishu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-06 21:55:02

Spróbuj tego

Scanner scanner=new Scanner(System.in);
String s=scanner.next();
char c=s.charAt(0);
 -1
Author: Farhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-17 20:30:43

Spróbuj tego: char c=S. nextLine ().charAt (0);

 -1
Author: Harshal Mande,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-14 14:28:28
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

Przy okazji, nie możesz przyjmować znaku bezpośrednio jako wejścia. Jak widać powyżej, łańcuch jest najpierw pobierany, a następnie charAt( 0); jest znaleziony i przechowywany

 -1
Author: Arafe Zawad Sajid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-23 02:52:44

Po prostu użyj...

Scanner keyboard = new Scanner(System.in);<br>
char c = keyboard.next().charAt(0);
To wszystko...
 -1
Author: Razoowp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-15 04:02:11

Możesz użyć typecastingu:

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

W ten sposób będziesz pobierał dane w łańcuchu ze względu na funkcję " next ()", ale następnie zostanie on przekonwertowany na znak ze względu na znak "char" wymieniony w nawiasach.

Ta metoda konwersji typu danych poprzez podanie docelowego typu danych w nawiasach nazywa się typecating. U mnie działa, Mam nadzieję, że u:)

 -2
Author: Nihaarika,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-26 20:35:10

Aby znaleźć indeks znaku w danym żądle, możesz użyć tego kodu:

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

    }

}
 -3
Author: Robi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-11 00:39:06

Najprostszym sposobem jest, najpierw zmień zmienną na łańcuch znaków i zaakceptuj wejście jako łańcuch znaków. Następnie można sterować w oparciu o zmienną wejściową za pomocą instrukcji if-else lub switch w następujący sposób.

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>
}
 -7
Author: AndroidShifu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-18 16:42:32