LoginSignup
1
0

More than 3 years have passed since last update.

備忘録: next・nextLine(paizaラーニング Java入門編9:#06にて)

Last updated at Posted at 2019-08-23

本日paizaのJava入門編9で以下のコードを書きました。

入力は以下

6
回復薬

クリスタル
クリスタル

出力は以下
※画像が6つ表示されると成功


// 画像を順番に出力する
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // 画像用ハッシュ
        HashMap<String, String> itemImages  = new HashMap<String, String>();
        itemImages.put("剣", "http://paiza.jp/learning/images/sword.png");
        itemImages.put("盾", "http://paiza.jp/learning/images/shield.png");
        itemImages.put("回復薬", "http://paiza.jp/learning/images/potion.png");
        itemImages.put("クリスタル", "http://paiza.jp/learning/images/crystal.png");

        // ここから下を書く
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        String[] itemOrders = new String[num];

        for (int i = 0 ; i < num; i++) {
            itemOrders[i] = sc.next();
        }

        for (String itemName : itemOrders) {
            System.out.println("<img src = '" + itemImages.get(itemName) + "'>");
            System.out.println("<br>");
        }
    }
}

ここで上記の

for (int i = 0 ; i < num; i++) {
            itemOrders[i] = sc.next();
        }

の部分を

for (int i = 0 ; i < num; i++) {
            itemOrders[i] = sc.nextLine();
        }

とかくと、

入力値の最初の「6」を読み込み、
最後の「剣」を読み込まないせいか、

スクリーンショット 2019-08-23 20.09.14.png

のようになりました。

nextLineの部分をnextに直すと

スクリーンショット 2019-08-23 20.09.35.png

となり、成功しました。

※画像引用:
paiza様より
https://paiza.jp/works/8nxtlwO8hADExEsUB3PO29UQOrhMK6eR/output.html
https://paiza.jp/works/aEjXurY_tyZM-09Y8aqCbLkvgw7p-V9h/output.html
より

原因を色々と調べた結果、
前のnextIntの影響を受けて、nextLineの性質上、
nextIntで読み込んだ数字の部分を空白として読み込んでしまったのだと思われます。

nextにして直ったのは、空白まで認識するnextLineと違って、改行で認識されるため、
nextIntで読み込んだ部分をnextは認識しなかったからだと考えました。

・・・とはいえこれがあってるかわからないので、知っている人がいましたら、
教えてくださるととってもとってもありがたいです・・・・!!!!!!!!!!!!!

1
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
1
0