How can I access variables outside of loop in Java? - java

So I have my if statements to search a .txt file for the currency codes that correspond to the country the user types in. I store those country codes in Strings called 'from' and 'to'. I need to access the results of the if statements which are stored in the 'from' and 'to' variables to plug into something later. When I try to use these in the line way down at the end it says Cannot find symbol 'from' and Cannot find symbol 'to'. How can I fix this?
//all my imports here
public class ExchangeApp {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("Exchange App");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 2, 5, 3));
//GUI Elements
JLabel toLabel = new JLabel("To");
JTextField CurrencyTo = new JTextField(20);
JLabel fromLabel = new JLabel("From");
JTextField CurrencyFrom = new JTextField(20);
JLabel amountLabel = new JLabel("Amount");
JTextField AmountText = new JTextField(20);
JLabel displayLabel = new JLabel();
JLabel updateLabel = new JLabel();
JButton Calculate = new JButton("Calculate");
JButton Clear = new JButton("Clear");
//Add elements to panel
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(fromLabel);
panel.add(CurrencyFrom);
panel.add(toLabel);
panel.add(CurrencyTo);
panel.add(amountLabel);
panel.add(AmountText);
panel.add(Calculate);
panel.add(Clear);
panel.add(displayLabel);
panel.add(updateLabel);
//make visible
frame.add(panel);
frame.setVisible(true);
class calculateListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==Calculate){
String line, from, to;
String fromString = CurrencyFrom.getText();
String toString = CurrencyTo.getText();
double amount = Double.parseDouble(AmountText.getText());
try{
//import text file
File inputFile = new File("currency.txt");
//create file scanner
Scanner input = new Scanner(inputFile);
try{
//skip first line
input.nextLine();
//while has next line
while(input.hasNextLine()){
//set line equal to entire line
line = input.nextLine();
String[] countryArray = line.split("\t");
//search for from
if(fromString.equals(countryArray[0])){
//set 'from' equal to that country code
from = countryArray[2];
//testing
System.out.println(from);
}
//search for to
if(toString.equals(countryArray[0])){
//set 'to' equal to that country code
to = countryArray[2];
System.out.println(to);
}
else{
displayLabel.setText("To country not found");
}
}//while loop
}//2nd try
finally{input.close();}
}//1st try
catch(IOException exception){
System.out.println(exception);
}//catch bracket
}//if bracket ****these 2 variables****
String address = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to;
}//action bracket
}//class implements action listener bracket
ActionListener listener = new calculateListener();
Calculate.addActionListener(listener);
}//main bracket
}//class bracket

Related

How to use JButton in Java

I'm trying to create a hangman game using the Swing class and Graphics class for a APCS class I have.
I created a JButton that would take the guess typed in by the user and either add it to the "misses" or fill in all of the corresponding letters in the word. I have a separate txt file where I pick a random word from.
When I run the program, all of the components show up, but the button does not do anything. I have been working on this for a few days and don't know what I am doing wrong. I have only learnt how to use the Swing class recently, so it may be a stupid mistake for all I know. I have put all of the code down below.
public class Hangman extends JFrame {
DrawPanel panel = new DrawPanel();
Graphics g = panel.getGraphics();
JTextField guess;
JTextField outputWord;
JTextField missesString;
boolean play;
JButton button = new JButton();
String output = "";
String word;
int misses = 0;
public Hangman() {
int again = 0;
String[] dictionary = new String[1000];
In words = new In("words.txt");
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(500, 500);
for (int i = 0; i < 1000; i++) {
dictionary[i] = words.readLine();
}
do {
int num = (int) (Math.random() * 1000);
word = dictionary[num].toLowerCase();
String answer = word;
word = "";
for (int i = answer.length(); i > 0; i--) {
word = word + "*";
}
int length = answer.length();
app.setLayout(new BorderLayout());
JLabel letter = new JLabel();
letter.setFont(new Font("Arial", Font.BOLD, 20));
letter.setText("Enter Your guess");
guess = new JTextField(10);
JLabel output = new JLabel();
output.setFont(new Font("Arial", Font.BOLD, 20));
output.setText("The Word is");
outputWord = new JTextField(30);
outputWord.setText(word);
outputWord.setEditable(false);
JLabel misses = new JLabel();
misses.setFont(new Font("Arial", Font.BOLD, 20));
misses.setText("Misses:");
missesString = new JTextField(52);
missesString.setEditable(false);
button = new JButton("Guess");
button.addActionListener(new ButtonListener());
JPanel panels = new JPanel();
panels.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.add(letter);
panel1.add(guess);
panel1.add(button);
JPanel panel2 = new JPanel();
panel2.add(output);
panel2.add(outputWord);
JPanel panel3 = new JPanel();
panel3.add(misses);
panel3.add(missesString);
app.add(panel1, BorderLayout.NORTH);
app.add(panel2, BorderLayout.EAST);
app.add(panel3, BorderLayout.SOUTH);
app.add(panels);
app.setVisible(true);
again = JOptionPane.showConfirmDialog(null, "Do you want to play again?");
} while (again == JOptionPane.YES_OPTION);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guess) {
output = "";
}
for (int i = 0; i <= word.length() - 1; i++) {
if (guess.getText().equalsIgnoreCase(word.substring(i, i + 1))) {
output = output.substring(0, i) + guess + output.substring(i + 1, word.length() - 1);
outputWord.setText(output);
} else {
misses++;
missesString.setText(missesString.getText() + guess + " ");
}
}
}
}
}
The components show up perfectly on the screen, it is only the button that is giving me a hard time by not working as expected.

calculating average of values in column of an array?

Ok, so I recently asked about how to get access to individual columns of an array in java, and I got an answer that worked perfectly. I then however intended to calculate things such as the maximum value in this column, and the average. However, I came across an issue. In order to access each value, I assume this column needs to be treated as an array also. However, the way I got access to each column was by storing it into a double. Therefore, I have no idea how to take each column and calculate things. Can anyone help me please? I'm sorry for posting so much that probably seems like nothing here, but we had no teacher for 12 weeks and are expected to turn in this work by just teaching ourselves, and I'm just really stuck.
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame.
private JPanel contentPane; //Create a container for the GUI.
//Create other components used in the GUI
private JTextField maxTxtVCC;
private JTextField maxTxtTemp;
private JTextField maxTxtLight;
private JTextField minTxtLight;
private JTextField avTxtLight;
private JTextField minTxtTemp;
private JTextField avTxtTemp;
private JTextField minTxtVCC;
private JTextField avTxtVCC;
private JButton btnMax;
private JButton btnMin;
private JButton btnAv;
private JTextField opnTxt;
private JButton btnOpn;
private TextArea textArea;
private JFileChooser fc;
private String content = "";
String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
int totalValues; //Used to hold the amount of values in the array (52790 ish)
Double[][] values;
double c4, c5, c6;
/**
* Launch the application.
*/
public static void main(String[] args) { //Main method
EventQueue.invokeLater(new Runnable() {
public void run() { //Create a runnable method
try {
CSVFiles frame = new CSVFiles(); //Launch the GUI
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace(); //Print errors
}
}
});
}
/**
* Create the frame.
*/
public CSVFiles() { //Open constructor
super ("CSV Files"); //Create a title for the GUI
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
setBounds(100, 100, 800, 600); //Set size and location
contentPane = new JPanel(); //Declare the JPanel
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
setContentPane(contentPane); //Add the JPanel
contentPane.setLayout(null); //Set the layout
maxTxtVCC = new JTextField(); //Declare this text field
maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
maxTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtVCC); //Add to the content pane
maxTxtTemp = new JTextField(); //Declare this text field
maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
maxTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtTemp); //Add to the content pane
maxTxtLight = new JTextField(); //Declare this text field
maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
maxTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtLight); //Add to the content pane
JLabel lblLight = new JLabel("Light"); //Declare this label
lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblLight.setBounds(22, 469, 46, 17); //Set size and location
contentPane.add(lblLight); //Add to the content pane
JLabel lblTemp = new JLabel("Temperature"); //Declare this label
lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblTemp.setBounds(10, 503, 109, 17); //Set size and location
contentPane.add(lblTemp);
JLabel lblVCC = new JLabel("VCC"); //Declare this label
lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblVCC.setBounds(22, 534, 46, 17); //Set size and location
contentPane.add(lblVCC); //Add to the content pane
minTxtLight = new JTextField(); //Declare this text field
minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
minTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtLight); //Add to the content pane
avTxtLight = new JTextField(); //Declare this text field
avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
avTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtLight); //Add to the content pane
minTxtTemp = new JTextField(); //Declare this text field
minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
minTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtTemp); //Add to the content pane
avTxtTemp = new JTextField(); //Declare this text field
avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
avTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtTemp); //Add to the content pane
minTxtVCC = new JTextField(); //Declare this text field
minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
minTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtVCC); //Add to the content pane
avTxtVCC = new JTextField(); //Declare this text field
avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
avTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtVCC); //Add to the content pane
btnMax = new JButton("Maximum"); //Declare this button
btnMax.setBounds(110, 438, 89, 23); //Set size and location
contentPane.add(btnMax); //Add to the content pane
btnMin = new JButton("Minimum"); //Declare this button
btnMin.setBounds(221, 438, 89, 23); //Set size and location
contentPane.add(btnMin); //Add to the content pane
btnAv = new JButton("Average"); //Declare this button
btnAv.setBounds(328, 438, 89, 23); //Set size and location
contentPane.add(btnAv); //Add to the content pane
textArea = new TextArea(); //Declare this text area
textArea.setBounds(22, 55, 551, 367); //Set size and location
textArea.setEditable(false); //Set it so it cannot be edited
contentPane.add(textArea); //Add to the content pane
btnOpn = new JButton("Open File"); //Declare this button
btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
public void actionPerformed(ActionEvent arg0) { //Method for action performed
try{
fc = new JFileChooser(); //Declare the file chooser
fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type
int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
File f; //Create a file to hold the data
//If the selected file is approved by the file chooser...
if(returnVal == JFileChooser.APPROVE_OPTION){
f = fc.getSelectedFile(); //Stored selected file into file variable
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder builder = new StringBuilder();
String line = "";
textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
textArea.append("\nLoading file...\n\n"); //Print out loading message and some new lines
in.readLine(); //Skip the first line as it's just headers
int index = 0; //Integer used to label the indexes of the array
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
c4 = Double.parseDouble(temp[3]);
c5 = Double.parseDouble(temp[4]);
c6 = Double.parseDouble(temp[5]);
}
totalValues = index; //Set a value to the total values
textArea.append(builder.toString()); //Using the string builder to compile the text
textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
in.close(); //Close the reader.
values = new Double [index][3];
}
else{
f = null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
btnOpn.setBounds(484, 26, 89, 23); //Set size and location
contentPane.add(btnOpn); //Add to the content pane
opnTxt = new JTextField(); //Declare this text field
opnTxt.setBounds(22, 27, 452, 20); //Set size and location
opnTxt.setEditable(false); //Set it so it cannot be edited
contentPane.add(opnTxt); //Add to the content pane
}
//Methods for Calculations
public static double findMax(double[] array){
double max;
max = array[0];
for(int i=1;i<array.length;++i){
if(array[i]>max){
max = array[i];
}
}
return max;
}
}
Also, after this, I tried an alterantive code, where instead of getting individual columns, I would instead store the unwanted columns into an array so they are voided during calculation, but this also does not work. I'll admit very much that I didn't fully understand this method, but it was based on an example code that was given to us without any explanation of what it was doing, so I thought I'd atleast try. It displays the file on the text area, but gives a null pointer exception when I tried to click the max button. http://gyazo.com/27ef7cf9f4bc0c72ecdc3c1f84e6d0f8 Again, appriciate any help. I'm trying to rush a bit cuz my class is coming to me for help cuz last year, I watched a series on java basics in my free time and so had no trouble with our first year work, and they came to me for help. However, I have found no java series or anything on stuff like this, just like specific videos that only help a little. So yeah, really big thanks for any help. :)
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame.
private JPanel contentPane; //Create a container for the GUI.
//Create other components used in the GUI
private JTextField maxTxtVCC;
private JTextField maxTxtTemp;
private JTextField maxTxtLight;
private JTextField minTxtLight;
private JTextField avTxtLight;
private JTextField minTxtTemp;
private JTextField avTxtTemp;
private JTextField minTxtVCC;
private JTextField avTxtVCC;
private JButton btnMax;
private JButton btnMin;
private JButton btnAv;
private JTextField opnTxt;
private JButton btnOpn;
private TextArea textArea;
private JFileChooser fc;
private String content = "";
String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
int totalValues; //Used to hold the amount of values in the array (52790 ish)
Double[][] values;
/**
* Launch the application.
*/
public static void main(String[] args) { //Main method
EventQueue.invokeLater(new Runnable() {
public void run() { //Create a runnable method
try {
CSVFiles frame = new CSVFiles(); //Launch the GUI
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace(); //Print errors
}
}
});
}
/**
* Create the frame.
*/
public CSVFiles() { //Open constructor
super ("CSV Files"); //Create a title for the GUI
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
setBounds(100, 100, 800, 600); //Set size and location
contentPane = new JPanel(); //Declare the JPanel
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
setContentPane(contentPane); //Add the JPanel
contentPane.setLayout(null); //Set the layout
maxTxtVCC = new JTextField(); //Declare this text field
maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
maxTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtVCC); //Add to the content pane
maxTxtTemp = new JTextField(); //Declare this text field
maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
maxTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtTemp); //Add to the content pane
maxTxtLight = new JTextField(); //Declare this text field
maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
maxTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtLight); //Add to the content pane
JLabel lblLight = new JLabel("Light"); //Declare this label
lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblLight.setBounds(22, 469, 46, 17); //Set size and location
contentPane.add(lblLight); //Add to the content pane
JLabel lblTemp = new JLabel("Temperature"); //Declare this label
lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblTemp.setBounds(10, 503, 109, 17); //Set size and location
contentPane.add(lblTemp);
JLabel lblVCC = new JLabel("VCC"); //Declare this label
lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblVCC.setBounds(22, 534, 46, 17); //Set size and location
contentPane.add(lblVCC); //Add to the content pane
minTxtLight = new JTextField(); //Declare this text field
minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
minTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtLight); //Add to the content pane
avTxtLight = new JTextField(); //Declare this text field
avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
avTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtLight); //Add to the content pane
minTxtTemp = new JTextField(); //Declare this text field
minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
minTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtTemp); //Add to the content pane
avTxtTemp = new JTextField(); //Declare this text field
avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
avTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtTemp); //Add to the content pane
minTxtVCC = new JTextField(); //Declare this text field
minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
minTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtVCC); //Add to the content pane
avTxtVCC = new JTextField(); //Declare this text field
avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
avTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtVCC); //Add to the content pane
btnMax = new JButton("Maximum"); //Declare this button
btnMax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double tempArray1 [] = new double [totalValues];
double tempArray2 [] = new double [totalValues];
double tempArray3 [] = new double [totalValues];
for (int i = 0; i < totalValues; i++){
tempArray1[i] = values[i][0]; //assign the indexes along side each individual sensor from sensor value
tempArray2[i] = values[i][1];
tempArray3[i] = values[i][2];
}
//execute the method defined in Utils.java to calculate maximum
maxTxtLight.setText(findMax(tempArray1)+"");
maxTxtTemp.setText(findMax(tempArray2)+"");
maxTxtVCC.setText(findMax(tempArray3)+"");
}
});
btnMax.setBounds(110, 438, 89, 23); //Set size and location
contentPane.add(btnMax); //Add to the content pane
btnMin = new JButton("Minimum"); //Declare this button
btnMin.setBounds(221, 438, 89, 23); //Set size and location
contentPane.add(btnMin); //Add to the content pane
btnAv = new JButton("Average"); //Declare this button
btnAv.setBounds(328, 438, 89, 23); //Set size and location
contentPane.add(btnAv); //Add to the content pane
textArea = new TextArea(); //Declare this text area
textArea.setBounds(22, 55, 551, 367); //Set size and location
textArea.setEditable(false); //Set it so it cannot be edited
contentPane.add(textArea); //Add to the content pane
btnOpn = new JButton("Open File"); //Declare this button
btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
public void actionPerformed(ActionEvent arg0) { //Method for action performed
try{
fc = new JFileChooser(); //Declare the file chooser
fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type
int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
File f; //Create a file to hold the data
//If the selected file is approved by the file chooser...
if(returnVal == JFileChooser.APPROVE_OPTION){
f = fc.getSelectedFile(); //Stored selected file into file variable
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder builder = new StringBuilder();
String line = "";
textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
textArea.append("\nLoading file...\n\n"); //Print out loading message and some new lines
in.readLine(); //Skip the first line as it's just headers
int index = 0; //Integer used to label the indexes of the array
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
}
totalValues = index; //Set a value to the total values
textArea.append(builder.toString()); //Using the string builder to compile the text
textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
in.close(); //Close the reader.
values = new Double [index][3];
for(int i = 0; i < totalValues; i++){
String cols[] = contentCSV[i].split(",");
String tempMillis = cols[0]; //Use a string to take the millis stamp out of the array
String tempStamp = cols[1]; //Use a string to take the time stamp out of the array
String tempDateTime = cols[2]; //Use a string to take the date stamp out of the array
for(int columns=3;columns<cols.length;++columns){
//temp sensor value holds the 9 sensors and the index numbers, parsing the data into double
values[i][columns-3] = Double.parseDouble(cols[columns]);
}
}
}
else{
f = null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
btnOpn.setBounds(484, 26, 89, 23); //Set size and location
contentPane.add(btnOpn); //Add to the content pane
opnTxt = new JTextField(); //Declare this text field
opnTxt.setBounds(22, 27, 452, 20); //Set size and location
opnTxt.setEditable(false); //Set it so it cannot be edited
contentPane.add(opnTxt); //Add to the content pane
}
//Methods for Calculations
public static double findMax(double[] array){
double max;
max = array[0];
for(int i=1;i<array.length;++i){
if(array[i]>max){
max = array[i];
}
}
return max;
}
}
The problem is here:
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
c4 = Double.parseDouble(temp[3]);
c5 = Double.parseDouble(temp[4]);
c6 = Double.parseDouble(temp[5]);
}
Your storing your values into temporary local (local to the while loop) variables.
These variables are re-assigned every loop so you lose the information.
You can do one of two things:
Calculate the running SUM, and number of rows in order to calculate the average at the end. Average = SUM / COUNT
Store all values in arraylists, and calculate average at the end.
Example:
double c4avg=0, c5avg=0, c6avg=0;
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
//Calculate Running Sum stored in AVG variable
c4avg += Double.parseDouble(temp[3]);
c5avg += Double.parseDouble(temp[4]);
c6avg += Double.parseDouble(temp[5]);
}
//Divide by total rows to get average
c4avg/=index;
c5avg/=index;
c6avg/=index;

How to get rid of spaces in the string of my Calc program

I was wondering how I would be able to account for spaces in my Calculator program. Right now it is set up to only work if there is a space after every value. I want it to be able to work if there is multiple spaces as well. I tried doing something (in my action performed, under the '=' sign test), but it didn't really work. So wanted to know how I could make it account for multiple spaces (like if there are more than one space before the next value, then it should recognize that that is the case, and delete the extra spaces). Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
int counter = 0;
if (text.equals("="))
{
doMath math = new doMath();
for(int i = 0; i <b.length(); i++)
{
String c = b.substring(i,(i+1));
String d = b.substring((i+1),(i+2));
String temp = "";
if( c.equals(" ") && c.equals(d))
{
temp = b.substring(0,i)+(b.substring(i+1));
b = temp;
}
}
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
counter ++;
if(counter <2)
{
b+= " ";
display.setText(b);
}
else
{
b+="";
display.setText(b);
}
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
counter = 0;
}
}
This method requires knowledge of regular expressions. For each string, simply replace any instance of multiple consecutive spaces with a single space. In other words, using regular expressions, you would replace "\\s+", which means "more than one space," with " ", which is just the space character.
Example:
String c = ...
c = c.replaceAll("\\s+", " ");
String str = "your string";
Pattern _pattern = Pattern.compile("\\s+");
Matcher matcher = _pattern.matcher(str);
str = matcher.replaceAll(" ");
Instead of using a substring, use a Scanner which takes a String as a parameter.
Or you can disable the "Space" button after it's pressed, enabling it back, when a different button is pressed.
If b is not empty you could try looking at the previous character using charAt and if it is a space do nothing.

Array Required, but java.lang.String found

I'm trying to hide a random word which I retrieved from a list in a text file, but the code keeps giving me the following error: Array Required, but java.lang.String found
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;
public class Hangman extends JFrame
{
private static final char HIDECHAR = '_';
String imageName = null;
String Path = "D:\\Varsity College\\Prog212Assign1_10-013803\\images\\";
static int guesses =0;
private String original = readWord();
private String hidden;
int i = 0;
static JPanel panel;
static JPanel panel2;
static JPanel panel3;
static JPanel panel4;
public Hangman(){
JButton[] buttons = new JButton[26];
this.original = original;
this.hidden = this.createHidden();
panel = new JPanel(new GridLayout(0,9));
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
JButton btnRestart = new JButton("Restart");
btnRestart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
JButton btnNewWord = new JButton("Add New Word");
btnNewWord.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie)
{
System.out.println("Error Thrown" + ie.getMessage());
}
}
});
JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word."
+ "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions."
+ "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
+ "\n"
+ "\nThe game is over when:"
+ "\nThe guessing player completes the word, or guesses the whole word correctly"
+ "\nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JLabel lblWord = new JLabel(original);
if(guesses >= 0) imageName = "Hangman1.jpg";
if(guesses >= 1) imageName = "Hangman2.jpg";
if(guesses >= 2) imageName = "Hangman3.jpg";
if(guesses >= 3) imageName = "Hangman4.jpg";
if(guesses >= 4) imageName = "Hangman5.jpg";
if(guesses >= 5) imageName = "Hangman6.jpg";
if(guesses >= 6) imageName = "Hangman7.jpg";
ImageIcon icon = null;
if(imageName != null){
icon = new ImageIcon(Path + File.separator + imageName);
}
JLabel label = new JLabel();
label.setIcon(icon);
String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
panel.add(buttons[i]);
}
panel2.add(label);
panel3.add(btnRestart);
panel3.add(btnNewWord);
panel3.add(btnHelp);
panel3.add(btnExit);
panel4.add(lblWord);
}
public String readWord()
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while(line != null)
{
String[] wordsLine = line.split(" ");
boolean addAll = words.addAll(Arrays.asList(wordsLine));
line = reader.readLine();
}
Random rand = new Random(System.currentTimeMillis());
String randomWord = words.get(rand.nextInt(words.size()));
return randomWord;
}catch (Exception e){
return null;
}
}
private String printWord(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.original.length(); i++){
sb.append(HIDECHAR);
}
return sb.toString();
}
public boolean check(char input){
boolean found = false;
for (int i = 0; i < this.original.length(); i++){
if(this.original.charAt(i)== input)){
found = true;
this.hidden[i] = this.original.charAt(i);
}
}
return found;
}
public static void main(String[] args)
{
System.out.println();
Hangman frame = new Hangman();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box mainPanel = Box.createVerticalBox();
frame.setContentPane(mainPanel);
mainPanel.add(panel, BorderLayout.NORTH);
mainPanel.add(panel2);
mainPanel.add(panel4);
mainPanel.add(panel3);
frame.pack();
frame.setVisible(true);
}
}
Okay there's the whole code< the error is now on line 151 and 149... I've also tried to fix it according to one of the posts
You can't use array subscripts: [], to index into a String, and both hidden and original are Strings.
You can instead use original.charAt(i) to read a character at an index.
As for writing a character at an index: java Strings are immutable, so you can't change individual characters. Instead make hidden a StringBuilder, or simply a char[]:
// in your class member declarations:
char hidden[] = createHidden();
// possible implementation of createHidden:
char[] createHidden()
{
if (original != null)
return new char[original.length()];
else return null;
}
And then your loop can use original.charAt like so:
if (this.original.charAt(i) == input)
{
found = true;
this.hidden[i] = this.original.charAt(i);
1. As you are using original.length() its a String, as length() method works with String, not with Array, as for array, length is an Instance variable.
2. Try it like this....
this.hidden[i] = original.charAt(i);
3. And as char is Not an object but a primitive, use "=="
if (this.original[i] == input)

How To Keep Size Of JTextArea constant?

I'm using an object of JTextArea in my application which deals with sending sms.
I've used a DocumentFilter so as to allow only 160 characters to be typed in the textarea but now, I want the size of the textarea to be constant. it goes on increasing if I keep writing on the same line without pressing 'enter' key or even when I keep on pressing only Enter key. I tried once using 'scrollbar' too but the problem remains same. Suggest me something over this. Below is my code. Please check it.
class Send_sms extends JPanel implements ActionListener,DocumentListener
{
JButton send;
JTextArea smst;
JLabel title,limit;
JPanel mainp,titlep,sendp,wrap,titlewrap,blankp1,blankp2,sendwrap;
JScrollPane scroll;
Border br,blackbr;
Boolean flag = false;
PlainDocument plane;
public static final int LINES = 4;
public static final int CHAR_PER_LINE = 40;
//character limit 160 for a sms
public Send_sms()
{
br = BorderFactory.createLineBorder(Color.RED);
blackbr = BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.DARK_GRAY,Color.GRAY);
setBorder(blackbr);
title = new JLabel("Enter the text you want to send!");
title.setFont(new Font("",Font.BOLD,17));
limit = new JLabel(""+charCount+" Characters");
smst = new JTextArea(LINES,CHAR_PER_LINE);
smst.setSize(100,100);
plane = (PlainDocument)smst.getDocument();
//adding DocumentSizeFilter 2 keep track of characters entered
plane.setDocumentFilter(new DocumentSizeFilter(charCount));
plane.addDocumentListener(this);
send = new JButton("Send");
send.setToolTipText("Click Here To Send SMS");
send.addActionListener(this);
//scroll = new JScrollPane(smst);
//scroll.setPreferredSize(new Dimension(200,200));
//scroll.setVerticalScrollBarPolicy(null);
//scroll.setHorizontalScrollBarPolicy(null);
smst.setBorder(br);
blankp1 = new JPanel();
blankp2 = new JPanel();
titlep = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlewrap = new JPanel(new GridLayout(2,1));
mainp = new JPanel(new BorderLayout());
sendwrap = new JPanel(new GridLayout(3,1));
sendp = new JPanel(new FlowLayout(FlowLayout.CENTER));
wrap = new JPanel(new BorderLayout());
titlep.add(title);
titlewrap.add(titlep);
titlewrap.add(blankp1);
sendp.add(send);
sendwrap.add(limit);
sendwrap.add(blankp2);
sendwrap.add(sendp);
wrap.add(smst,BorderLayout.CENTER);
mainp.add(titlewrap,BorderLayout.NORTH);
mainp.add(wrap,BorderLayout.CENTER);
mainp.add(sendwrap,BorderLayout.SOUTH);
add(mainp);
}
public void actionPerformed(ActionEvent e)
{
Vector<Vector<String>> info = new Vector<Vector<String>> ();
Vector<String> numbers = new Vector<String>();
if(e.getSource() == send)
{
//Call a function to send he message to all the clients using text
//charCount = 165;
String msg = smst.getText();
if(msg.length() == 0)
JOptionPane.showMessageDialog(null,"Please Enter Message","Error",JOptionPane.ERROR_MESSAGE);
else
{
// System.out.println("Message:"+msg);
Viewdata frame = new Viewdata(msg);
limit.setText(""+charCount+" Characters");
charCount = 160;
}
}
}
public void insertUpdate(DocumentEvent e)
{
System.out.println("The legth:(insert) "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
if(charCount >0)
charCount--;
else
break;
}
limit.setText(""+charCount+" Characters");
}
public void removeUpdate(DocumentEvent e)
{
//System.out.println("The legth(remove): "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
charCount++;
}
limit.setText(""+charCount+" Characters");
}
public void changedUpdate(DocumentEvent e)
{
//System.out.println("The legth(change): "+e.getLength());
}
}//end Send_sms
Sound like you are creating the text area using
JTextArea textArea = new JTextArea();
When using this format the text area doesn't have a preferred size so it keeps on growing. If you use:
JTextArea textArea = new JTextArea(2, 30);
JScrollPane scrollPane = new JScrollPane( textArea );
Then the text area will have a preferred size of 2 rows and (roughly) 30 columns. As you type when you exceed the preferred width the horizontal scrollbar will appear. Or if you turn on wrapping, then the text will wrap and a vertical scrollbar will appear.
you need to specify:
textArea.setColumns (160);
textArea.setLineWrap (true);
textArea.setWrapStyleWord (false); //default
But the real problem is that you allow to input more than 160 characters. You need to create some kind of validator which will skip all inputed characters when there are already 160 characters written.
Initialise the textArea with a document that extends PlainDocument and in the insertString method limit the characters to 160

Categories

Resources