java - 通过 .nextLine 从文件中读取

标签 java indexoutofboundsexception

当我运行我的程序时,出现以下错误。它运行文件中的第一行,但是当它返回到主方法中的循环来处理第二行时,这就是我得到的。

java.lang.ArrayIndexOutOfBoundsException: 1 
    at Popcorn.barGraphByLine(Popcorn.java:94)
    at Popcorn.main(Popcorn.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

我的代码:

import java.io.*;
import java.util.*;

public class Popcorn
{

public static void main(String args[])throws IOException
{

printHeading(4, "Popcorn");

//This will call a method to validate a user input as a file name, then
//create a Scanner object to read from the FileReader object
String fileName = validatedFileName();
Scanner inFromFile = new Scanner(new FileReader("Test.txt"));

printBarGraphHeader();

while(inFromFile.hasNextLine())
{
  String thisLine = inFromFile.nextLine();
  barGraphByLine(thisLine);
}


inFromFile.close();
}

private static String validatedFileName()
{
Scanner keyboardIn = new Scanner(System.in);

System.out.print("Please enter a file name.");
String tryName = keyboardIn.next();
File createFile = new File(tryName);

while(!createFile.exists())
{
  System.out.print("The file name you entered is invalid, Please enter a
  vaild file name.");
  tryName = keyboardIn.next();
  createFile = new File(tryName);
} 
keyboardIn.close();
return tryName;
}

public static void printBarGraphHeader()
{
System.out.println("                     Popcorn Co-Op                   ");
System.out.println();
System.out.println("                             Production in Hundreds  ");
System.out.println("                             of Pint Jars per Acre   ");
System.out.println("Farm Name                       1   2   3   4   5   6");
System.out.println("                             ---|---|---|---|---|---|");
}


public static void barGraphByLine(String str)
{
String acresString = "";
String jarsString = "";

//This takes any spaces of one or more grouped together and replaces it
//with a single space.
str = str.replaceAll("\\s+" , " ");

//This takes the String str that is composed of the entire line from the file and splits it into two strings at the
//comma, since every name has a comma after it.
String[] splitStr = str.split(", ", 2);

String str1 = splitStr[0];
String str2 = splitStr[1];

String farmName = str1;

Scanner readStr2 = new Scanner(str2);

while(readStr2.hasNext())
{

  acresString = readStr2.next();

  jarsString = readStr2.next();

}

double acres = Double.parseDouble(acresString);
double jars = Double.parseDouble(jarsString);
double jarsPerAcre = jars/acres;

String graphStars = "";
if(jarsPerAcre < 400)
{
  for(int count = 25; count < jarsPerAcre; count += 25)
  {
    graphStars += "*";
  }
  for(int count = 375; count >jarsPerAcre;count -= 25)
  {
    graphStars = graphStars + " ";
  }
  graphStars = graphStars + "|";
}
else
{
  for(int count = 25; count < 400; count += 25)
  {
    graphStars += "*";
  }
  graphStars += "#";
  for(int count = 400; count < jarsPerAcre; count += 25)
  {
    graphStars += "*";
  }
}


int afterNameSpaceCount = 29 - farmName.length();
for(int count = 0; count < afterNameSpaceCount; count++)
{
  farmName = farmName + " ";
}

System.out.println(farmName + graphStars);

readStr2.close();
}  
}

最佳答案

看看这些行:

while (readStr2.hasNext()) {
  acresString = readStr2.next();
  jarsString = readStr2.next();
}

这里您调用了 next() 方法两次,并且没有对第二次调用的 hasNext() 进行显式检查。您面临 NoSuchElementException 的风险,它与您的问题没有直接关系,但您会发现下一个问题。

如果你想读取两个字符串,你必须每次调用hasNext()。但是,请注意:在您的代码中,如果 while 语句循环超过 2 次,您将丢失从 readStr2 读取的一些值。

关于java - 通过 .nextLine 从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28871451/

相关文章:

java - Java 中从类到主类的用户输入

java - JavaFX 的 OutOfBoundsException

java.lang.StringIndexOutOfBoundsException : when using PolyUtil. 解码

java - ArrayIndexOutOfBoundsException 的数组足够大,可以容纳我提供的数据

java - JTable setValueAt 不工作

java - 使用 spring 中的 Rest 模板通过 post 调用发送 json 数据

java - 如何让媒体 Controller 工作

java.lang.UnsatisfiedLinkError 即使库和类有方法

java - 使用 Hashmap 进行字符串分组

java - 有时 ArrayIndexOutOfBoundsException,有时代码运行完美?