LoginSignup
0
0

More than 3 years have passed since last update.

nextIntとnextLineとsubstringを使うとエラーになった。

Last updated at Posted at 2020-07-08
import java.util.Scanner;

/*
原因はnextInt
nextIntで123と入力すると
Java側では123\nに変換され(末尾に\nが入る。)
nextIntは123だけを返す
次にnextLineを入力すると先ほどの残った\nが読み込まれ
エラーが発生する。

解決法は
変数への代入を伴わないnextLineを記述する。(以下のソースのscanner.nextLine())
これをすることで\nが消去され次にnextLineが正常に動く

※nextIntは\nを消す機能がないためnextLineを入れる必要がある。
※バックスラッシュとnで改行を表す。

*/
public class Hello {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int a = 0;
        int b = 0;
        String str = "";

        a = scanner.nextInt();
        b = scanner.nextInt();
        scanner.nextLine();
        str = scanner.nextLine();
        System.out.println(str.substring(a - 1, b));
    }
 }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0