What's wrong with my codes? Please help!

*Questions are #13 and #14. These should be combined.
Can you please tell me why the following is not answering the questions #13 and #14?
Thank you!!
import java.util.Scanner;               // Needed for Scanner class
import java.text.DecimalFormat;          // Needed for DecimalFormat class
     #13:
          An Internet service provider has three different subscription
          packages for its customers:
          Package A:          For $9.95 per month 10 hours of access are provided.
                              Additional hours are $2.00 per hour.
          Package B:          For $13.95 per month 20 hours of access are provided.
                              Additional hours are $1.00 per hour.
          Package C:          For $19.95 per month unlimited access is provided.
          Write a program that calculates a customer's monthly bill. It should
          ask the user to enter the letter of the package the customer has
          purchased (A, B, or C) and the number of hours that were used. It should
          then display the total charges.
     #14:
          Modify the program you wrote for Programming Challenge 13 so it also
          calculates and displays the amount of money Package A customers
          would save if they purchased Package B or C, and the amount of
          money Package B customers would save if they purchased Package C.
          If three would be no savings, no message should be printed.
public class Internet3
     public static void main(String[] args)
          char ch, ch1;
          int hours;
          double monthlyBill, additionalBill, savings, total, saved;
          // Create a Scanner object for keyboard input.
          Scanner keyboard = new Scanner(System.in);
          // Get the letter of the package the user has purchased.
          System.out.println("Enter one of the letters of the package" +
                                   "you have purchased: A, B, or C?\nNote: "
                                   + "Please type in uppercase.");
          ch = keyboard.nextLine().charAt(0);
          // Create a DecimalFormat object.
          DecimalFormat formatter = new DecimalFormat("#0.00");
          // If the user typed A
          if (ch == 'A')
               System.out.println("Have you purchased an additional package?" +
                                        " If so, enter the letter of the package." +
                                        " then press the enter key. If not, just "+
                                        "type N.\nNote: Please type in uppercase.");
               ch1 = keyboard.nextLine().charAt(0);
               if (ch1 == 'B' || ch1 == 'C')     // If the user typed B or C
                    System.out.println("Enter the number of hours " +
                                        "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 10)               // If the user typed int less than or equal to 10
                         monthlyBill = 9.95;
                         System.out.println("Your original monthly bill is $" + monthlyBill);
                         savings = -4.00;
                         saved = monthlyBill + savings;
                         System.out.println("You saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
                    else                              // If the user typed int more than 10
                         monthlyBill = 9.95;
                         total = monthlyBill + ((hours - 10)*2);
                         System.out.println("Your original monthly bill is $" + total);
                         savings = -4.00;
                         saved = total + savings;
                         System.out.println("You saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
               else if (ch1 == 'N')               // If the user typed N
                    System.out.println("Enter the number of hours " +
                                             "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 10)               // If the user typed int less than or equal to 10
                         monthlyBill = 9.95;
                         System.out.println("Your monthly bill is $" + monthlyBill);
                    else                              // If the user typed int more than 10
                         monthlyBill = 9.95;
                         total = monthlyBill + ((hours - 10)*2);
                         System.out.println("Your monthly bull is $" + formatter.format(total));
          else if (ch == 'B')                         // If the user typed B
               System.out.println("Have you purchased an additional package?" +
                                        " If so, enter the letter of the package." +
                                        " then press the enter key. If not, just "+
                                        "type N.\nNote: Please type in uppercase.");
               ch1 = keyboard.nextLine().charAt(0);
               if (ch1 == 'C')                         // If the user typed C
                    System.out.println("Enter the number of hours " +
                                             "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 20)               // If the user typed int less than or equal to 20
                         monthlyBill = 13.95;
                         System.out.println("Your original monthly bill is $" + monthlyBill);
                         savings = -4.00;
                         saved = monthlyBill + savings;
                         System.out.println("Your saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
                    else                              // If the user typed int more than 20
                         monthlyBill = 13.95;
                         total = monthlyBill + (hours - 20);
                         System.out.println("Your original monthly bill is $" + total);
                         savings = -4.00;
                         saved = total + savings;
                         System.out.println("You saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
               else if (ch1 == 'N')               // If the user typed N
                    System.out.println("Enter the number of hours " +
                                             "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 20)               // If the user typed int less than or equal to20
                         monthlyBill = 13.95;
                         System.out.println("Your monthly bill is $" + monthlyBill);
                    else                              // If the user typed int more than 20
                         monthlyBill = 13.95;
                         total = monthlyBill + (hours - 20);
                         System.out.println("Your monthly bill is $" + formatter.format(total));
          else if (ch == 'C')                         // If the user typed C
               System.out.println("Enter the number of hours " +
                                        "that you used in mounth.");
               hours = keyboard.nextInt();
               if (hours > 0)                         // If the user typed int more than 0
                    monthlyBill = 19.95;
                    System.out.println("Your monthly bill is $" + monthlyBill);
          else                                        // If the user typed a character other than A, B, or C
               System.out.println("That's not A, B, or C!");
}

#13:
          An Internet service provider has three different subscription
          packages for its customers:
          Package A:          For $9.95 per month 10 hours of access are provided.
                              Additional hours are $2.00 per hour.
          Package B:          For $13.95 per month 20 hours of access are provided.
                              Additional hours are $1.00 per hour.
          Package C:          For $19.95 per month unlimited access is provided.
          Write a program that calculates a customer's monthly bill. It should
          ask the user to enter the letter of the package the customer has
          purchased (A, B, or C) and the number of hours that were used. It should
          then display the total charges.
     #14:
          Modify the program you wrote for Programming Challenge 13 so it also
          calculates and displays the amount of money Package A customers
          would save if they purchased Package B or C, and the amount of
          money Package B customers would save if they purchased Package C.
          If three would be no savings, no message should be printed.
import java.util.Scanner;               // Needed for Scanner class
import java.text.DecimalFormat;          // Needed for DecimalFormat class
public class Internet3
     public static void main(String[] args)
          char ch, ch1;
          int hours;
          double monthlyBill, additionalBill, savings, total, saved;
          // Create a Scanner object for keyboard input.
          Scanner keyboard = new Scanner(System.in);
          // Get the letter of the package the user has purchased.
          System.out.println("Enter one of the letters of the package" +
                                   "you have purchased: A, B, or C?\nNote: "
                                   + "Please type in uppercase.");
          ch = keyboard.nextLine().charAt(0);
          // Create a DecimalFormat object.
          DecimalFormat formatter = new DecimalFormat("#0.00");
          // If the user typed A
          if (ch == 'A')
               System.out.println("Have you purchased an additional package?" +
                                        " If so, enter the letter of the package." +
                                        " then press the enter key. If not, just "+
                                        "type N.\nNote: Please type in uppercase.");
               ch1 = keyboard.nextLine().charAt(0);
               if (ch1 == 'B' || ch1 == 'C')     // If the user typed B or C
                    System.out.println("Enter the number of hours " +
                                        "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 10)               // If the user typed int less than or equal to 10
                         monthlyBill = 9.95;
                         System.out.println("Your original monthly bill is $" + monthlyBill);
                         savings = -4.00;
                         saved = monthlyBill + savings;
                         System.out.println("You saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
                    else                              // If the user typed int more than 10
                         monthlyBill = 9.95;
                         total = monthlyBill + ((hours - 10)*2);
                         System.out.println("Your original monthly bill is $" + total);
                         savings = -4.00;
                         saved = total + savings;
                         System.out.println("You saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
               else if (ch1 == 'N')               // If the user typed N
                    System.out.println("Enter the number of hours " +
                                             "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 10)               // If the user typed int less than or equal to 10
                         monthlyBill = 9.95;
                         System.out.println("Your monthly bill is $" + monthlyBill);
                    else                              // If the user typed int more than 10
                         monthlyBill = 9.95;
                         total = monthlyBill + ((hours - 10)*2);
                         System.out.println("Your monthly bull is $" + formatter.format(total));
          else if (ch == 'B')                         // If the user typed B
               System.out.println("Have you purchased an additional package?" +
                                        " If so, enter the letter of the package." +
                                        " then press the enter key. If not, just "+
                                        "type N.\nNote: Please type in uppercase.");
               ch1 = keyboard.nextLine().charAt(0);
               if (ch1 == 'C')                         // If the user typed C
                    System.out.println("Enter the number of hours " +
                                             "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 20)               // If the user typed int less than or equal to 20
                         monthlyBill = 13.95;
                         System.out.println("Your original monthly bill is $" + monthlyBill);
                         savings = -4.00;
                         saved = monthlyBill + savings;
                         System.out.println("Your saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
                    else                              // If the user typed int more than 20
                         monthlyBill = 13.95;
                         total = monthlyBill + (hours - 20);
                         System.out.println("Your original monthly bill is $" + total);
                         savings = -4.00;
                         saved = total + savings;
                         System.out.println("You saved $4.00 and the total monthly bill is $" +
                                                  formatter.format(saved));
               else if (ch1 == 'N')               // If the user typed N
                    System.out.println("Enter the number of hours " +
                                             "that you used in month.");
                    hours = keyboard.nextInt();
                    if (hours <= 20)               // If the user typed int less than or equal to20
                         monthlyBill = 13.95;
                         System.out.println("Your monthly bill is $" + monthlyBill);
                    else                              // If the user typed int more than 20
                         monthlyBill = 13.95;
                         total = monthlyBill + (hours - 20);
                         System.out.println("Your monthly bill is $" + formatter.format(total));
          else if (ch == 'C')                         // If the user typed C
               System.out.println("Enter the number of hours " +
                                        "that you used in mounth.");
               hours = keyboard.nextInt();
               if (hours > 0)                         // If the user typed int more than 0
                    monthlyBill = 19.95;
                    System.out.println("Your monthly bill is $" + monthlyBill);
          else                                        // If the user typed a character other than A, B, or C
               System.out.println("That's not A, B, or C!");
}          

Similar Messages

  • What's wrong with my code? Help

    I'm attaching the code here in case it'd help in getting a faster response. This is supposed to be an exercise in turtle graphics. The idea is to use the program to draw shapes using a series of commands (I'm sure the experts here are familiar with it). It compiles and runs fine, however whenever certain commands are entered, after the move command, the program gives an exception "Array is out of bounds".
    For instance, if I enter
    1)2, 5, 1(step), 5, 1( step)
    and the print result it also not working.
    I'm a newbie to this, and I'm just trying to learn. Please help!
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;
    public class Turtle extends JApplet implements ActionListener
    JLabel commandLabel;
    JTextField command;
    JTextArea outputArea, array_area;
    char floor[][];
    int direction=0;
    String output="", number="";
    int i,j,n,com=0;
    int num=0,direct=0,pen_status=0;
    public void init()
    Container c= getContentPane();
    c.setLayout(new FlowLayout());
    outputArea = new JTextArea(9,15 );
    outputArea.setText("command"+"\n"+"1:pen up"+"\t"+"2:pen down"+"\n"+ "3:turn right"+"\t"+"4:turn left"+"\n"+ "5:move"+"\n"+"6:print"+"\n"+"9:end data");
    c.add(outputArea);
    commandLabel=new JLabel("Enter the command");
    c.add(commandLabel);
    command=new JTextField(8);
    command.addActionListener(this);
    c.add(command);
    floor=new char[20][20];
    for(int i=0;i<20;i++){
    for(int j=0;j<20;j++) {
    floor[i][j]='0';
    output+=floor[i][j];
    output+="\n";
    i=j=0;
    array_area = new JTextArea(20,20);
    c.add(array_area);
    array_area.setText(output);
         public void actionPerformed(ActionEvent e)
              play();
         public void play(){
    com = Integer.parseInt(command.getText());
    switch (com){
    case 1:
    showStatus("Pen is up");
    pen_status=0;
         command.setText("");
         break;
    case 2:
    showStatus("Pen is down");
    pen_status=1;
    command.setText("");
         break;
    case 3:
    showStatus("Turn right");
    direction+=90;
    command.setText("");
         break;
    case 4:
    showStatus("Turn left");
    direction-=90;
    command.setText("");
         break;
    case 5:
    number=JOptionPane.showInputDialog("Enter a number");
    num=Integer.parseInt(number);
    showStatus("moving");
    move();
    command.setText("");
         break;
    case 6:
    showStatus("print");
         print();
         command.setText("");
         break;          
    case 9:
         command.setEditable(false);
         break;
         default:
         showStatus("Entered the Wrong command");
    command.setText("");
         break;
         public void move()
         if (pen_status==0){
         direct = direction%360;
         switch(direct){
         case 90:
         for(n=1;n<=num;n++)
         j++;
         break;
    case 180:
    for(n=1;n<=num;n++)
         i++;
         break;
    case 270:
    for(n=1;n<=num;n++)
         j--;
         break;
    case 0:
    for(n=1;n<=num;n++)
         i--;
         break;
    else if(pen_status==1){
         direct = direction%360;
         switch(direct){
         case 90:
    for(n=1;n<=num;n++)
         floor[i][j++]='1';          
         break;
    case 180:
         for(n=1;n<=num;n++)
    floor[i++][j]='1';
         break;
    case 270:
         for(n=1;n<=num;n++)
    floor[i][j--]='1';
         break;
    case 0:
         for(n=1;n<=num;n++)
    floor[i--][j]='1';
         break;
         public void print()
         int a, b;
         output="";
         for(a=0;a<20;a++){
         for(b=0;b<20;b++){
         if(floor[a]=='1') {
         output+="*";
         else
         output+=" ";
         output+="\n";
         array_area.setText(output);     

    Ok, I wasn't aware of the code tags..
    Here're the errors I'm getting when I run the move command:
    java.lang.ArrayIndexOutOfBoundsException: -5
            at Turtle.move(Turtle.java:126)
            at Turtle.play(Turtle.java:80)
            at Turtle.actionPerformed(Turtle.java:51)
            at javax.swing.JTextField.fireActionPerformed(JTextField.java:489)
            at javax.swing.JTextField.postActionEvent(JTextField.java:670)
            at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:7
    84)Can anyone help? I'm out of ideas and frustrated

  • I can't open any program anymore an my ipod since the last 30 minutes, no more games and social network programs. What is wrong with my ipod.Please help

    I can't open any program anymore on my ipod since the last 30 minutes, please help

    Did you try to reset the device by holding the sleep and home button until the Apple logo come back again?
    If this does not work, set it up again "as new device", shown in this article: How to set up your iPhone or iPod touch as a new device

  • What's wrong with my code? please help....

    when display button is clicked it must diplay the remarks but it didn't happen...
    what's wrong with my code? please help
    here is my code.....
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class Area extends Applet implements ItemListener,ActionListener
         {Label arlbl = new Label("AREA");
          Choice archc = new Choice();
          Label extlbl = new Label("EXPENDITURE TYPE");
          CheckboxGroup extchk = new CheckboxGroup();
              Checkbox fchk = new Checkbox("FOOD",extchk,true);
              Checkbox schk = new Checkbox("SHELTER",extchk,false);
              Checkbox echk = new Checkbox("EDUCATION",extchk,false);
              Checkbox uchk = new Checkbox("UTILITIES",extchk,false);
          Label exalbl = new Label("EXPENDITURE AMOUNT");
          TextField exatf = new TextField("",20);
          Label remlbl = new Label("REMARKS");
          TextField remtf = new TextField("",30);
          Button disbtn = new Button("DISPLAY");
          Button resbtn = new Button("RESET");
          String display;
          public void init()
              {add(arlbl);
               archc.add("MANILA");
               archc.add("MAKATI");
               archc.add("QUEZON");
               archc.add("PASAY");
               add(archc);
               archc.addItemListener(this);
               add(extlbl);
               add(fchk);
               fchk.addItemListener(this);
               add(schk);
               schk.addItemListener(this);     
               add(echk);
               echk.addItemListener(this);
               add(uchk);
               uchk.addItemListener(this);
               add(exalbl);
               add(exatf);
               add(remlbl);
               add(remtf);
               add(disbtn);
               disbtn.addActionListener(this);
               add(resbtn);
               resbtn.addActionListener(this);
         public void itemStateChanged(ItemEvent ex)
              {int n = archc.getSelectedIndex();
               if(n==0)
                   {if(fchk.getState())
                         {exatf.setText("10000.00");
                         display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("8500.00");
                        display = archc.getSelectedItem();
              if(n==1)
                   {if(fchk.getState())
                        {exatf.setText("5000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("11000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("7500.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
              if(n==2)
                   {if(fchk.getState())
                        {exatf.setText("13000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("7000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("27000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
              if(n==3)
                   {if(fchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("9000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("19000.00");
                        display = archc.getSelectedItem();
         public void actionPerformed(ActionEvent e)
              {if(e.getSource() == disbtn)
                    {String amtstr = exatf.getText();
                     int amt = Integer.parseInt(amtstr);
                        {if(amt > 8000)
                             {remtf.setText(display + " IS ABOVE BUDGET");
                        else
                             {remtf.setText(display + " IS BELOW BUDGET");
              if(e.getSource() == resbtn)
                   {archc.select(0);
                   fchk.setState(true);
                   schk.setState(false);
                   echk.setState(false);
                   uchk.setState(false);
                   exatf.setText("");
                   remtf.setText("");
    Edited by: lovely23 on Feb 28, 2009 11:24 PM

    Edit: thanks for cross-posting this question on another forum. I now see that I wasted my time trying to study your code in the java-forums to help you with an answer that had already been answered elsewhere (here). Do you realize that we are volunteers, that our time is as valuable as yours? Apparently not. Cross-post again and many here will not help you again. I know that I won't.

  • FileFilter????What's wrong with this code???HELP!!

    I want to limit the JFileChooser to display only txt and java file. But the code I wrote has error and I don't know what's wrong with it. can anyone help me to check it out? Thank you.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class FileFilterTest extends JPanel
         public static void main(String[] args)
              new FileFilterTest();
         public class fFilter implements FileFilter
              public boolean accept(File file)
                   String name = file.getName();
                   if(name.toLowerCase().endsWith(".java") || name.toLowerCase().endsWith(".txt"))
                        return true;
                   else
                        return false;
         public FileFilterTest()
              JFileChooser fc = new JFileChooser();
              fc.setFileFilter(new fFilter());
              fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
              //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              //fc.setMultiSelectionEnabled(true);
              int returnVal = fc.showDialog(FileFilterTest.this, "Open File");
              if(returnVal == JFileChooser.APPROVE_OPTION)
                   String file = fc.getSelectedFile().getPath();
                   if(file == null)
                        return;
              else if(returnVal == JFileChooser.CANCEL_OPTION)
                   System.exit(0);
              else
                   System.exit(0);
              JFrame f = new JFrame();
              FileFilterTest ff = new FileFilterTest();
              f.setTitle("FileFilterTest");
              f.setBackground(Color.lightGray);
              f.getContentPane().add(ff, BorderLayout.CENTER);
              f.setSize(800, 500);
              f.setVisible(true);
    }

    There are two file filters
    class javax.swing.filechooser.FileFilter
    interface java.io.FileFilter
    In Swing you need to make a class which extends the first one and implements the second. Sometimes you may not need to implement the second, but it is more versitle to do so and requires no extra work.

  • What's wrong with my code? compliation error

    There is a compilation error in my program
    but i follow others sample prog. to do, but i can't do it
    Please help me, thanks!!!
    private int selectedRow, selectedCol;
    final JTable table = new JTable(new MyTableModel());
    public temp() {     
    super(new GridLayout(1, 0));                         
    table.setPreferredScrollableViewportSize(new Dimension(600, 200));     
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);     
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
         //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
         System.out.println("No rows are selected.");
    else {
         selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow+ " is now selected.");
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
    createPopupMenu();
    public void createPopupMenu() {       
    //Create the popup menu.
    JPopupMenu popup = new JPopupMenu();
    // display item
    JMenuItem menuItem = new JMenuItem("Delete selected");
    popup.add(menuItem);
    menuItem.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
              System.out.println("Display selected.");
              System.out.println("ClientID: "+table.getValueAt(selectedRow,0));
              int index = table.getSelectedColumn();
              table.removeRow(index);     <-------------------------------compliation error     
         }}); //what's wrong with my code? can anyone tell
    //me what careless mistake i made?
    MouseListener popupListener = new PopupListener(popup);
    table.addMouseListener(popupListener);
    public class MyTableModel extends AbstractTableModel {
    private String[] columnNames = { "ClientID", "Name", "Administrator" };
    private Vector data = new Vector();
    class Row{
         public Row(String c, String n, String a){
              clientid = c;
              name = n;
              admin = a;
         private String clientid;
         private String name;
         private String admin;
    public MyTableModel(){}
    public void removeRow(int r) {    
         data.removeElementAt(r);
         fireTableChanged(null);
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
         return "";
    public boolean isCellEditable(int row, int col) {   
    return false;
    public void setValueAt(Object value, int row, int col) {}
    }

    Inside your table model you use a Vector to hold your data. Create a method on your table model
    public void removeRow(int rowIndex)
        data.remove(rowIndex); // Remove the row from the vector
        fireTableRowDeleted(rowIndex, rowIndex); // Inform the table that the rwo has gone
    [/data]
    In the class that from which you wish to call the above you will need to add a reference to your table model.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • What's wrong with my code for comparing date retreived from db and sysdate?

    Hi all,
    I need to retrive date from the DB and compare it to system date.i have posted the code below.i get java.sql.SQL Exception:Io exception:Socket closed.
    What's wrong with the code?please help me.Thanks in advance.
    public boolean date() throws IOException, SQLException {
    Connection con1;
    long millis = System.currentTimeMillis();
    Timestamp timestamp = new java.sql.Timestamp(millis);
    ResultSet rs4 = null;
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection(
    "jdbc:oracle:thin:@abc:1605:xyz",
    "cdf", "cdf");
    Statement stmt_exp = con.createStatement();
    rs4 = stmt_exp.executeQuery("SELECT DATE FROM TABLE_NAME")
    while (rs4.next()) {
    Timestamp timestamp2 = rs4.getTimestamp("expire_date");
    con1.close();
    catch (Exception e)
    e.printStackTrace();
    finally
    //ResultSet rs4 = null;
    //Timestamp timestamp2;
    Timestamp timestamp2 = rs4.getTimestamp("expire_date");
    if (timestamp2.compareTo(timestamp) < 0)  //sysdate < exp date
    return true;
    } else {
    return false;
    }

    Didn't you understand what BalusC said? You're closing the connection and then trying to use the ResultSet. The ResultSet will be closed when you close the connection so you can't use it anymore.
    You should close the connection last thing in your code, probably in a finally. And after you close your ResultSet and Statement.
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    ----------------------------------------------------------------

  • What is wrong with this code? on(release) gotoAndPlay("2")'{'

    Please could someone tell me what is wrong with this code - on(release)
    gotoAndPlay("2")'{'
    this is the error that comes up and i have tried changing it but it is not working
    **Error** Scene=Scene 1, layer=Layer 2, frame=1:Line 2: '{' expected
         gotoAndPlay("2")'{'
    Total ActionScript Errors: 1 Reported Errors: 1
    Thanks

    If you have a frame labelled "2" then it should be:
    on (release) {
        this._parent.gotoAndPlay("2");
    or other wise just the following to go to frame 2:
    on (release) {
         this._parent.gotoAndPlay(2);
    You just had a missing curly bracket...

  • I can't figure out what's wrong with this code

    First i want this program to allow me to enter a number with the EasyReader class and depending on the number entered it will show that specific line of this peom:
    One two buckle your shoe
    Three four shut the door
    Five six pick up sticks
    Seven eight lay them straight
    Nine ten this is the end.
    The error message i got was an illegal start of expression. I can't figure out why it is giving me this error because i have if (n = 1) || (n = 2) statements. My code is:
    public class PoemSeventeen
    public static void main(String[] args)
    EasyReader console = new EasyReader();
    System.out.println("Enter a number for the poem (0 to quit): ");
    int n = console.readInt();
    if (n = 1) || (n = 2)
    System.out.println("One, two, buckle your shoe");
    else if (n = 3) || (n = 4)
    System.out.println("Three, four, shut the door");
    else if (n = 5) || (n = 6)
    System.out.println("Five, six, pick up sticks");
    else if (n = 7) || (n = 8)
    System.out.println("Seven, eight, lay them straight");
    else if (n = 9) || (n = 10)
    System.out.println("Nine, ten, this is the end");
    else if (n = 0)
    System.out.println("You may exit now");
    else
    System.out.println("Put in a number between 0 and 10");
    I messed around with a few other thing because i had some weird errors before but now i have narrowed it down to just this 1 error.
    The EasyReader class code:
    // package com.skylit.io;
    import java.io.*;
    * @author Gary Litvin
    * @version 1.2, 5/30/02
    * Written as part of
    * <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    * (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    * and
    * <i>Java Methods AB: Data Structures</i>
    * (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    * EasyReader provides simple methods for reading the console and
    * for opening and reading text files. All exceptions are handled
    * inside the class and are hidden from the user.
    * <xmp>
    * Example:
    * =======
    * EasyReader console = new EasyReader();
    * System.out.print("Enter input file name: ");
    * String fileName = console.readLine();
    * EasyReader inFile = new EasyReader(fileName);
    * if (inFile.bad())
    * System.err.println("Can't open " + fileName);
    * System.exit(1);
    * String firstLine = inFile.readLine();
    * if (!inFile.eof()) // or: if (firstLine != null)
    * System.out.println("The first line is : " + firstLine);
    * System.out.print("Enter the maximum number of integers to read: ");
    * int maxCount = console.readInt();
    * int k, count = 0;
    * while (count < maxCount && !inFile.eof())
    * k = inFile.readInt();
    * if (!inFile.eof())
    * // process or store this number
    * count++;
    * inFile.close(); // optional
    * System.out.println(count + " numbers read");
    * </xmp>
    public class EasyReader
    protected String myFileName;
    protected BufferedReader myInFile;
    protected int myErrorFlags = 0;
    protected static final int OPENERROR = 0x0001;
    protected static final int CLOSEERROR = 0x0002;
    protected static final int READERROR = 0x0004;
    protected static final int EOF = 0x0100;
    * Constructor. Prepares console (System.in) for reading
    public EasyReader()
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
    new InputStreamReader(System.in), 128);
    * Constructor. opens a file for reading
    * @param fileName the name or pathname of the file
    public EasyReader(String fileName)
    myFileName = fileName;
    myErrorFlags = 0;
    try
    myInFile = new BufferedReader(new FileReader(fileName), 1024);
    catch (FileNotFoundException e)
    myErrorFlags |= OPENERROR;
    myFileName = null;
    * Closes the file
    public void close()
    if (myFileName == null)
    return;
    try
    myInFile.close();
    catch (IOException e)
    System.err.println("Error closing " + myFileName + "\n");
    myErrorFlags |= CLOSEERROR;
    * Checks the status of the file
    * @return true if en error occurred opening or reading the file,
    * false otherwise
    public boolean bad()
    return myErrorFlags != 0;
    * Checks the EOF status of the file
    * @return true if EOF was encountered in the previous read
    * operation, false otherwise
    public boolean eof()
    return (myErrorFlags & EOF) != 0;
    private boolean ready() throws IOException
    return myFileName == null || myInFile.ready();
    * Reads the next character from a file (any character including
    * a space or a newline character).
    * @return character read or <code>null</code> character
    * (Unicode 0) if trying to read beyond the EOF
    public char readChar()
    char ch = '\u0000';
    try
    if (ready())
    ch = (char)myInFile.read();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (ch == '\u0000')
    myErrorFlags |= EOF;
    return ch;
    * Reads from the current position in the file up to and including
    * the next newline character. The newline character is thrown away
    * @return the read string (excluding the newline character) or
    * null if trying to read beyond the EOF
    public String readLine()
    String s = null;
    try
    s = myInFile.readLine();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (s == null)
    myErrorFlags |= EOF;
    return s;
    * Skips whitespace and reads the next word (a string of consecutive
    * non-whitespace characters (up to but excluding the next space,
    * newline, etc.)
    * @return the read string or null if trying to read beyond the EOF
    public String readWord()
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;
    try
    while (ready() && Character.isWhitespace(ch))
    ch = (char)myInFile.read();
    while (ready() && !Character.isWhitespace(ch))
    count++;
    buffer.append(ch);
    myInFile.mark(1);
    ch = (char)myInFile.read();
    if (count > 0)
    myInFile.reset();
    s = buffer.toString();
    else
    myErrorFlags |= EOF;
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    return s;
    * Reads the next integer (without validating its format)
    * @return the integer read or 0 if trying to read beyond the EOF
    public int readInt()
    String s = readWord();
    if (s != null)
    return Integer.parseInt(s);
    else
    return 0;
    * Reads the next double (without validating its format)
    * @return the number read or 0 if trying to read beyond the EOF
    public double readDouble()
    String s = readWord();
    if (s != null)
    return Double.parseDouble(s);
    // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
    return 0.0;
    Can anybody please tell me what's wrong with this code? Thanks

    String[] message = {
        "One, two, buckle your shoe",
        "One, two, buckle your shoe",
        "Three, four, shut the door",
        "Three, four, shut the door",
        "Five, six, pick up sticks",
        "Five, six, pick up sticks",
        "Seven, eight, lay them straight",
        "Seven, eight, lay them straight",
        "Nine, ten, this is the end",
        "Nine, ten, this is the end"
    if(n>0)
        System.out.println(message[n]);
    else
        System.exit(0);

  • JScrollPane, what is wrong with my code?

    Hi, I appreciated if you helped me(perhaps by trying it out yourself?)
    I wanted my JScrollPane to display what is drawn on my canvas (which may be large)by scrolling, but it says it doesn't need any vertical and horizontal scroll bars. Here is the code that has this effect
    import javax.swing.*;
    import java.awt.*;
    public class WhatsWrong extends JApplet{
    public void init(){
    Container appletCont = getContentPane();
    appletCont.setLayout(new BorderLayout());
    JPanel p = new JPanel();
    p.setLayout(new BorderLayout());
    p.add(new LargeCanvas(),BorderLayout.CENTER);
    int ver = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int hor = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(p,ver,hor);
    appletCont.add(jsp,BorderLayout.CENTER);
    class LargeCanvas extends Canvas{
    public LargeCanvas(){
    super();
    setBackground(Color.white);
    public void paint(Graphics g){
    g.drawRect(50,50,700,700);
    and the html code:
    <html>
    <body>
    <applet code="WhatsWrong" width = 300 height = 250>
    </applet>
    </body>
    </html>
    What shall I do?
    Thanks in advance.

    What is wrong with your code is that your class, LargeCanvas must implement the Scrollable interface in order to be scrolled by a JScrollPane.
    A comment regarding your use of Canvas and Swing components: The Java Tutorial recommends that you extend JPanel to do custom painting. Canvas is what they call a "heavyweight" component and they recommend not to mix lightweight (Swing) components and heavyweight components.
    There is a lot more information on custom painting on the Java Tutorial in the Lesson "Creating a GUI with Swing.

  • What's wrong with the code?

    public void run()
    try
    {     for(;;)
         mgr = (RTPManager)RTPManager.newInstance();
         mgr.addSessionListener(this);
         mgr.addReceiveStreamListener(this);
         try{  /*****port1 = port2 = 29261, which port is only used in here
         localAddr = new SessionAddress(InetAddress.getLocalHost(), port1);
         destAddr = new SessionAddress(ipAddr, port2);
         }catch(Exception e)
              System.out.println(e + " 4");
         try{
         mgr.initialize(localAddr);
         }catch(Exception e)
         System.out.println(e + " 5");
         //set buffer
         bc = (BufferControl)mgr.getControl("javax.media.control.BufferControl");
         if (bc != null)
         bc.setBufferLength(20);
         try{
              mgr.addTarget(destAddr);
         }catch(Exception e)
         System.out.println(e + " 2");
    catch(Exception e)
         System.out.println(e+ " 3");
    the error when i run the code is like that:
    javax.media.rtp.InvalidSessionAddressException: Can't open local data port: 29261
    5
    java.io.IOException: Address already in use: Cannot bind 2
    which means there is error in :
    mgr.initialize(localAddr);
    mgr.addTarget(destAddr);
    But i don't know what's wrong with the code,
    can any one help me?

    I do not find any problem using the same ports for local and destination address with several unicasts. My problems are others.
    But note that the error is even at constructing the localAddress, I mean before trying the destinationAddress. Thus the reason cannot be the former is already in use. In fact I think the later belongs to a remote hosts. Likely, it is trying to access the destinationAddress through the localAddress, but this has not been constructed properly.

  • [b]Does anybody know what is wrong with my code[/b]

    I cannot see what is wrong with this code but i can't get it to compile. when i try to compile it i get the
    "Exception in thread "main" java.lang.NoClassDefFoundError:
    Is this a problem with compiling or is it a code error?
    Here is my code
    public class IntCalc{
         int value;
         public IntCalc(){
              value = 0;
         public void add(int number)     {
              value = value + number;
         public void subtract(int number){
              value = value - number;
         public int getValue()     {
              return value;
    Message was edited by:
    SHIFTER

    Youd don't have a class file. Compile it first then run it. If your compiler isnt making the .class file tell me and ill give you a link to a realy good java compiler.

  • Red highlight next to code in dreamweaver. What is wrong with the code and is it affecting the websi

    What is wrong with the code and is it affecting the website?

    Line 107 looks dodgy to me and it won't have any effect on your code.  However, it is a good idea to post a complete link to your CSS for us to see it in full and to validate it using external tools.  In fact, you could validate the CSS (and HTML) yourself..
    <http://jigsaw.w3.org/css-validator/>
    Good luck.

  • I'm trying to add the system date with a Label. What is wrong with the code

    import java.util.*;
    import javax.swing.*;
    public class CurrentDateApplet extends JApplet
         Calendar currentCalendar = Calendar.getInstance();
         JLabel dateLabel = new JLabel();
         JPanel mainPanel = new JPanel();
         int dayInteger = currentCalendar.get(Calendar.DATE);
         int monthInteger = currentCalendar.get(Calendar.MONTH)+1;
         int yearInteger = currentCalendar.get(Calendar.YEAR);
         public void init()
              mainPanel.add(dateLabel);
              setContentPane(mainPanel);
              dateLabel.append(currentCalendar.get(Calendar.HOUR) + currentCalendar.get
                        (Calendar.MINUTE);
    }

    As for what's wrong with the code, it would be easier if you said: it doesn't show the date (it does this instead), it doesn't compile (I get this message) etc.
    Anyway I'll assume you want to display the time in a label...
    dateLabel.append(currentCalendar.get(Calendar.HOUR) + currentCalendar.get
    (Calendar.MINUTE);This won't compile: the parentheses are mismatched, and there is simply no such thing as append(). So we could trydateLabel.setText("" + currentCalendar.get(Calendar.HOUR) + currentCalendar.get(Calendar.MINUTE));This wroks, but looks pretty nasty and it's not how you are supposed to format dates and times. Here's the unofficial party line, nicked from one of jverd's posts:
    Calculating Java dates: Take the time to learn how to create and use dates
    Formatting a Date Using a Custom Format
    Parsing a Date Using a Custom Format
    From those links you should be able to find those applicable to times like this: http://www.exampledepot.com/egs/java.text/FormatTime.html
    Using this approach you would end up with something like:import java.text.Format;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.JApplet;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class CurrentDateApplet extends JApplet
        private Date date;
        private JLabel timeLabel;
        private JPanel mainPanel;
        public void init()
            mainPanel = new JPanel();
            timeLabel = new JLabel();
            mainPanel.add(timeLabel);
            setContentPane(mainPanel);
            date = new Date();
            Format formatter = new SimpleDateFormat("HH:ss a");
            timeLabel.setText(formatter.format(date));
    }

  • TS1702 i if use "search" in music on my ipod touch 5th gen the result just show only album and playlist but nothing song result.whats wrong with it?please help

    i if use "search" in music on my ipod touch 5th gen the result just show only album and playlist but nothing song result.whats wrong with it?please help

    The users guide says:
    Spotlight searches the following:
    Contacts—All content
    Apps—Titles
    Music—Names of songs, artists, and albums, and the titles of podcasts and videos
    Podcasts—Titles
    Videos—Titles
    Audiobooks—Titles
    Notes—Text of notes
    Calendar (Events)—Event titles, invitees, locations, and notes
    Mail—To, From, and Subject fields of all accounts (the text of messages isn’t searched)
    Reminders—Titles
    Messages—Names and text of messages
    Try:
    - Reset the iOS device. Nothing will be lost
    Reset iOS device: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Unsynce all music and resync
    - Reset all settings
    Go to Settings > General > Reset and tap Reset All Settings.
    All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
    - Restore from backup
    - Restore to factory settings/new iOS device.
    - Make an appointment at the Genius Bar of an Apple store.
    Apple Retail Store - Genius Bar

  • What's wrong with my code?

    I don't have a lot of time for explanation. Somebody please tell me what's wrong with the following code.
    import java.nio.*;
    import java.io.*;
    public class GettingAnInteger {
         public static void main(String args[]) {
              IntBuffer intBuf = new IntBuffer.allocate(10);
              int x;
              x = intBuf.get();
              System.out.print(x);
    }Thanks!!!

    Why wouldn't you include the keyword new?http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/learning/new2java/index.html
    http://javaalmanac.com
    http://www.jguru.com
    http://www.javaranch.com
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

Maybe you are looking for

  • Why can I load Image from jar?

    hi,all: I've packed all gif images into a jar file,it works well on jdk1.4.2_05 with this command: java -jar pos.jar but failed on other jdk versions lower than jdk1.4.2_05. here is the package structure: ├─resource │ ├─configfile │ └─images here is

  • IPhoto 9.6 on Yosemite

    Hi, i have a Mac Book Retina with Yosemite, i installed the 9.6 version of iPhoto but no working. the error is: Process:               iPhoto [513] Path:                  /Applications/iPhoto.app/Contents/MacOS/iPhoto Identifier:            com.apple

  • Error Log entry Unable to write file with XML Saver

    Hi all, I have just encountered the following problem. I am saving a XML file using the XML Saver. Another BLT reads the file, changes something, and saves it again with the same name. The file is saved, but the NetWeaver SAP Log gives the error "Una

  • Using CSS for portal theme

    Hi, I have 1 css file which I should use to build the EP theme. This theme will be used by all the web dynpro applications deployed on this portal. Is there any way i can use the CSS file directly rather than using the theme editor in NW developer st

  • "show ip flow top-talkers" output question

    Hello all, I have a question about the "show ip flow top-talkers" command. The top enry for this 1841 router with a T1 connection is always this line: SrcIf            SrcIPaddress    DstIf         DstIPaddress    Pr SrcP   DstP  Bytes Se0/1/0