Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 19
  1. #1
    Utente di HTML.it
    Registrato dal
    Dec 2004
    Messaggi
    75

    [Java] errori di compilazione

    Mi aiutate a risolvere gli errori di compilazione del seguente codice??? VVoVe:

    [CODE*]

    /**

    * File: JavaExerciseForm.java

    * Author: JB

    *

    * Comment: Sample Java application

    */



    import info.clearthought.layout.TableLayout;



    import javax.swing.*;

    import javax.swing.event.ChangeEvent;

    import javax.swing.event.ChangeListener;

    import javax.swing.filechooser.FileFilter;

    import java.awt.*;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.io.*;

    import java.util.Arrays;

    import java.util.ArrayList;



    /**

    * Java Exercise application class

    * @author JB

    * @version 1.0

    */

    public class JavaExerciseForm extends JFrame {



    /**

    * Inner custom listener class

    */

    private class ButtonAction implements ActionListener, ChangeListener {

    public void actionPerformed(ActionEvent e) {

    if (e.getSource().equals(btnInsert))

    JavaExerciseForm.this.btnInsertActionPerformed(e);



    if (e.getSource().equals(btnImport))

    JavaExerciseForm.this.btnImportActionPerformed(e);



    if (e.getSource().equals(btnExport))

    JavaExerciseForm.this.btnExportActionPerformed(e);



    if (e.getSource().equals(btnSort))

    JavaExerciseForm.this.btnSortActionPerformed(e);



    if (e.getSource().equals(btnReset))

    JavaExerciseForm.this.btnResetActionPerformed(e);



    if (e.getSource().equals(btnExit))

    JavaExerciseForm.this.btnExitActionPerformed(e);

    }



    public void stateChanged(ChangeEvent e) {

    JavaExerciseForm.this.cbxStateChanged(e);

    }

    }



    /**

    * Inner custom file filter class

    * @author JB

    * @version 1.4.0.1

    */

    private class CustomFileFilter extends FileFilter {

    /**

    * Add a new file extension to the filter

    * @param extension a string representing the new file extension

    */

    public void addExtension(String extension) {

    if (extension.startsWith("."))

    extension = "." + extension;



    extensions.add(extension.toLowerCase());

    }



    /**

    * Add a list of new file extensions to the filter

    * @param extensions an array list of strings representing the new file extensions

    */

    public void addExtension(String[] extensions) {

    ArrayList<String> newExtensions = new ArrayList<String>(extensions.length);



    for (int i = 0; i < extensions.length; i++) {

    if (extensions[i].startsWith(".")) {

    newExtensions.add(i, extensions[i].toLowerCase());

    continue;

    }



    newExtensions.add(i, "." + extensions[i].toLowerCase());

    }



    this.extensions.addAll(newExtensions);

    }



    /**

    * Get the description of the file set recognized by the file filter

    * @return a string representing the file set description

    */

    public String getDescription() {

    return description;

    }



    /**

    * Set the description for the file set recognized by the file filter

    * @param description a string representing the file set description

    */

    public void setDescription(String description) {

    this.description = description;

    }



    /**

    * Check if the selected file can be accepted by the filter

    * @param f the selected file

    * @return true if the file can be accepted, otherwise false

    */

    public boolean accept(File f) {

    if (f.isDirectory())

    return true;



    String fileName = f.getName().toLowerCase();



    for (int i = 0; i < extensions.size(); i++)

    if (fileName.endsWith(extensions.get(i)))

    return true;



    return false;

    }



    private String description = "";

    private ArrayList<String> extensions = new ArrayList<String>();

    }



    /**

    * Class instance constructor

    */

    public JavaExerciseForm() {

    initializeComponents();

    }



    /**

    * Initialization method

    */

    private void initializeComponents() {

    txtInput = new JTextField(10);

    btnInsert = new JButton("Insert in list");

    txtInputList = new JTextArea(10, 30);

    scrollPane = new JScrollPane(txtInputList);

    lblMin = new JLabel("Minimum: ");

    lblMinValue = new JLabel("");

    lblMax = new JLabel("Maximum: ");

    lblMaxValue = new JLabel("");

    lblSum = new JLabel("Sum: ");

    lblSumValue = new JLabel("");

    lblAverage = new JLabel("Average: ");

    lblAverageValue = new JLabel("");

    btnImport = new JButton("Import list from file...");

    btnExport = new JButton("Export list to file...");

    cbxAsNumbers = new JCheckBox("As numbers", true);

    cbxAsString = new JCheckBox("As string");

    btnSort = new JButton("Sort list");

    btnReset = new JButton("Reset list");

    btnExit = new JButton("Exit");



    fileChooser = new JFileChooser(new File(".\\data"));

    fileFilter = new CustomFileFilter();

    fileFilter.addExtension(new String[] { ".txt", ".lst"});

    fileFilter.setDescription("List files (*.txt; *.lst)");

    fileChooser.setFileFilter(fileFilter);

    fileChooser.setSelectedFile(new File("content.txt"));



    txtInput.setHorizontalAlignment(JTextField.RIGHT);

    lblMinValue.setHorizontalAlignment(SwingConstants. RIGHT);

    lblMaxValue.setHorizontalAlignment(SwingConstants. RIGHT);

    lblSumValue.setHorizontalAlignment(SwingConstants. RIGHT);

    lblAverageValue.setHorizontalAlignment(SwingConsta nts.RIGHT);

    txtInputList.setEditable(false);



    ButtonAction action = new ButtonAction();



    btnInsert.addActionListener(action);

    btnSort.addActionListener(action);

    btnImport.addActionListener(action);

    btnExport.addActionListener(action);

    cbxAsNumbers.addChangeListener(action);

    cbxAsString.addChangeListener(action);

    btnReset.addActionListener(action);

    btnExit.addActionListener(action);



    cellSizes = new double[][] {

    { 10, 96, 10, TableLayout.FILL, 5, TableLayout.FILL, 10 },

    { 10, 24, 10, 24, 5, 24, 5, 24, 5, 24, 10, 24, 16, 24, 5, 24, 5, 24, 16, 24, 5, 24, 10 }

    };



    intArray = new int[MAX_NUMBER_OF_ENTRIES];

    counter = 0;



    Container contentPane = this.getContentPane();

    contentPane.setLayout(new TableLayout(cellSizes));

    contentPane.add(txtInput, "1, 1");

    contentPane.add(btnInsert, "3, 1, 5, 1");

    contentPane.add(scrollPane, "1, 3, 1, 21");

    contentPane.add(lblMin, "3, 3");

    contentPane.add(lblMinValue, "5, 3");

    contentPane.add(lblMax, "3, 5");

    contentPane.add(lblMaxValue, "5, 5");

    contentPane.add(lblSum, "3, 7");

    contentPane.add(lblSumValue, "5, 7");

    contentPane.add(lblAverage, "3, 9");

    contentPane.add(lblAverageValue, "5, 9");

    contentPane.add(btnSort, "3, 11, 5, 11");

    contentPane.add(btnImport, "3, 13, 5, 13");

    contentPane.add(btnExport, "3, 15, 5, 15");

    contentPane.add(cbxAsNumbers, "3, 17");

    contentPane.add(cbxAsString, "5, 17");

    contentPane.add(btnReset, "3, 19, 5, 19");

    contentPane.add(btnExit, "3, 21, 5, 21");



    scrollPane.setHorizontalScrollBarPolicy(ScrollPane Constants.HORIZONTAL_SCROLLBAR_NEVER);

    scrollPane.setVerticalScrollBarPolicy(ScrollPaneCo nstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    this.setTitle("Java Exercise");

    this.setResizable(false);

    this.pack();



    Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();

    Dimension frameDimension = this.getSize();

    this.setLocation((screenDimension.width - frameDimension.width) / 2,

    (screenDimension.height - frameDimension.height) / 2);

    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    }



    /**

    * Exit button event handler

    * @param e the fired event

    */

    private void btnExitActionPerformed(ActionEvent e) {

    this.setVisible(false);

    this.dispose();

    System.exit(0);

    }



    /**

    * Reset button event handler

    * @param e the fired event

    */

    private void btnResetActionPerformed(ActionEvent e) {

    for (int i = intArray.length; --i < 0

    intArray[i] = 0;



    counter = 0;



    txtInputList.setText("");

    lblMinValue.setText("");

    lblMaxValue.setText("");

    lblSumValue.setText("");

    lblAverageValue.setText("");



    txtInput.requestFocusInWindow();

    }





    [/CODE*]


    continua......

  2. #2
    Utente di HTML.it
    Registrato dal
    Dec 2004
    Messaggi
    75
    continua.....



    [CODE*]


    /**

    * Checkbox button event handler

    * @param e the fired event

    */

    private void cbxStateChanged(ChangeEvent e) {

    if (!cbxAsNumbers.isSelected() && !cbxAsString.isSelected()) {

    btnExport.setEnabled(false);



    return;

    }



    if (!btnExport.isEnabled())

    btnExport.setEnabled(true);

    }



    /**

    * Sort button event handler

    * @param e the fired event

    */

    private void btnSortActionPerformed(ActionEvent e) {

    if (counter != 0) {

    Arrays.sort(intArray, 0, counter);

    txtInputList.setText("");



    for (int i = 0; i < counter; i++)

    txtInputList.append(Integer.toString(intArray[i]) + "\n");

    }



    txtInput.requestFocusInWindow();

    }



    /**

    * Import button event handler

    * @param e the fired event

    */

    private void btnImportActionPerformed(ActionEvent e) {

    BufferedReader in = null;



    if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)

    try {

    in = new BufferedReader(new FileReader(fileChooser.getSelectedFile()));

    String str = null;



    while ((str = in.readLine()) != null) {

    if (str == null ? "==" == null : str.equals("=="))

    continue;

    if (str == null ? "" == null : str.equals(""))

    break;

    intArray[counter++] = Integer.parseInt(str);

    txtInputList.append(str + "\n");

    }

    } catch (FileNotFoundException ex) {

    JOptionPane.showMessageDialog(this,

    "Specified file not found.",

    "File Error",

    JOptionPane.ERROR_MESSAGE);

    } catch (NumberFormatException ex) {

    JOptionPane.showMessageDialog(this,

    "Number format error.",

    "Input Error",

    JOptionPane.ERROR_MESSAGE);

    } catch (IOException ex) {

    JOptionPane.showMessageDialog(this,

    "I/O stream error.",

    "I/O Error",

    JOptionPane.ERROR_MESSAGE);

    } catch (Exception ex) {

    JOptionPane.showMessageDialog(this,

    "Unexpected error.",

    "Import Error",

    JOptionPane.ERROR_MESSAGE);

    }

    finally {

    if (in != null) {

    try {

    in.close();

    } catch (IOException ex) {

    JOptionPane.showMessageDialog(this,

    "Error closing file.",

    "I/O Error",

    JOptionPane.ERROR_MESSAGE);

    } catch (Exception ex) {

    JOptionPane.showMessageDialog(this,

    "Unexpected error.",

    "Import Error",

    JOptionPane.ERROR_MESSAGE);

    }

    }



    this.setLabels();

    txtInput.requestFocusInWindow();

    }

    }



    /**

    * Export button event handler

    * @param e the fired event

    */

    private void btnExportActionPerformed(ActionEvent e) {

    PrintWriter out = null;



    if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)

    try {

    out = new PrintWriter(

    new BufferedWriter(new FileWriter(fileChooser.getSelectedFile().getPath() )));



    if (counter != 0) {

    if (cbxAsNumbers.isSelected() && cbxAsString.isSelected()) {

    for (int i = 0; i < counter; i++)

    out.println(intArray[i]);

    out.println("==");

    out.println(txtInputList.getText());

    }

    else {

    if (cbxAsNumbers.isSelected())

    for (int i = 0; i < counter; i++)

    out.println(intArray[i]);

    else if (cbxAsString.isSelected())

    out.println(txtInputList.getText());

    }



    if (out.checkError() == true)

    JOptionPane.showMessageDialog(this,

    "Print stream has encountered an error.",

    "Print Error",

    JOptionPane.ERROR_MESSAGE);

    }



    } catch (IOException ex) {

    JOptionPane.showMessageDialog(this,

    "I/O stream error.",

    "File Error",

    JOptionPane.ERROR_MESSAGE);

    }

    finally {

    if (out != null)

    out.close();

    txtInput.requestFocusInWindow();

    }

    }



    /**

    * Insert button event handler

    * @param e the fired event

    */

    private void btnInsertActionPerformed(ActionEvent e) {

    int nInput = 0;

    String strInput = txtInput.getText();



    try {

    nInput = Integer.parseInt(strInput);

    if (counter < intArray.length) {

    intArray[counter++] = nInput;

    txtInputList.append(Integer.toString(nInput) + "\n");

    this.setLabels();

    }

    else

    JOptionPane.showMessageDialog(this,

    "No more space in the list.",

    "Input Error",

    JOptionPane.ERROR_MESSAGE);

    } catch (NumberFormatException ex) {

    if (!strInput.equals(""))

    JOptionPane.showMessageDialog(this,

    "Number format error.",

    "Input Error",

    JOptionPane.ERROR_MESSAGE);

    } catch (Exception ex) {

    JOptionPane.showMessageDialog(this,

    "Unexpected error.",

    "Input Error",

    JOptionPane.ERROR_MESSAGE);

    }

    finally {

    txtInput.setText("");

    txtInput.requestFocusInWindow();

    }

    }



    /**

    * Helper method

    */

    private void setLabels() {

    if (counter == 1) {

    String strValue = Integer.toString(intArray[counter - 1]);

    lblMinValue.setText(strValue);

    lblMaxValue.setText(strValue);

    lblSumValue.setText(strValue);

    lblAverageValue.setText(strValue);



    return;

    }



    int tmpArray[] = new int[counter];

    Long sum = 0L;

    double average;



    for (int i = 0; i < counter; i++) {

    tmpArray[i] = intArray[i];

    String strSum = (sum += (long) intArray[i]).toString();

    try {

    Long.parseLong(strSum);

    lblSumValue.setText(strSum);

    } catch (NumberFormatException e) {

    lblSumValue.setText("Out of bounds");

    }

    }



    Arrays.sort(tmpArray);

    average = (double) sum / counter;



    lblMinValue.setText(Integer.toString(tmpArray[0]));

    lblMaxValue.setText(Integer.toString(tmpArray[counter - 1]));

    lblAverageValue.setText(Double.toString(average));

    }



    private JTextField txtInput;

    private JButton btnInsert;

    private JTextArea txtInputList;

    private JScrollPane scrollPane;

    private JLabel lblMin;

    private JLabel lblMinValue;

    private JLabel lblMax;

    private JLabel lblMaxValue;

    private JLabel lblSum;

    private JLabel lblSumValue;

    private JLabel lblAverage;

    private JLabel lblAverageValue;

    private JButton btnImport;

    private JButton btnExport;

    private JCheckBox cbxAsNumbers;

    private JCheckBox cbxAsString;

    private JButton btnSort;

    private JButton btnReset;

    private JButton btnExit;



    private JFileChooser fileChooser;

    private CustomFileFilter fileFilter;



    private double cellSizes[][];

    private int[] intArray;

    private int counter;

    private static final int MAX_NUMBER_OF_ENTRIES = 256;



    /**

    * Main method

    * @param args the command line arguments

    */

    public static void main(String[] args) {

    new JavaExerciseForm().setVisible(true);

    }



    }
    [/CODE*]


    grazie per la pazienza...

  3. #3
    Utente di HTML.it L'avatar di netarrow
    Registrato dal
    Apr 2004
    Messaggi
    1,425
    il tag code... senza * , basta scrivere tutto il codice, selezionarlo e premere code in alto.

    Scrivere tutto il sorgente è dispersivo e rende più complicato trovare l'errore, magari l'unico problema sta in una riga sola.

    Compila il programma e dicci che errore da.

    Imparare è un'esperienza, tutto il resto è solo informazione. (Albert Einstein)

  4. #4
    Utente di HTML.it
    Registrato dal
    Dec 2004
    Messaggi
    75
    Scusa ma non ho proprio capito!!!!!

    esempio il pezzo di codice che mi da errore è:
    (la riga è evidenziata e mi dice:si suppone che ci sia ( o [

    public void addExtension(String[] extensions) {

    ArrayList<String> newExtensions = new ArrayList<String>(extensions.length);


    for (int i = 0; i < extensions.length; i++) {

    if (extensions[i].startsWith(".")) {

    newExtensions.add(i, extensions[i].toLowerCas());

    continue;

    }



    newExtensions.add(i, "." + extensions[i].toLowerCase());

    }



    this.extensions.addAll(newExtensions);

    }

  5. #5
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,304
    Quello che intendeva dirti netarrow è che i tag CODE che hai usato, si scrivono senza l'asterisco: tu hai scritto [CODE*] e [/CODE*]

    L'errore credo che sia dovuto al fatto che tu stai utilizzando il compilatore della JDK 1.4, mentre stai scrivendo codice per la 1.5.

    Scegli: o scrivi codice per la 1.4 oppure scarichi la JDK 1.5.


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  6. #6
    Utente di HTML.it
    Registrato dal
    Dec 2004
    Messaggi
    75
    Quindi per non scaricare la 1.5 dovrei adattare il codice per la 1.4....!!!!!

    Sai per caso cos'è che dovrei modificare?

  7. #7
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,304
    Sì... gli ArrayList non sono tipizzati:
    codice:
    ArrayList newExtensions = new ArrayList(extensions.length);
    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  8. #8
    Utente di HTML.it
    Registrato dal
    Dec 2004
    Messaggi
    75
    e l'errore in questo?

    codice:
    public boolean accept(File f) {
    
                if (f.isDirectory())
    
                    return true;
    
    
    
                String fileName = f.getName().toLowerCase();
    
    
    
                for (int i = 0; i < extensions.size(); i++)
    
                    if (fileName.endsWith(extensions.get(i))) 
    
                        return true;
    
    
    
                return false;
    
            }

  9. #9
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,304
    Manca il cast a String: il metodo get() di ArrayList ritorna un Object:
    codice:
    if ( fileName.endsWith((String) extensions.get(i)) ) {
       ...
    }
    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  10. #10
    Utente di HTML.it
    Registrato dal
    Dec 2004
    Messaggi
    75
    Scusa ne aprofitto...

    e questo:

    String strSum = (sum += (long) intArray[i]).toString();

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.