gpt4 book ai didi

java - 用一台扫描仪读取两个字符串

转载 作者:行者123 更新时间:2023-12-01 19:56:12 25 4
gpt4 key购买 nike

我有一个扫描仪,它首先读取标题,然后读取用户输入的两个单词,用空格分开,然后将它们放入导演姓名和导演姓氏中:但是使用下面的代码我收到错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at MainSystem.addBook(MainSystem.java:57)
at MainSystem.main(MainSystem.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

代码:

private static void addBook() {

System.out.println("\nEnter title: ");
title = scanner.next();

System.out.println("\nEnter director: ");
String[] parts = scanner.next().split(" ");
directorName = parts[0];
directorSurname = parts[1];

}

编辑:为了调用方法 add book 我也早些时候使用了扫描仪 - 也许这是问题所在:

 System.out.println("\nEnter 0 for loading the Library." +
"\nEnter 1 for save and quit" +
"\nEnter 2 for list all the Books in the Library." +
"\nEnter 3 for add Book to the Library.");

int answer = scanner.nextInt();

最佳答案

您需要使用 nextLine 方法获取输入。以下是我在 eclipse 中尝试的工作版本

编辑:根据问题中的新编辑更新了代码。每当给出整数作为输入并按回车键时,换行符就会作为下一个扫描器的输入。因此,在获取输入后编写一个 nextLine() 。更新的代码按照编辑的问题工作。

import java.util.Scanner;

public class Snippet {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter 0 for loading the Library."
+ "\nEnter 1 for save and quit"
+ "\nEnter 2 for list all the Books in the Library."
+ "\nEnter 3 for add Book to the Library.");

int answer = scanner.nextInt();
scanner.nextLine();
if(answer == 3)
addBook();
}

private static void addBook() {
System.out.println("Enter title: ");
String title = scanner.nextLine();
System.out.println("Enter director: ");
String[] parts = scanner.nextLine().split(" ");
String directorName = parts[0];
String directorSurname = parts[1];
System.out.println("title : " + title);
System.out.println("directorname : " + directorName);
System.out.println("directorsurname : " + directorSurname);
}
}

关于java - 用一台扫描仪读取两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49667080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com