logo

Java skeneris nextLine() metode

The nextLine() Java Scanner klases metode tiek izmantota, lai iegūtu skenera objekta ievades virkni.

Sintakse

Tālāk ir sniegta deklarācija nextLine() metode:

 public String nextLine() 

Parametrs

Šī metode nepieņem nevienu parametru.

Atgriežas

The nextLine() metode atgriež rindu, kas tika izlaista.

Izņēmumi

NoSuchElementException - Tas izmetīs šo izņēmumu, ja netiks atrasta neviena līnija.

IllegalStateException - Šis izņēmums tiks parādīts, ja izsaukšana tiks veikta pēc skenera aizvēršanas.

ankita lokhande vecums

Saderības versija

Java 1.5 un jaunāka versija

1. piemērs

 import java.util.*; public class ScannerNextLineExample1 { public static void main(String args[]){ Scanner scan = new Scanner(System.in); System.out.print('Enter Item ID: '); String itemID = scan.nextLine(); System.out.print('Enter Item price: '); String priceStr = scan.nextLine(); double price = Double.valueOf(priceStr); System.out.println('Price of Item '+itemID + ' is $'+price); scan.close(); } } 

Izvade:

 Enter Item ID: A151 Enter Item price: 3473.75 Price of Item A151 is 73.75 

2. piemērs

 import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class ScannerNextLineExample2 { public static void main(String args[]) throws FileNotFoundException{ // Declare File object File file = new File('/home/javatpoint/Desktop/ABHISHEK/AngularJS/Index/abc.txt'); // initialize the scanner Scanner scan = new Scanner(file); // iterate through the file line by line while(scan.hasNextLine()){ // print the contents of a file by line System.out.println(scan.nextLine()); } // close the scanner object; scan.close(); } } 

Izvade:

 hasNextLine public boolean hasNextLine() IllegalStateException 

3. piemērs

 import java.util.*; public class ScannerNextLineExample3 { public static void main(String args[]){ String str = 'Facebook.com 
 1 + 1 = 2.0 
 JavaTpoint.com '; Scanner scanner = new Scanner(str); //Print the next line System.out.println(scanner.nextLine()); //Check if there is a next line again System.out.println(scanner.hasNextLine()); System.out.println(scanner.nextLine()); //Check if there is a next line again System.out.println(scanner.hasNextLine()); System.out.println(scanner.nextLine()); //Check if there is a next line again System.out.println(scanner.hasNextLine()); scanner.close(); } } 

Izvade:

 Facebook.com true 1 + 1 = 2.0 true JavaTpoint.com false