Итак, я недавно спросил о том, как получить доступ к отдельным столбцам массива в java, и я получил ответ, который работал отлично. Затем я решил рассчитать такие вещи, как максимальное значение в этом столбце, и среднее значение. Однако я столкнулся с проблемой. Чтобы получить доступ к каждому значению, я предполагаю, что этот столбец также нужно рассматривать как массив. Однако способ, которым я получил доступ к каждому столбцу, состоял в том, чтобы сохранить его в двойном. Поэтому я не знаю, как взять каждый столбец и рассчитать вещи. Кто-нибудь может мне помочь? Мне жаль, что вы так много публикуете, что, вероятно, здесь ничего не кажется, но у нас не было учителя в течение 12 недель и, как ожидается, мы включим эту работу, просто обучая себя, и я просто застрял.вычисление среднего значения в столбце массива?
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;
}
}
Кроме того, после этого, я попробовал alterantive код, где вместо того, чтобы отдельные столбцы, я бы вместо того, чтобы хранить ненужные столбцы в массиве таким образом, они аннулируются при расчете, но это также не работает. Я очень признаюсь, что не полностью понял этот метод, но он был основан на примере кода, который был дан нам без объяснения того, что он делает, поэтому я думал, что попробую. Он отображает файл в текстовой области, но дает исключение нулевого указателя, когда я пытался нажать кнопку max. http://gyazo.com/27ef7cf9f4bc0c72ecdc3c1f84e6d0f8 Опять же, попробуйте любую помощь. Я пытаюсь немного поспешить, потому что мой класс приходит ко мне за помощью в прошлом году, я смотрел серию на основе java в свободное время и поэтому не имел проблем с нашей первой работой, и они пришли ко мне за помощью , Тем не менее, я не нашел ни одной серии java или чего-либо подобного на подобных материалах, точно так же, как определенные видео, которые только помогают. Так что да, действительно большое спасибо за любую помощь. :)
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;
}
}
Чтобы получить лучшие ответы, пожалуйста, прочитайте: http://sscce.org/ Существует много нерелевантных код здесь .. –
вы не говорите нам, что вы испробовали , Я чувствую, что ваш переход от одного вопроса к другому без понимания основ Java. –
Ну, я использовал ответ для анализа данных из массива String в двойные значения, которые затем удерживают отдельные столбцы, но когда я попытался разбить отдельные столбцы на массив, он может: t cuz метод slit для строковых значений , Поэтому я не знаю, как взять столбец «c4», что является двойным значением чисел в столбце в массиве, а затем обрабатывать каждое значение в этом отдельно для вычислений. –