用扫描仪读取输入;输出打印两次

时间:2014-08-27 11:04:18

标签: java string java.util.scanner

我有以下课程

import java.util.Scanner;

public class Album{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        System.out.println("How many songs do your CD contain?");
        int songs = sc.nextInt();

        String[] songNames = new String[songs];

        for (int i = 0; i < songs; i++) {
            System.out.println("Please enter song nr " + (i+1) + ": ");
            songNames[i] = sc.nextLine();
            // What is wrong here? (See result for this line of code)
            // It is working when I use "sc.next();"
            // but then I can't type a song with 2 or more words.
            // Takes every word for a new song name. 
        }

        System.out.println();
        System.out.println("Your CD contains:");
        System.out.println("=================");
        System.out.println();

        for (int i = 0; i < songNames.length; i++) {
            System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
        }
    }
}

我无法键入歌曲名称nr 1,因为它始终显示前两个。

如果我输入3,就像这样:

How many songs do your CD contain?
3
Please enter song nr 1:
Please enter song nr 2: 

5 个答案:

答案 0 :(得分:3)

更改

int songs = sc.nextInt();

为:

int songs = Integer.parseInt(sc.nextLine().trim());

它会正常工作。

您不应将nextIntnextLine的用法混合使用。

答案 1 :(得分:1)

sc.nextLine();

之后添加int songs = sc.nextInt();

输入数字并使用扫描仪(作为数字)使用sc.nextInt();读取数字后,换行符字符将出现在输入流中,当您执行此操作时将会读取该字符sc.nextLine()。因此,要跳过(覆盖)它,您需要在sc.nextLine()

之后致电sc.nextInt();

答案 2 :(得分:0)

sc.nextLine()之后添加sc.nextInt(),您的代码可以正常使用。

原因是您输入歌曲名称后的行尾。

答案 3 :(得分:0)

使用nextIntnextLine,我会选择nextLine

import java.util.Scanner;

public class Album{

  public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    System.out.println("How many songs do your CD contain?");
    int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt()

    String[] songNames = new String[songs];

    for (int i = 0; i < songs; i++) {
        System.out.println("Please enter song nr " + (i+1) + ": ");
        songNames[i] = sc.nextLine();
        // What is wrong here? (See result for this line of code)
        // It is working when I use "sc.next();"
        // but then I can't type a song with 2 or more words.
        // Takes every word for a new song name. 
    }

    System.out.println();
    System.out.println("Your CD contains:");
    System.out.println("=================");
    System.out.println();

    for (int i = 0; i < songNames.length; i++) {
        System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
    }
  }
}

答案 4 :(得分:0)

放一个sc.nextLine();在int songs = sc.nextInt();

之后