English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Testo
Fino a Java 1.5, i programmatori utente dipendevano dalle classi di flusso di caratteri e di flusso di byte per leggere i dati.
Per impostazione predefinita, gli spazi vengono considerati delimitatori (che dividono i dati in token).
Legge vari tipi di dati provenienti dalla sorgentenextXXX()
I metodi forniti da questa classe includononextInt()
,nextShort()
,nextFloat()
,nextLong()
,nextBigDecimal()
,nextBigInteger()
,nextLong()
,nextShort()
,nextDouble()
,nextByte()
,nextFloat()
,next()
。
Puoi passare un oggetto Scanner come parametro al metodo.
Il seguente programma Java dimostra come passare un oggetto Scanner al metodo. L'oggetto Scanner legge il contenuto del file.
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class ScannerExample { public String sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); while(sc.hasNext()) { sb.append(sc.nextLine()); } return sb.toString(); } public static void main(String args[]) throws IOException { //Istanziazione della classe inputStream InputStream stream = new FileInputStream("D:\\sample.txt"); //Instanziamento della classe Scanner Scanner sc = new Scanner(stream); ScannerExample obj = new ScannerExample(); //Chiamata al metodo String result = obj.sampleMethod(sc); System.out.println("Contenuto del file:"); System.out.println(result); } }
Contenuto del file: oldtoolbag.com was born from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
Nell'esempio seguente, creiamo un oggetto Scanner con sorgente standard (System.in) e lo passiamo come parametro al metodo.
import java.io.IOException; import java.util.Scanner; public class ScannerExample { public void sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); System.out.println("Inserisci il tuo nome:"); String name = sc.next(); System.out.println("Inserisci la tua età:"); String age = sc.next(); System.out.println("Hello " + name + " tu hai " + age + " anni"); } public static void main(String args[]) throws IOException { //Instanziamento della classe Scanner Scanner sc = new Scanner(System.in); ScannerExample obj = new ScannerExample(); //Chiamata al metodo obj.sampleMethod(sc); } }
Inserisci il tuo nome: Krishna Inserisci la tua età: 25 Hello Krishna, tu hai 25 anni