每次我尝试运行文件以显示图形时,它都会完成大部分程序,直到GraphAtOrigin类为止。这是引发错误的地方,提示“ IndexOutOfBoundsException:索引0超出长度0的范围”。因此,我认为将domainList字符串ArrayList转换为domainNumList Double ArrayListsome的wat出了点问题,或者当我尝试从CreateGraphInterior类获取double数组时遇到了问题。我该怎么做才能防止此异常并允许代码运行?
我已经尝试了使用各种技巧将String ArrayList转换为Double ArrayList,但是如果您有更好的方法,请告诉我。
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class GraphProject {
public static JTextField depStart = new JTextField(10);
public static JTextField depEnd = new JTextField(10);
public static JTextField indStart = new JTextField(10);
public static JTextField indEnd = new JTextField(10);
public static JFrame main = new JFrame("Input The Graph Scale");
public static JButton submit = new JButton("Submit");
// for the input of Title, subtitle, and units
public static JFrame getInfo = new JFrame("Input The Graph Information");
public static JTextField gTitle = new JTextField(10);
public static JTextField gSubTitle = new JTextField(10);
public static JTextField depAxisUnit = new JTextField(10);
public static JTextField indAxisUnit = new JTextField(10);
public static JButton submitInfo = new JButton("Submit");
public static boolean selected = false;
public static boolean noSelected = false;
public static int dataLength;
public static double domainMax;
public static double rangeMax;
public static ArrayList<String> rangeList = new ArrayList<String>();
public static ArrayList<String> domainList = new ArrayList<String>();
public static void main(String[] args)throws Exception {
// Used to print out the data from the txt file
/*
ArrayList<String> result = new ArrayList<>();
FileReader fr = new FileReader("DataSetValues.txt");
int i;
while((i=fr.read()) != -1){
System.out.print((char)i);
}
*/
readData1();
readData2();
ObtainGraphInfo getGraphInfo = new ObtainGraphInfo();
getGraphInfo.graphInfo();
}
// Creates the Option Pane for user to input axis start and end positions
public static void axisPositions(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean yes = false;
boolean no = false;
JCheckBox startAtOrigin = new JCheckBox("Yes", yes);
startAtOrigin.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
selected = true;
makeGraph();
System.out.println("run the method to make the points graph at origin (0,0)");
main.dispose();
}
}
});
JCheckBox dontStartAtOrigin = new JCheckBox("No", no);
dontStartAtOrigin.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
noSelected = true;
makeGraph();
System.out.println("run the method to stop the points from graphing at the origin (0,0)");
main.dispose();
}
}
});
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
main.setContentPane(gui);
main.setLocationRelativeTo(null);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Do you want the points to begin graphing "));
controls.add(startAtOrigin);
labels.add(new JLabel(" with the origin (0,0)? "));
controls.add(dontStartAtOrigin);
/*labels.add(new JLabel("Independent Axis Start Position: "));
controls.add(indStart);
labels.add(new JLabel("Independent Axis End Position: "));
controls.add(indEnd);*/
// Codes for the action performed when the submit button is pressed
submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){
submit = (JButton)e.getSource();
main.dispose();
makeGraph();
}
});
gui.add(submit, BorderLayout.SOUTH);
main.getRootPane().setDefaultButton(submit);
main.pack();
submit.setVisible(false);
main.setVisible(true);
}
// Read the data from txt file and put it into an arrayList then separate into domain and range arrayLists
public static ArrayList<String> readData1() throws Exception{
ArrayList<String> dataList = new ArrayList<String>();
File file = new File("C://Users//wildc//Desktop//ToMac//Computer Science//Java Programs//GraphProjectFolder//testValues.txt");
Scanner scanData = new Scanner(file);
try{
while (scanData.hasNext()){
dataList.add(scanData.next());
}
int position = 0;
for (int counter = 0; counter < ((dataList.size()/2) + 1) ; counter ++ ) {
domainList.add(dataList.get(position));
position = (position + 2);
}
scanData.close();
//Creating domainList
} catch(Exception e) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran 1");
}
System.out.println(domainList.size() + " This is the Domain SIzeS");
System.out.println(domainList + "This is the domain List");
System.out.println(dataList + "This is the data list");
dataLength = domainList.size();
domainMax = Double.parseDouble(Collections.max(domainList));
System.out.println(domainMax + " : Domain max");
return domainList;
}
public static ArrayList<String> readData2() throws Exception{
ArrayList<String> dataList = new ArrayList<String>();
File file = new File("C://Users//wildc//Desktop//ToMac//Computer Science//Java Programs//GraphProjectFolder//testValues.txt");
Scanner scanData = new Scanner(file);
try{
while (scanData.hasNext()){
dataList.add(scanData.next());
}
scanData.close();
//Creating rangeList
int position = 1;
for (int counter = 0; counter < ((dataList.size()/2) + 1) ; counter ++ ) {
rangeList.add(dataList.get(position));
position = (position + 2);
}
// Was used to replace a certain element with another (incomplete)
}catch(Exception e) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran 2");
}
rangeMax = Double.parseDouble(Collections.max(rangeList));
System.out.println(rangeMax + " : Range max");
return rangeList;
}
//Displaying the frame for the graph to be on
public static void makeGraph(){
JFrame graph = new JFrame();
graph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
graph.setSize(1000,1000);
graph.setTitle("Test Graph Scales");
graph.setLocationRelativeTo(null);
CreateGraphOutline graphFrame = new CreateGraphOutline();
CreateGraphInterior verticalLines = new CreateGraphInterior();
graph.add(graphFrame);
graph.setVisible(true);
graph.add(verticalLines);
graph.setVisible(true);
// TestFile testingAction = new TestFile();
//String[] testing = {"1","2","3"};
// testingAction.main(testing);
CreateGraphAttributes graphAttributes = new CreateGraphAttributes();
graph.add(graphAttributes);
GraphAtOrigin graphWithOriginStart = new GraphAtOrigin();
if (selected == true) {
graph.add(graphWithOriginStart);
graph.setVisible(true);
}
/*GraphNotAtOrigin graphNotWithOriginStart = new GraphAtOrigin();
if (noSelected == true) {
graph.add(graphNotWithOriginStart);
graph.setVisible(true);
}
makeGraph();
}*/
}}
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.util.*;
public class CreateGraphAttributes extends JComponent{
public static String whereToStart;
public static String graphTitle;
public static String graphSubTitle;
public static String depUnit;
public static String indUnit;
public static String depTitle;
public static String indTitle;
public static FontMetrics metrics;
public void paintComponent(Graphics image) {
Graphics2D graph = (Graphics2D) image;
ObtainGraphInfo graphSpecifics = new ObtainGraphInfo();
ArrayList graphInformation = (ArrayList)graphSpecifics.setGraphAttributes();
graphTitle = graphInformation.get(0).toString();
graphSubTitle = graphInformation.get(1).toString();
depUnit = graphInformation.get(2).toString();
indUnit = graphInformation.get(3).toString();
depTitle = graphInformation.get(4).toString();
indTitle = graphInformation.get(5).toString();
// System.out.println(depAxisStartText + "," + indAxisStartText);
// title
Rectangle titleSpace = new Rectangle(200,50,600,200);
Font titleFont = new Font("Serif", Font.BOLD | Font.PLAIN, 22);
titleText(graph, graphTitle, titleSpace, titleFont);
// subtitle
Rectangle subTitleSpace = new Rectangle(200,100,600,150);
Font subTitleFont = new Font("Serif", Font.PLAIN, 14);
subTitleText(graph, graphSubTitle, subTitleSpace, subTitleFont);
// dependent axis 500, 700
Rectangle depTitleSpace = new Rectangle(200,600,550,150);
depAxisText(graph, depTitle, depUnit, depTitleSpace, subTitleFont);
// independent axis 10, 400
Rectangle indTitleSpace = new Rectangle(0,200,100,400);
indAxisText(graph, indTitle, indUnit, indTitleSpace, subTitleFont);
Point bottomLeftPoint = new Point(200,600);
Point bottomRightPoint = new Point(800,600); // 600px difference
Point leftBottomPoint = new Point(200,600);
Point leftTopPoint = new Point(200,200); // 400px difference
Point rightBottomPoint = new Point(800,600);
Point rightTopPoint = new Point(800,200);
Point topLeftPoint = new Point(200,200);
Point topRightPoint = new Point(800,200); // 600px difference
}
public void titleText(Graphics2D g, String text, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Draw the String
g.drawString(text, x, y);
}
public void subTitleText(Graphics2D g, String text, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Draw the String
g.drawString(text, x, y);
}
public void depAxisText(Graphics2D g, String text, String text2, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Create correct text structure
text = (text + " (" + text2 + ")");
// Draw the String
g.drawString(text, x, y);
}
public void indAxisText(Graphics2D g, String text, String text2, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Create correct text structure
text = (text + " (" + text2 + ")");
// Draw the String
g.drawString(text, x, y);
}
}
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
public class CreateGraphOutline extends JComponent{
public void paintComponent(Graphics image, boolean selected) {
Graphics2D graph = (Graphics2D) image;
Point bottomLeftPoint = new Point(200,600);
Point bottomRightPoint = new Point(800,600); // 600px difference
Line2D.Double depAxis = new Line2D.Double(bottomLeftPoint,bottomRightPoint);
BasicStroke lineThickness = new BasicStroke(4);
graph.setStroke(lineThickness);
graph.setColor(Color.BLACK);
graph.draw(depAxis);
Point leftBottomPoint = new Point(200,600);
Point leftTopPoint = new Point(200,200); // 400px difference
Line2D.Double indAxis = new Line2D.Double(leftBottomPoint,leftTopPoint);
graph.draw(indAxis);
Point rightBottomPoint = new Point(800,600);
Point rightTopPoint = new Point(800,200);
Line2D.Double rightIndAxis = new Line2D.Double(rightBottomPoint,rightTopPoint);
graph.draw(rightIndAxis);
Point topLeftPoint = new Point(200,200);
Point topRightPoint = new Point(800,200); // 600px difference
Line2D.Double topDepAxis = new Line2D.Double(topLeftPoint,topRightPoint);
graph.draw(topDepAxis);
}
}
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class ObtainGraphInfo {
public static JFrame getInfo = new JFrame("Input The Graph Information");
public static JTextField gTitle = new JTextField(10);
public static JTextField gSubTitle = new JTextField(10);
public static JTextField depAxisUnit = new JTextField(10);
public static JTextField indAxisUnit = new JTextField(10);
public static JTextField depAxisTitle = new JTextField(10);
public static JTextField indAxisTitle = new JTextField(10);
public static JButton submitInfo = new JButton("Submit");
public static GraphProject mainFile = new GraphProject();
public static ArrayList gAttributes;
public static void main(String[] args) {
}
// Prompt the user for the title, subtitle, and units of the Graph
public static void graphInfo(){
getInfo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
getInfo.setContentPane(gui);
getInfo.setLocationRelativeTo(null);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Graph Title: "));
controls.add(gTitle);
labels.add(new JLabel("Graph Sub-Title: "));
controls.add(gSubTitle);
labels.add(new JLabel("Dependent Axis Unit: "));
controls.add(depAxisUnit);
labels.add(new JLabel("Independent Axis Unit: "));
controls.add(indAxisUnit);
labels.add(new JLabel("Dependent Axis Title: "));
controls.add(depAxisTitle);
labels.add(new JLabel("Independent Axis Title: "));
controls.add(indAxisTitle);
// Codes for the action performed when the submit button is pressed
submitInfo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){
submitInfo = (JButton)e.getSource();
if (gTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (gSubTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
if (depAxisUnit.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
if (indAxisUnit.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (depAxisTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (indAxisTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
String graphTitle = gTitle.getText();
String graphSubTitle = gSubTitle.getText();
String dependentAxisUnit = depAxisUnit.getText();
String independentAxisUnit = indAxisUnit.getText();
String dependentAxisTitle = depAxisTitle.getText();
String independentAxisTitle = indAxisTitle.getText();
ArrayList graphAttributes = new ArrayList<String>();
graphAttributes.add(graphTitle);
graphAttributes.add(graphSubTitle);
graphAttributes.add(dependentAxisUnit);
graphAttributes.add(independentAxisUnit);
graphAttributes.add(dependentAxisTitle);
graphAttributes.add(independentAxisTitle);
getInfo.dispose();
makeGraphAttributes(graphAttributes);
mainFile.axisPositions();
}
}
}
}
}
}}});
gui.add(submitInfo, BorderLayout.SOUTH);
getInfo.getRootPane().setDefaultButton(submitInfo);
getInfo.pack();
getInfo.setVisible(true);
}
public static void makeGraphAttributes(ArrayList<String> graphAttributes){
gAttributes = (ArrayList) graphAttributes.clone();
System.out.println(gAttributes);
setGraphAttributes();
}
public static ArrayList<String> setGraphAttributes(){
return gAttributes;
}
}
// This is the Text File Used
0.281 0.0487
0.396 0.727
0.522 0.974
0.639 0.121
0.774 0.145
// This class creates the Double ArrayList
public class CreateGraphInterior extends JComponent{
public static ArrayList<Double> domainNumList = new ArrayList<Double>();
public static ArrayList<Double> rangeNumList = new ArrayList<Double>();
public static ArrayList<String> domainList = new ArrayList<String>();
public static ArrayList<String> rangeList = new ArrayList<String>();
public static GraphProject main = new GraphProject(); // this is where the original domainList and rangeList are found
public static int dataSize;
public static double domMax;
public static double ranMax;
public void paintComponent(Graphics image) {
main.dataLength = dataSize;
main.domainMax = domMax;
main.rangeMax = ranMax;
makeLists();
Graphics2D graph = (Graphics2D) image;
int domAxisPos = 200;
for (int counter = 0; counter < 9; counter++ ) {
Point topPoint = new Point(domAxisPos,200);
Point bottomPoint = new Point(domAxisPos,620);
Line2D.Double verticalLines = new Line2D.Double(bottomPoint,topPoint);
BasicStroke lineThickness = new BasicStroke(2);
graph.setStroke(lineThickness);
graph.setColor(Color.BLACK);
graph.draw(verticalLines);
domAxisPos = domAxisPos + 75;
}
int ranAxisPos = 600;
for (int counter = 0; counter < 9; counter++ ) {
Point leftPoint = new Point(180,ranAxisPos);
Point rightPoint = new Point(800,ranAxisPos);
Line2D.Double horizontalLines = new Line2D.Double(leftPoint,rightPoint);
BasicStroke lineThickness = new BasicStroke(2);
graph.setStroke(lineThickness);
graph.setColor(Color.GRAY);
graph.draw(horizontalLines);
ranAxisPos = ranAxisPos - 50;
}
if (main.selected == true) {
GraphAtOrigin graphWithOrigin = new GraphAtOrigin();
}
if (main.noSelected == true) {
System.out.println("Its false");
ranAxisPos = 600;
double domLabel = 0;
for (int counter = 0; counter < 9; counter++ ) {
graph.drawString(Double.toString(domLabel), domAxisPos, 650);
domLabel = domLabel + 2.0;
domAxisPos = domAxisPos - 50;
}
}
}
public static void makeLists(){
try{
domainList = main.readData1();
System.out.println(domainList + " This is domain list");
rangeList = main.readData2();
System.out.println(rangeList + " This is range list");
int count = 0;
for (int counter = 0; counter < (main.dataLength + 1) ; counter++) {
try {
//Convert String to Double, and store it into Double array list.
String domNumber = domainList.get(count);
double domNumber2 = Double.parseDouble(domNumber);
String ranNumber = rangeList.get(count);
double ranNumber2 = Double.parseDouble(ranNumber);
domainNumList.add(domNumber2);
rangeNumList.add(ranNumber2);
count = count + 1;
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran");
}
}}catch(Exception e){
System.out.println("Error arose");
}
}
}
// This is where I try to use the Double ArrayList
public class GraphAtOrigin extends JComponent{
public static GraphProject main = new GraphProject();
public static CreateGraphInterior graphInterior = new CreateGraphInterior();
// make regular unit into pixel unit
public static double oneDomPX = (domMax / 600);
public static double oneRanPX = (ranMax / 400);
public static ArrayList<Double> domainNumList = new ArrayList<Double>();;
public static ArrayList<Double> rangeNumList = new ArrayList<Double>();;
public static void plotPoints(){
domainNumList = graphInterior.domainNumList; // error occurs here
rangeNumList = graphInterior.rangeNumList;
int domPointPos = 0;
int ranPointPos = 0;
for (int counter = 0; counter < (main.dataLength + 1); counter++) {
// X data point
double domNum = domainNumList.get(domPointPos);
//A what to add to 200
double domAdd = domNum / oneDomPX;
// newX make the point relavent to the graphs location
double domPoint = domAdd + 200;
// make domPoint integer to be used on point method
int newDomPoint = (int)domPoint;
// subtract half the thickness of point to make it graph at the points center
newDomPoint = newDomPoint - 3;
// X data point
double ranNum = graphInterior.rangeNumList.get(ranPointPos);
//A what to add to 200
double ranAdd = ranNum / oneRanPX;
// newX make the point relavent to the graphs location
double ranPoint = 600 - ranAdd;
// make domPoint integer to be used on point method
int newRanPoint = (int)ranPoint;
// subtract half the thickness of point to make it graph at the points center
newRanPoint = newRanPoint - 3;
graph.fillOval(newDomPoint,newRanPoint,6,6);
domPointPos++;
ranPointPos++;
}
}
}
然后,输出应允许for循环执行并绘制数据点,但会引发异常,并且程序无法完成。
答案 0 :(得分:2)
我怀疑问题出在:
for (int counter = 0; counter < (main.dataLength + 1) ; counter++) {
如果dataLength为0,则它将运行一次并执行get(0)
,这将引发您显示的异常。
但是,如果您要做的只是将字符串列表转换为双打列表,则可以使用:
domainList.stream().map(Double::valueOf).collect(Collectors.toList());
如果您希望安静地跳过无效的字符串,那么对于在Double
的javadoc中使用的正则表达式有很长的解释。一个简单的版本可能是:
Pattern doublePattern = Pattern.compile("\\d+(\\.\\d+)?");
List<Double> result = domainList.stream()
.filter(doublePattern::matches).map(Double::valueOf)
.collect(Collectors.toList());