logo

Scanner i nextChar() a Java

Classe d'escàner en Java admet nextInt(), nextLong(), nextDouble() etc. Però no hi ha nextChar() (vegeu això per exemples) Per llegir un caràcter, fem servir next().charAt(0) . La funció next() retorna el següent testimoni/paraula a l'entrada com a cadena i la funció charAt(0) retorna el primer caràcter d'aquesta cadena, el número 0 a la funció de CharAt( NÚMERO ) representa l'índex de la paraula única de la cadena introduïda i estableix aquest caràcter d'índex a la variable char.

Java








// Java program to read character using Scanner> // class> import> java.util.Scanner;> public> class> ScannerDemo1 {> >public> static> void> main(String [] args){> >Scanner sc =>new> Scanner(System.in);> >char> c = sc.next().charAt(>1>);> >// here this is the indexing of the element to take //> >System.out.println(>'c = '>+c);> >}> > }> > > >



>

>

Entrada:

ge>

Sortida:

c = e>