Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Multiple errors - Reading data from a file and using a GUI to display

  1. #1
    Junior Member
    Join Date
    Nov 2011
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Multiple errors - Reading data from a file and using a GUI to display

    Hi there,

    First off, I apologize if this is a long post, I'm new to this forum and I wanted to make sure that everyone understands what I'm trying to achieve.

    I'm currently doing a Java programming class at my school and I'm in the last week of the class having completed a whole semester of 16 weeks. According to my instructor, I've really gotten the hang of Java (considering this is the first time I used Java, I'm pretty pleased about this). Anyway, throughout most of the class, I've been able to figure out what the errors are in my programs and I've managed to fix them so that I can submit them for grading. However, I'm on my last lab and I'm a bit stumped and I'd like to see if anyone on here can help.

    For the final lab, we've been asked to read in a data file containing 10(ten) items of food and the amount of calories each one has. As this our last lab, we need to use Java swing to create a GUI with buttons, a text field and check boxes and this data read from the file should then go into to a drop-down list (I assume that the best way to do this is with a combo box). The user is then going to chose an item from the combo box for the food they want to eat and enter the number of 'food' they want to eat in the text field. Then, they click a button to calculate the total amount of calories for that food. We were also asked to give the user the option of converting the food to grams (to do this, it was suggested that we keep all the food items in the same measurement to start with, making it easier to convert them to another measurement). I chose to have all the foods in ounces, so converting them to grams would be very easy.

    I created the program in it's entirety and figured out most of the errors, which were simple typos or missing semi-colons at the end of the of some of the lines where they should be. However, now I have four errors which have really stumped me including one that I have never seen before. I think that part of the issue is where I am storing the data from the file in an array and then moving only the food items to the combo box and attaching a listener action to it.

    Here's the kind of data I'm reading in:

    Food,Calories(Ounces)
    100% NATURAL CEREAL(1 oz),135
    WHOLE ALMONDS(1 oz),165
    BLUE CHEESE(1 oz),100
    BRAZIL NUTS(1 oz),185
    CAP'N CRUNCH CEREAL(1 oz),120

    I've told the program I'm reading and then discarding the first line (as this is just a header) and then the food (the first field on each line) will be stored in the 'foods' array and the second field after the comma the calories, will be stored in the 'calories' array.

    Here is the program I've written. I've left comments in the program as this will probably help.

    // Import the Java swing, scanner and the io classes
    import java.io.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Scanner;
    import java.text.DecimalFormat;
     
    public class CalorieGui extends JFrame // Start of CalorieGui class
    {
      private JButton calcButton;
      private JButton exitButton;
      public JPanel buttonPanel;
     
      private JComboBox foodList;
      public JPanel comboPanel;
     
      private JTextField caloriesTextField;
      private JLabel messageLabel;
      private JLabel messagelabel2;
      public JPanel caloriePanel;
     
      public JPanel headerPanel;
      public JPanel inputPanel;
     
      private JRadioButton ouncesButton;
      private JRadioButton gramsButton;
      private ButtonGroup radioButtonGroup;
      public JPanel radioButtonPanel;  
     
     
      private final double conversion  = 28.3495231;
     
      String[] foods = new String[9];
      double[] calories = new double[9];  
     
       public CalorieGui()  	
       {
        super ("Calorie Counter");
     
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     
    	setSize(400, 380);
            setLayout(new GridLayout(5,1));
     
            readFile();
     
    	makeHeaderPanel();
    	makeComboPanel();
    	makeInputPanel();
    	makeRadioButtonPanel();
    	makeButtonPanel();
     
            add(headerPanel);
            add(comboPanel);
            add(inputPanel);
            add(radioButtonPanel);
            add(buttonPanel);
     
            pack();
            setVisible(true);
        }
     
        private void readFile()  // Start of the readFile method
       {
        String GetLine = ""; // Create a string for getting a line
        String MyData[]; // Create string array for storing the data read from the file
     
        File InFile = new File("Calories.dat");
     
       	try
        	{
        	  FileInputStream InStream = new FileInputStream(InFile); // Create an input stream for the file to be read
        	  BufferedReader br = new BufferedReader (new InputStreamReader (InStream)); // Create a input bufferedreader for the file to be read
     
        	    int Counter = 0; // Create a counter and set it to zero
     
        	    GetLine = br.readLine(); // Read the first line of data from the file, which is the header and store it in 'Getline'. We are not going to need it
     
    	  /* Create a while loop that reads in each line of data and stores the first peice of data in the mydata array and looks for a comma 
              * in-between each
    	  * peice of data on the line, so that it puts each peice in it's own part of the array createed for it. The name of the food goes into the 
              *food
    	  * array and the calories go into the calories array. The loop then increases the counter by one for each line that is read
              */
        		while ((GetLine = br.readLine()) !=null) 
        		 {
        			MyData = GetLine.split(",");
     
        			foods[Counter] = String.parseString(MyData[0]); // This is the first error...says cannot find symbol
        			calories[Counter] = Double.parseDouble(MyData[1]);
     
    			Counter++;
        		}
     
        	   // Tell the user that the file has been read
    	  JOptionPane.showMessageDialog(null,"Finished reading in the list of data from the Calorie file");
     
    	  // Close the files as we are finished reading it
        	  br.close();
     
           }  //end try
        	  catch (Exception e)
     
        	  {
        	     // Tell the user what the error is if we cannot use the try method above
        	     JOptionPane.showMessageDialog(null,"Error " + e.getMessage());
        	  }  // end catch
     
       } //  End of readFile method
     
       private void makeHeaderPanel() // Start of the makeHeaderPanel method
       	{
       	  headerPanel = new JPanel(); // Create a new panel for the header
     
       	  JLabel heading = new JLabel("Food Calorie calculator"); // Put a label on the panel for the heading
     
       	  headerPanel.add(heading); // Add the heading to the header panel
       	}  // End of the makeHeaderPanel method
     
       private void makeComboPanel() // Start of of makeComboPanel method
          {
             comboPanel = new JPanel(); //Create the ComboBox panel
     
    	 foodList = new JComboBox(); // Create a combo list in this box for the food list
     
             // Create a for loop which moves each item from the food array created above into it's own position in the combo box
             for(int i = 0; i < foods.length; i++) 
            {
               foodList.addItem(new String(foods[i]));
    	   foodList.addItem(foods[i]);
            } // End of for loop
     
            // Create a listener action for the combo box when the user selects an item in the combobox
            foodList.addActionListener(new ComboBoxListener()); 
            comboPanel.add(foodList); // Add the foodlist to the combo panel
         } // End of makeComboPanel method
     
       private void makeInputPanel() // Start of makeInputPanel method
        {
        	inputPanel =  new JPanel(); //Create the input panel
     
        	messageLabel = new JLabel("Amount of food you want to eat:"); // Put a label next to this text field
          	caloriesTextField = new JTextField(4); /// Create a text field for the user to enter the number of foods they want to eat
     
          	// Add the label and text field to the panel.
          	inputPanel.add(messageLabel); 
          	inputPanel.add(caloriesTextField);
     
        } // End of makeInputPanel method
     
       private void makeRadioButtonPanel() // Start of the makeRadioButton panel
        {
          radioButtonPanel = new JPanel(); // Create the radio button panel
     
          messagelabel2 = new JLabel("Convert to grams or leave as ounces?"); // Create a message label for the radio buttons
     
          ouncesButton = new JRadioButton("Ounces", true); // Create the Ounces radio button and mark it selected
          gramsButton = new JRadioButton("Grams"); // Create the Grams radio button 
          ButtonGroup group = new ButtonGroup(); // Create a new button group for the radio buttons
     
          // Add the buttons to radio button group
         group.add(ouncesButton);
         group.add(gramsButton);
     
         // Add the radio buttons to the panel
          radioButtonPanel.add(messagelabel2);
          radioButtonPanel.add(ouncesButton);
          radioButtonPanel.add(gramsButton);
        } // Start of the makeRadioButton panel
     
       private void makeButtonPanel() // Start of the makeButton panel
        {
        	buttonPanel =  new JPanel(); //Create the button panel
     
        	calcButton = new JButton("Calculate"); // Create the Calculate button
          	exitButton = new JButton("Exit"); // Create the Exit button
     
          	// Register the action listeners.
          	calcButton.addActionListener(new CalcButtonListener());
          	exitButton.addActionListener(new ExitButtonListener());
     
          	// Add the buttons to the button panel.
         	buttonPanel.add(calcButton);
          	buttonPanel.add(exitButton);
        } // End of the makeButton panel
     
        private class ComboBoxListener implements ActionListener // Start of Combo box listener class
         {
    	public void actionPerformed(ActionEvent e) // Start of actionPerformed method for the listener
    	 {
    	  // This is the second and third errors I am getting, because I'm not sure how to handle the selected item in the combo box with the 
                  listener
     
                  int i;
    	      String selectedFood;
    	      Double selectedCalories;
    	      i = foodList.getSelectedIndex();
    	      selectedFood = foodList[i]; 
    	      selectedCalories = foodList[i]; 
    	 }
          } // End of Combo box listener class
     
        private class CalcButtonListener implements ActionListener // Start of Calc button listener class
        {
            public void actionPerformed(ActionEvent e) // Start of actionPerformed method for the listener
          	{
            // Create te variables for storing the data when the button is pressed
             String numberin;
             double caloriesOut;
    	 double numFood;
    	 double total;
     
    	 // Get the value from the calories text field and put it into the muberin variable
             numberin = caloriesTextField.getText();
     
             // Transfer the string value to the numFood variable and parse as a double
             numFood = Double.parseDouble(numberin);
     
             caloriesOut = selectedCalories; // Store the selected calories in the CaloriesOut variable
     
    	    // If statment for the number of foods to be eaten, if it's negative, display a dialog box instead of calculating
    	    if (numFood<0)
    		  JOptionPane.showMessageDialog(null,"Please enter a positive figure");
     
    	   else // If the number is positive, use it to calculate the total number of calories, either in ounces or converted to grams
    		{
    		  if (ouncesButton.isSelected())
    		   total =  caloriesOut * numFood;
     
    		  else 
    		    total =  caloriesOut * numFood * conversion;
    		}
     
               // Create a DecimalFormat object to format the total to two decimal places.
               DecimalFormat calorieAmount = new DecimalFormat("0.00");
     
    	   // Display the toal sales from the total variable in message dialog using the decimal format
               JOptionPane.showMessageDialog(null, "Total amount of calories per gram: " + calorieAmount.format(total));
     
       	  } // End of actionPerformed method
        } // End of Calc button listener class
     
       private class ExitButtonListener implements ActionListener // Start of Exit button listener class
       {
          public void actionPerformed(ActionEvent e) // Start of actionPerformed method for the listener
          {
             System.exit(0); // Exit the application.
          } // End of actionPerformed method
       } // End of Exit button listener class
    }// End of CalorieGui class
    The errors I'm getting in the program are listed in the comments above, but there is one error that applies to the whole program and this is the one I've never seen before..

    CalorieGui.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.

    I don't know how to recompile with -xlint, so I have no idea what this means.

    I would be very grateful if anyone can help me with this program and tell me what I've done wrong. Thank you so much!


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,067
    Thanks
    47
    Thanked 2,146 Times in 2,119 Posts

    Default Re: Multiple errors - Reading data from a file and using a GUI to display

    how to recompile with -xlint,
    Here is the command line I use for compiling with some sample compiler options:
    F:\Java\jdk1.6.0_29\bin\javac.exe -Xlint -g -deprecation -classpath D:\JavaDevelopment\;.;..\. ClientServer_Problem.java

    errors I'm getting in the program are listed in the comments
    If you get errors, please copy and post the full text of the error message in your post.

  3. The Following User Says Thank You to Norm For This Useful Post:

    toledospod (November 30th, 2011)

  4. #3
    Junior Member
    Join Date
    Nov 2011
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Multiple errors - Reading data from a file and using a GUI to display

    Thanks for the advice Norm. I was actually able to get the help I needed from my instructor(I emailed just after posting this, but she was busy over the holidays and I forgot to check on here for any replies until yesterday). It turned out that I didn't need this part of the code at all:

    private class ComboBoxListener implements ActionListener // Start of Combo box listener class
         {
    	public void actionPerformed(ActionEvent e) // Start of actionPerformed method for the listener
    	 {
    	      int i;
    	      String selectedFood;
    	      Double selectedCalories;
    	      i = foodList.getSelectedIndex();
    	      selectedFood = foodList[i]; 
    	      selectedCalories = foodList[i]; 
    	 }
          } // End of Combo box listener class

    My instructor said that the calc button listener would do all the work for me. She also told me that I didn't need to use "String.ParseString" when getting the food item from the file.

    I added the "-xlint:checked" to the compiler parameters and realized that this wasn't an error but just a warning (my program compiles without errors now)

    Just out of curiosity, here's the warning I got when I added -xlint:

    warning: [unchecked] unchecked call to JComboBox(E[]) as a member of the raw type JComboBox
    foodList = new JComboBox(foods); // Create a combo list in this box for the food list

    where E is a type-variable:
    E extends Object declared in class JComboBox
    Does anyone know what this means?

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,067
    Thanks
    47
    Thanked 2,146 Times in 2,119 Posts

    Default Re: Multiple errors - Reading data from a file and using a GUI to display

    The message deals with Generics, a way to have the compiler check the types of objects you use with various classes.

  6. #5
    Junior Member
    Join Date
    Nov 2011
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Multiple errors - Reading data from a file and using a GUI to display

    Could explain what you mean by that, I don't really understand.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,067
    Thanks
    47
    Thanked 2,146 Times in 2,119 Posts

    Default Re: Multiple errors - Reading data from a file and using a GUI to display

    Take a look at the java tutorial. Go to this site and Find Generics:
    The Really Big Index

Similar Threads

  1. Reading File and Outputting Data
    By ChrisMessersmith in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 13th, 2011, 12:40 PM
  2. Help with Scanner class - Reading Data from a file
    By billias in forum What's Wrong With My Code?
    Replies: 7
    Last Post: June 28th, 2011, 12:07 PM
  3. Help reading data from file, manipulating then rewriting out.
    By Nismoz3255 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: May 19th, 2011, 09:13 AM
  4. Reading data from a text file into an object
    By surfbumb in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 6th, 2011, 08:37 PM
  5. Reading from a file, multiple lines
    By MysticDeath in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: October 15th, 2009, 02:40 AM