【发布时间】:2018-10-20 15:12:37
【问题描述】:
这个问题和我之前的问题有关:
Java does not differ between 2 String variables in array of objects for loop proplem
@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)+"作者姓名:");但是什么也没发生,它让我输入了这两个值,但是当对象被打印时,标题被错过了!
等待您的帮助 非常感谢你
【问题讨论】:
-
我试图理解问题的标题,但我无法理解。
-
您的问题是完全重复,您需要了解这一点才能继续前进。您正在混合面向行的输入和非面向行的输入。
input.nextLine();需要在input.nextDouble();之后(因为 that 会留下一个尾随换行符 - 20.0 不包含\n)。 或者,或者 总是使用input.nextLine()并解析double、int,或者你自己的任何东西——这样可以避免问题。 -
String email=input.next();和double price=input.nextDouble();被枚举examples在使用后跳过nextLine()next()或nextFoo() -
@ElliottFrisch Frisch 我看不懂,如果你能通过代码告诉我,因为我无法通过理论说明来理解,我将非常感激
标签: java string class object variables