Я получаю следующую ошибку при запуске моей программы. Он проходит через первую строку в файле, но когда он возвращается к циклу в основном методе обработки второй строки, это то, что я получаю.чтение из файла .nextLine
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();
}
}
'String str1 = splitStr [0]; String str2 = splitStr [1]; 'он должен быть там - ваше регулярное выражение для разделения? – rzysia
Данные всегда будут иметь значение: Некоторые названия фермы, #ofacres #ofjars (со случайными промежутками между промежутками) , поэтому я знаю, что он будет разделен на две части с одной запятой в линия. –
так возможно, что после запятой нет пробела? put 'System.out.println (table.lenght)', печатать переменные - это поможет вам найти ответ :) – rzysia