首页 > 解决方案 > Java 在对象的 2 个字符串变量数组之间没有区别(更新)

问题描述

这个问题与我之前的问题有关:

Java在循环问题的对象数组中的2个字符串变量之间没有区别

@JB Nizet 给了我这个链接并将我的问题标记为重复:Scanner is skipping nextLine() after using next() or nextFoo()?

但我尝试按照他们所说的去做,但效果不佳,你可以看到我按照他们所说的做了:

3- 主要课程:

import java.util.Scanner;
public class BookTest {

    public static void main(String[] args) {
       Scanner input= new Scanner(System.in);

       // 1. making array of books (Array of objects):
       Book[] books= new Book[3];

       //2. store the values into an array of objects:

        for (int i = 0; i <books.length; i++) {
            System.out.print("Enter book "+ (i+1)+ " title: ");
            String title=input.nextLine();
            input.nextLine();
            System.out.println("Enter book "+(i+1)+" author's name:");
            String name=input.nextLine();

            System.out.print("Enter book "+ (i+1)+ " price: ");
            double price=input.nextDouble();

            System.out.println("Enter book "+(i+1)+" author's email: ");
            String email=input.next();

            Author a=new Author(name,email);

            books[i]=new Book(title,price,a);

            System.out.println(books[i]+"\n");

        }

    }

}

如您所见,我添加了一个 input.nextLine(); 字符串之间的行 title=input.nextLine(); and System.out.println("输入书"+(i+1)+"作者姓名:"); 但是什么也没发生,它让我输入了这两个值,但是当对象被打印时,标题被错过了!

看看运行: 在此处输入图像描述

等待您的帮助,非常感谢

标签: javastringclassobjectvariables

解决方案


正如它在对Scanner 的回答中所说的那样,在使用 next() 或 nextFoo() 之后跳过了 nextLine()?,您必须在每个 next() 或 nextFoo() 之后使用尾随的新行。喜欢,

for (int i = 0; i < books.length; i++) {
    System.out.print("Enter book " + (i + 1) + " title: ");
    String title = input.nextLine();
    // NOT HERE. input.nextLine();
    System.out.println("Enter book " + (i + 1) + " author's name:");
    String name = input.nextLine();

    System.out.print("Enter book " + (i + 1) + " price: ");
    double price = input.nextDouble(); // next or nextFoo
    input.nextLine(); // Scanner is skipping nextLine

    System.out.println("Enter book " + (i + 1) + " author's email: ");
    String email = input.next(); // next or nextFoo
    input.nextLine(); // Scanner is skipping nextLine
    Author a = new Author(name, email);
    books[i] = new Book(title, price, a);
    System.out.println(books[i] + "\n");
}

或者,正如那个出色的答案中所建议的那样,自己解析输入并始终使用nextLine(). 喜欢,

for (int i = 0; i < books.length; i++) {
    System.out.print("Enter book " + (i + 1) + " title: ");
    String title = input.nextLine();
    // NOT HERE. input.nextLine();
    System.out.println("Enter book " + (i + 1) + " author's name:");
    String name = input.nextLine();

    System.out.print("Enter book " + (i + 1) + " price: ");
    String pr = input.nextLine();
    double price = Double.parseDouble(pr);

    System.out.println("Enter book " + (i + 1) + " author's email: ");
    String email = input.nextLine();
    Author a = new Author(name, email);
    books[i] = new Book(title, price, a);
    System.out.println(books[i] + "\n");
}

推荐阅读