Every time I try to run my file to display a graph it gets the majority of teh program done, up until to the GraphAtOrigin Class. This is where an error is thrown, saying the "IndexOutOfBoundsException: Index 0 out of bounds for length 0". So I believe there is something wrong with the wat I converted the domainList String ArrayList to the domainNumList Double ArrayListsome or a problem when I try to get the double array from the CreateGraphInterior Class. What do I need to do to prevent this exception and allow the code to run?
I have already tried casting the String ArrayList to a Double ArrayList with varies techniques, but if you have a better way let me know.
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++;
}
}
}
The output should then allow the for loops to execute and draw data points, but the exception is thrown and the program doesn't complete.
I suspect the problem is at:
for (int counter = 0; counter < (main.dataLength + 1) ; counter++) {
If the dataLength is 0 then this will run once and perform a get(0) which will throw the exception you have shown.
However if all you want to do is to convert a list of strings to a list of doubles, then you could use:
domainList.stream().map(Double::valueOf).collect(Collectors.toList());
If you wish to quietly skip invalid strings then there is a long explanation of the regexp to use in the javadoc for Double. A simple version might be:
Pattern doublePattern = Pattern.compile("\\d+(\\.\\d+)?");
List<Double> result = domainList.stream()
.filter(doublePattern::matches).map(Double::valueOf)
.collect(Collectors.toList());
My code now works for sum, subtract, multiple, divide.
However it doesn't show the decimal when I put 10.0 and 2.0 or 5.4 and 2.
How should I change, then it can be used for decimal??
This is my code now.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
// instance variables
JLabel num1Label = null;
JTextField num1Text = null;
JLabel num2Label = null;
JTextField num2Text = null;
JButton sumButton = null;
JButton multipleButton=null;
JButton divideButton=null;
JButton subtractButton = null;
JLabel ansLabel = null;
// constructor
public Calculator() {
setLayout(new GridBagLayout()); // set layout (how elements are arranged in window)
// **** label: num 1
GridBagConstraints layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 0;
layoutCon.insets = new Insets(10,10,10,10);
num1Label = new JLabel("Num 1:");
add(num1Label,layoutCon); // added label to JFrame
// **** text field: num 1
layoutCon = new GridBagConstraints();
layoutCon.gridx = 1;
layoutCon.gridy = 0;
layoutCon.insets = new Insets(10,10,10,10);
num1Text = new JTextField(20);
add(num1Text, layoutCon);
// **** label: num 2
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 1;
layoutCon.insets = new Insets(10,10,10,10);
num2Label = new JLabel("Num 2:");
add(num2Label,layoutCon); // added label to JFrame
// **** text field: num 2
layoutCon = new GridBagConstraints();
layoutCon.gridx = 1;
layoutCon.gridy = 1;
layoutCon.insets = new Insets(10,10,10,10);
num2Text = new JTextField(20);
add(num2Text, layoutCon);
// **** Sum Button
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 2;
layoutCon.insets = new Insets(10,10,10,10);
sumButton = new JButton("Sum");
add(sumButton, layoutCon);
sumButton.addActionListener(this); // register sumButton with the ActionListener in Calculator
// Multiple Button
layoutCon= new GridBagConstraints();
layoutCon.gridx=0;
layoutCon.gridy=4;
layoutCon.insets=new Insets(10,10,10,10);
multipleButton= new JButton("Multiple");
add(multipleButton, layoutCon);
multipleButton.addActionListener(this);
// Divide Button
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 5;
layoutCon.insets = new Insets(10,10,10,10);
divideButton = new JButton("Divide");
add(divideButton, layoutCon);
divideButton.addActionListener(this);
// **** label: answer
layoutCon = new GridBagConstraints();
layoutCon.gridx = 1;
layoutCon.gridy = 2;
layoutCon.insets = new Insets(10,10,10,10);
ansLabel = new JLabel("Answer");
add(ansLabel,layoutCon); // added label to JFrame
// **** Subtract Button
layoutCon = new GridBagConstraints();
layoutCon.gridx = 0;
layoutCon.gridy = 3;
layoutCon.insets = new Insets(10,10,10,10);
subtractButton = new JButton("Subtract");
add(subtractButton, layoutCon);
subtractButton.addActionListener(this); // register subtractButton with the ActionListener in Calculator
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Sum")) {
ansLabel.setText("" + (Integer.parseInt(num1Text.getText()) + Integer.parseInt(num2Text.getText())));
}
else if (e.getActionCommand().equals("Subtract")) {
ansLabel.setText("" + (Integer.parseInt(num1Text.getText()) - Integer.parseInt(num2Text.getText())));
}
else if (e.getActionCommand().equals("Multiple")){
ansLabel.setText(""+(double)(Integer.parseInt(num1Text.getText())*Integer.parseInt(num2Text.getText())));
}
else if (e.getActionCommand().equals("Divide")){
ansLabel.setText(""+(Integer.parseInt(num1Text.getText())/Integer.parseInt(num2Text.getText())));
}
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.pack(); // resizes window (JFrame) so you can see the elements in it
calc.setVisible(true); // make window visible
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit program when close window
}
}
actionPerformed is parsing its inputs as int and operating on them as such. If you want to use floating-point numbers, try using double instead.
Parsing as an integer cannot handle double's or any floating point number (decimal) as such change your actionPerformed to parse double's instead or parse int's:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Sum")) {
ansLabel.setText("" + (Double.parseDouble(num1Text.getText()) + Double.parseDouble(num2Text.getText())));
}
else if (e.getActionCommand().equals("Subtract")) {
ansLabel.setText("" + (Double.parseDouble(num1Text.getText()) - Double.parseDouble(num2Text.getText())));
}
else if (e.getActionCommand().equals("Multiple")){
ansLabel.setText(""+(double)(Double.parseDouble(num1Text.getText())*Double.parseDouble(num2Text.getText())));
}
else if (e.getActionCommand().equals("Divide")){
ansLabel.setText(""+(Double.parseDouble(num1Text.getText())/Double.parseDouble(num2Text.getText())));
}
}
You use
Integer.parseInt(num1Text.getText());
which parses a String to an int.
With
Double.parseDouble(num1Text.getText());
you get a double.
Note that you might want to catch the NumberFormatException, since you most likley don't want your program to stop on malformed user input:
double num1;
try
{
num1 = Double.parseDouble(num1Text.getText());
} catch (NumberFormatException e)
{
// either use a default value or give feedback to the user on what he did wrong
// for example
num1 = 1;
}
If you don't want to print a double value, if only integer values are entered by the user, then you could first try to parse to int, catch the exception (if any) and then parse to double.
Another error in your divison line:
ansLabel.setText(
""+(Integer.parseInt(num1Text.getText())/Integer.parseInt(num2Text.getText())));
You do not check if the second parameter is != 0, otherwise you might divide by 0!
To keep your code more readable you might want to create an extra method for parsing a String to a number:
private static double parseDouble(String s)
{
double num;
try
{
num = Double.parseDouble(num1Text.getText());
} catch (NumberFormatException e)
{
// either use a default value or give feedback to the user on what he did wrong
// for example
num = 1;
}
return num;
}
A possible fix for the division by 0 could be:
double num1 = parseDouble(num1Text.getText());
double num2 = parseDouble(num2Text.getText());
String command = e.getActionCommand();
if (command.equals("Sum"))
{
ansLabel.setText("" + (num1 + num2));
} else if (command.equals("Subtract"))
{
ansLabel.setText("" + (num1 - num2));
} else if (command.equals("Multiple"))
{
ansLabel.setText("" + (num1 * num2));
} else if (command.equals("Divide"))
{
if (num2 == 0)
{
ansLabel.setText("ERROR: Division by zero!");
} else
{
ansLabel.setText("" + (num1 / num2));
}
}
you should use double data type instead of integer for 4 operations
Like this:
public void actionPerformed( ActionEvent e )
{
if( e.getActionCommand().equals( "Sum" ) )
ansLabel.setText( "" + ( Double.
parseDouble(num1Text.getText() ) + Double.parseDouble(
num2Text.getText() ) ) );
// etc.
I've been having problems running this program it compiles but doesn't run properly. When I run it and attempt to perform the calculations it spits out a bunch errors. I think it has to with variable types. Here is the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class area extends JFrame implements ActionListener, ItemListener{
//row 1
JPanel row1 = new JPanel();
JLabel select = new JLabel("Please select what you would like to caculate the area and volume of.");
//row 2
JPanel row2 = new JPanel();
JCheckBox circle = new JCheckBox("Circle", false);
JCheckBox cube = new JCheckBox("Cube", false);
//row 3
JPanel row3 = new JPanel();
JLabel radlab = new JLabel("Radius of the circle (in cm)");
JTextField rad = new JTextField(3);
JLabel sidelab = new JLabel("A side of the cube (in cm)");
JTextField side = new JTextField(3);
//row4
JPanel row4 = new JPanel();
JButton solve = new JButton("Solve!");
//row 5
JPanel row5 = new JPanel();
JLabel areacallab = new JLabel("Area");
JTextField areacal = new JTextField(10);
JLabel volumelab = new JLabel("Volume");
JTextField volume = new JTextField(10);
public area(){
setTitle("Area Caculator");
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//disables all text areas
rad.setEnabled(false);
side.setEnabled(false);
areacal.setEnabled(false);
volume.setEnabled(false);
//add listeners
circle.addItemListener(this);
cube.addItemListener(this);
solve.addActionListener(this);
FlowLayout one = new FlowLayout(FlowLayout.CENTER);
setLayout(one);
row1.add(select);
add(row1);
row2.add(circle);
row2.add(cube);
add(row2);
row3.add(radlab);
row3.add(rad);
row3.add(sidelab);
row3.add(side);
add(row3);
row4.add(solve);
add(row4);
row5.add(areacallab);
row5.add(areacal);
row5.add(volumelab);
row5.add(volume);
add(row5);
}
public void circlepick(){
//cube.setCurrent(false);
cube.setEnabled(false);
rad.setEnabled(true);
}
public void cubepick(){
circle.setEnabled(false);
side.setEnabled(true);
}
#Override
public void itemStateChanged(ItemEvent event) {
Object item = event.getItem();
if (item == circle){
circlepick();
}
else if (item == cube){
cubepick();
}
}
#Override
public void actionPerformed(ActionEvent evt){
//String radi = rad.getText();
//String sid = side.getText();
//circlesolve();
//cubesolve();
String radi = rad.getText();
String sid = side.getText();
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
double cirarea = Math.PI * Math.pow(radius, 2);
double cirvolume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
double cubearea = Math.pow(length, 2);
double cubevolume = Math.pow(length, 3);
areacal.setText("" + cirarea + cubearea + "");
volume.setText("" + cirvolume + cubevolume + "");
}
public static void main(String[] args) {
area are = new area();
}
}
Here are the errors is printing out when attempting to perform the math (sorry it really long).
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1038)
at java.lang.Double.parseDouble(Double.java:548)
at area.actionPerformed(area.java:112)
...
Thanks so much in advance for an help!
When calling the functions:
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
either radi or sid is am Empty String, thats what
java.lang.NumberFormatException: empty String
tells you.
You might consider adding a System.out.println(raid + ", " + sid) before parsing to check what values are empty Strings and make sure, that the Strings are not empty.
Double.parseDouble(String s) throws a NumberFormatException when the given String s can not be parsed into a double value.
I think I almost got it if I can just get rid of a few exceptions the program gives me when I try to run it. Here's the code I have:
package RandomMathGame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class RandomMathGame {
public static void main(String[] args) {
RandomProblemGenerator randomProblems = new RandomProblemGenerator(10);
final int numberProblems = 10;
int correctScore = 0;
JPanel panel = new JPanel();
int answer;
int correctAnswer;
JLabel[] mathProblems = new JLabel[numberProblems];
final JTextField[] mathAnswers = new JTextField[numberProblems];
JLabel[] correctYesNo = new JLabel[numberProblems];
final JLabel score = new JLabel(correctScore + "/10");
JButton submit = new JButton("Submit");
for (int i = 1; i <= numberProblems; i++)
{
final int X = randomProblems.createNumberX();
final int Y = randomProblems.createNumberY();
mathProblems[i] = new JLabel("" + X + " * " + Y + " = ");
mathAnswers[i] = new JTextField();
answer = Integer.parseInt(mathAnswers[i].getText());
correctAnswer = X * Y;
if (answer == correctAnswer)
{
correctYesNo[i] = new JLabel("Correct answer; good job!");
correctScore = correctScore + 1;
}
else
{
correctYesNo[i] = new JLabel("Incorrect answer; try again!");
}
panel.add(mathProblems[i]);
panel.add(mathAnswers[i]);
panel.add(correctYesNo[i]);
}
final int temp = correctScore;
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
score.setText("Score: " + temp + "/10");
}
});
panel.add(submit);
panel.add(score);
JFrame gameFrame = new JFrame();
gameFrame.setTitle("Random Math Game");
gameFrame.setSize(150, 150);
gameFrame.setVisible(true);
gameFrame.setContentPane(panel);
}
}
And these are the exceptions it's giving me when I run it:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at RandomMathGame.RandomMathGame.main(RandomMathGame.java:33)
Java Result: 1
I'm crunched for time, so any help would be much appreciated.
You are trying to get from a field you just created which is blank.
mathAnswers[i] = new JTextField();
answer = Integer.parseInt(mathAnswers[i].getText());
So in this you are just checking from wrong place.
Seems like on first step you want to create the text fields and the second line should be there at some other event.
Hope it helps
String answerStr = mathAnswers[i].getText();
if(answerStr.isEmpty()){
correctYesNo[i] = new JLabel("Not a valid answer/answer field empty!");
} else {
answer = Integer.parseInt(answerStr);
correctAnswer = X * Y;
//Rest of your code goes here
}
Hope this helps you!
answer = Integer.parseInt(mathAnswers[i].getText());
Is what's causing the error. This is because one of your textfields is blank. Do some validation before accepting user input, unless you want your application to go awry.
I'm having trouble with my radio buttons. I can click on all three at the same time. It should be when you click on one the other one turns off?
I'm using a grid layout. So when I try group.add it doesn't work.
Example:
I have the buttons declared like this
JRadioButton seven = new JRadioButton("7 years at 5.35%", false);
JRadioButton fifteen = new JRadioButton("15 years at 5.5%", false);
JRadioButton thirty = new JRadioButton("30 years at 5.75%", false);
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
This is my code:
/*Change Request #6
Write the program in Java (with a graphical user interface)
so that it will allow the user to select which way
they want to calculate a mortgage:
by input of the amount of the mortgage,
the term of the mortgage,
and the interest rate of the mortgage payment
or by input of the amount of a mortgage and
then select from a menu of mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5 %
- 30 year at 5.75%
In either case, display the mortgage payment amount
and then, list the loan balance and interest paid
for each payment over the term of the loan.
Allow the user to loop back and enter a new amount
and make a new selection, or quit.
Insert comments in the program to document the program.
*/
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WK4 extends JFrame implements ActionListener
{
int loanTerms[] = { 7, 15, 30 };
double annualRates[] = { 5.35, 5.5, 5.75 };
// Labels
JLabel AmountLabel = new JLabel(" Loan Amount $ ");
JLabel PaymentLabel = new JLabel(" Monthly Payment ");
JLabel InterestLabel = new JLabel(" Interest Rate % ");
JLabel TermLabel = new JLabel(" Years of Loan ");
// Text Fields
JTextField mortgageAmount = new JTextField(6);
JTextField Payment = new JTextField(6);
JTextField InterestRate = new JTextField(3);
JTextField Term = new JTextField(3);
// Radio Buttons
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton seven = new JRadioButton("7 years at 5.35%");
JRadioButton fifteen = new JRadioButton("15 years at 5.5%");
JRadioButton thirty = new JRadioButton("30 years at 5.75%");
// Buttons
JButton exitButton = new JButton("Exit");
JButton resetButton = new JButton("Reset");
JButton calculateButton = new JButton("Calculate ");
// Text Area
JTextArea LoanPayments = new JTextArea(20, 50);
JTextArea GraphArea = new JTextArea(20, 50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public WK4(){
super("Mortgage Calculator");
//Window
setSize(700, 400);
setLocation(200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(2, 2));
Container grid = getContentPane();
grid.setLayout(new GridLayout(4, 10, 0, 12)); //rows, cols, hgap, vgap
pane.add(grid);
pane.add(scroll);
grid.add(AmountLabel);
grid.add(mortgageAmount);
grid.add(InterestLabel);
grid.add(InterestRate);
grid.add(TermLabel);
grid.add(Term);
grid.add(PaymentLabel);
grid.add(Payment);
grid.add(Box.createHorizontalStrut(15));
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
grid.add(calculateButton);
grid.add(resetButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
// Action Listeners
mortgageAmount.addActionListener(this);
InterestRate.addActionListener(this);
Term.addActionListener(this);
Payment.addActionListener(this);
seven.addActionListener(this);
fifteen.addActionListener(this);
thirty.addActionListener(this);
calculateButton.addActionListener(this);
exitButton.addActionListener(this);
resetButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object command = e.getSource();
if (command == exitButton) {
System.exit(0);
}
else if (command == seven) {
calcLoan(loanTerms[0], annualRates[0]);
}
else if (command == fifteen) {
calcLoan(loanTerms[1], annualRates[1]);
}
else if (command == thirty) {
calcLoan(loanTerms[2], annualRates[2]);
}
else if (command == calculateButton) {
double years = 0;
double rates = 0;
try {
years = Double.parseDouble(Term.getText());
rates = Double.parseDouble(InterestRate.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
calcLoan(years, rates);
}
else if (command == resetButton) {
mortgageAmount.setText("");
Payment.setText("");
InterestRate.setText("");
Term.setText("");
LoanPayments.setText("");
}
}
private void calcLoan(double years, double rates) {
Term.setText(String.valueOf(years));
InterestRate.setText(String.valueOf(rates));
double amount = 0;
try {
amount = Double.parseDouble(mortgageAmount.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
double interestRate = rates;
double intRate = (interestRate / 100) / 12;
int months = (int) years * 12;
double rate = (intRate / 12);
double payment = amount * intRate
/ (1 - (Math.pow(1 / (1 + intRate), months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
NumberFormat CurrencyFormatter = NumberFormat.getCurrencyInstance();
Payment.setText(CurrencyFormatter.format(payment));
LoanPayments.setText(" Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while (currentMonth < months) {
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t"
+ CurrencyFormatter.format(MonthlyAmt) + "\t"
+ CurrencyFormatter.format(MonthlyInterest) + "\t"
+ CurrencyFormatter.format(remainingPrincipal) + "\n");
GraphArea.append("" + remainingPrincipal);
}
}
public static void main(String[] args) {
new WK4();
}
}
You're adding the radio buttons to the grid but you also need to add them to the button group that you defined.
Maybe this:
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
Should be this: ??? (Copy/paste bug?)
ButtonGroup group = new ButtonGroup();
group.add(seven);
group.add(fifteen);
group.add(thirty);
Or maybe you need to do both. The radio buttons have to belong to a container as well as a button group to be displayed and to behave properly.