logo

Java のスキャナー nextLine() メソッドと例

nextLine() の方法 java.util.スキャナ クラスは、このスキャナを現在の行を越えて進め、スキップされた入力を返します。この関数は、最後の行区切り文字を除いて、現在の行の残りを出力します。 next は行区切り文字の後に設定されます。このメソッドは入力全体を検索して行区切り文字を探し続けるため、行区切り文字が存在しない場合はスキップする行を検索してすべての入力を検索する可能性があります。

構文:



tkinterボタン
public String nextLine()>

パラメーター: この関数はパラメータを受け入れません。

戻り値: このメソッドは、 ライン それはスキップされました

例外: この関数は、次に説明する 2 つの例外をスローします。



    NoSuchElementException: 行が見つからなかった場合にスローします。 IllegalStateException: このスキャナが閉じている場合にスローします。

以下のプログラムは上記の機能を示しています。

プログラム 1:






文字列の値
// Java program to illustrate the> // nextLine() method of Scanner class in Java> // without parameter> > import> java.util.*;> > public> class> GFG1 {> >public> static> void> main(String[] argv)> >throws> Exception> >{> > >String s =>'Gfg Geeks GeeksForGeeks'>;> > >// create a new scanner> >// with the specified String Object> >Scanner scanner =>new> Scanner(s);> > >// print the next line> >System.out.println(scanner.nextLine());> > >// print the next line again> >System.out.println(scanner.nextLine());> > >// print the next line again> >System.out.println(scanner.nextLine());> > >scanner.close();> >}> }>

>

>

出力:

 Gfg Geeks GeeksForGeeks>

プログラム 2: NoSuchElementException をデモンストレーションするには

数学パウJava




// Java program to illustrate the> // nextLine() method of Scanner class in Java> > import> java.util.*;> > public> class> GFG1 {> >public> static> void> main(String[] argv)> >throws> Exception> >{> > >try> {> > >String s =>''>;> > >// create a new scanner> >// with the specified String Object> >Scanner scanner =>new> Scanner(s);> > >System.out.println(scanner.nextLine());> >scanner.close();> >}> >catch> (Exception e) {> >System.out.println(>'Exception thrown: '> + e);> >}> >}> }>

>

Javaで配列を初期化する

>

出力:

 Exception thrown: java.util.NoSuchElementException: No line found>

プログラム 3: IllegalStateException を示すには




Javaは文字列をintに変換します
// Java program to illustrate the> // nextLine() method of Scanner class in Java> // without parameter> > import> java.util.*;> > public> class> GFG1 {> >public> static> void> main(String[] argv)> >throws> Exception> >{> > >try> {> > >String s =>'Gfg'>;> > >// create a new scanner> >// with the specified String Object> >Scanner scanner =>new> Scanner(s);> > >scanner.close();> > >// Prints the new line> >System.out.println(scanner.nextLine());> >scanner.close();> >}> >catch> (Exception e) {> >System.out.println(>'Exception thrown: '> + e);> >}> >}> }>

>

>

出力:

 Exception thrown: java.lang.IllegalStateException: Scanner closed>

参照: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()