java - 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)+"作者姓名:"); 但是什么也没发生,它让我输入了这两个值,但是当对象被打印时,标题被错过了!
等待您的帮助,非常感谢
解决方案
正如它在对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");
}
推荐阅读
- r - 生成具有 15 分钟时间间隔和今天日期的字符串 csv 名称列表
- php - PHP/Laravel,带有多个参数的 url
- html - 如何将样式/样式表应用于我用来在反应中打印特定 div 的隐藏 iframe
- sql - 如何使用 SQL 函数合并 Bigquery 中的重复值
- python - 如何将具有外键的 django 模型导出到 csv
- npm - Vue 3 安装挂起
- mern - 我的网站有时无法为用户加载,并显示“无法访问此网站”
- dart - Dart 函数框架使用
- linux - 跳转服务器中内部服务器之间的连接
- swupdate - 如何使用 sendtohawkbit 或 Suricatta 守护程序向 hawkbit 发送反馈消息?