gpt4 book ai didi

java - 创建一个简单的文本菜单 : String out of bonds expection ( range 0 ) Java

转载 作者:行者123 更新时间:2023-11-30 09:16:38 25 4
gpt4 key购买 nike

我正在尝试创建一个菜单,通过 numbersystem 方法将一组数字打印到屏幕上。当我尝试循环我的菜单时,出现以下错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at homework4_5.Driver.engageDriver(Driver.java:31)
at homework4_5.Driver.engageDriver(Driver.java:47)
at homework4_5.Driver.main(Driver.java:18)

我也相信我的方法 NumberSystem 不是问题所在。 (与使用其他输入法一样,我可以获得产生正确结果的方法。)

我在使用文本菜单时经常遇到这个问题。谁能帮我?我认为可能是扫描器收到了一个空字符串,无法从中解析 int

import java.util.Scanner;

public class Driver {
Scanner sc = new Scanner (System.in);

public int baseCount = 0;
public int numOfCols = 0;
public boolean loop = true;


public static void main(String[] args){
Driver driver = new Driver();
driver.engageDriver();
}


public void engageDriver(){
NumberSystem ns = new NumberSystem();
System.out.println("Hello, please enter the numeric value corresponding to your counting/base system" );
String temp = sc.nextLine();

if(temp.charAt(0)== 'q'){
System.out.println("Shutting Down the program...Thank You!");
loop = false;
return;
}
baseCount = Integer.parseInt(temp);

System.out.println("Now enter how many columns you would like to display ( a value from 1 to 3 ) ");
numOfCols=sc.nextInt();
System.out.println("The number table you requested is:\n ");

ns.printNumberSystem(baseCount, numOfCols);
if(loop){
engageDriver();
}
}
}

最佳答案

从堆栈跟踪可以清楚地看出,当 charAt 被调用时,temp 是空的。在尝试调用此方法之前检查 String 是否包含内容

if (!temp.isEmpty() && temp.charAt(0) == 'q') {

主要问题是 Scanner#nextInt 不使用换行符。因此,您需要使用这些字符以确保它们不会在 engageDriver

的递归调用中通过 InputStream 传回
numOfCols = sc.nextInt();
sc.nextLine();

关于java - 创建一个简单的文本菜单 : String out of bonds expection ( range 0 ) Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361968/

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