Java作业(使用for循环填充数组)

标签 java methods for-loop

我只是在学习 Java 的第二个学期,所以我的问题可能有一个非常简单的解决方案,但因此我已经纠结了几个小时。以下代码用于收集用户输入并将实例的信息存储在数组中。

没有机会为相册名称输入任何内容。输出结果如下。

Enter 5 songs

Title: title
Author: author1
Interpreter: int1
Year released: 2000
Album: File name: //Why doesn't this collect input and place File name: on the next line.

如果有人能指出正确的方向,我将不胜感激。我包括以下两种方法,以防它们与我的问题有关。感谢您提供的任何帮助。

    public static void main(String[] args){

    Scanner kybd = new Scanner(System.in);

    Song[] songTest = new Song[5];

    System.out.println("Enter 5 songs\n");


    //TEST
    for(Song x:songTest)
    {
        x = new Song();
        System.out.print("Title: ");
        x.setTitle(kybd.nextLine());
        System.out.print("Author: ");
        x.setAuthor(kybd.nextLine());
        System.out.print("Interpreter: ");
        x.setInterpreter(kybd.nextLine());
        System.out.print("Year released: ");
        x.setYearReleased(kybd.nextInt());
        System.out.print("Album: ");
        x.setAlbum(kybd.nextLine()); //this doesn't allow for input.  it prints "File name:" and skips the user input for an album name.  Also, when I comment out Year released, the problem goes away.
        System.out.print("File name: ");
        x.setFileName(kybd.nextLine());
        System.out.print(x);
        System.out.println();
    }


public void setYearReleased(int y)
{
    if (y>0 && y<2013)
        this.yearReleased = y;
    else
    {
        System.out.print ("This song is not that old");
        this.yearReleased = -5;
    }
}

    public void setAlbum(String a)
{
    this.album = a;
}

最佳答案

您需要在 kybd.nextInt() 之后执行 kybd.nextLine() 以便以下 kybd.nextLine() 执行不捕获为 nextInt() 按下回车键时使用的换行符。

关于Java作业(使用for循环填充数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12555334/

相关文章:

java - 添加 JMenuBar 并将其设置为可见后,Eclipse 不显示 JMenu 项目?

创建一个包含 100 个节点的链表,每个节点包含一个随机数 C

python - 打印 Pandas 数据框中每一列的唯一值

java - 使用 itext 读取 PDF 时获取字符串和 int 值的正确方法是什么?

java - Derby "A truncation error was encountered trying to shrink CLOB ' <流值 >' to length 255"

java - java中的输入检查方法

java - Java 代码的等效 Scala 代码不起作用(方法签名无效)

c++ - for循环中的条件不执行

java.io.IOException : Server returned HTTP response code: 403 for URL: http://start. spring.io

java - 非泛型类中的 Java 泛型问题