Joptionpane in java???
Ok I am having to do a program with java using JOptionPane and I am a little losted really.
This is what I am having to do: http://www.cse.sc.edu/~huhns/csce145/homework/prog2.html
I have some of the formulas but don't know what to type in to make it read them. If anybody can help
my aim is mrjp11 and my icq is 168138609. Thanks
Here is what I have:
That is what I have so far, pretty much nothing. I have to make it echo the number i put in there and I am not sure what will do that for me. Then I have to find all the other stuff that I posted above. Any help??
* radius.java
* Created: Mon Jan 27 13:34:56 2003
* @author <a href="mailto:Jonathan@DESKTOP"></a>
* @version
*/// Java packages
import javax.swing.JOptionPane;
public class radius{
public radius() {
public static void main(String[] args)
double raduis;//in inches
double area;//in square inches
double diameter;//in inches
double circumference;//in inches
String radiusString = JOptionPane.showInputDialog("Enter the radius of your circle in inches.");
double radius;
I did that and got 2 errors, here is what i have and the errors too!!!
* radius.java
* Created: Mon Jan 27 13:34:56 2003
* @author <a href="mailto:Jonathan@DESKTOP"></a>
* @version
*/// Java packages
import javax.swing.JOptionPane;
public class radius{
public radius() {
public static void main(String[] args)
double raduis=0;//in inches
double area;//in square inches
double diameter;//in inches
double circumference;//in inches
String radiusString=null;
boolean flag=true; //controls the loop
do {
try{
radiusString = JOptionPane.showInputDialog("Enter the radius of your circle in inches.");
if(radiusString==null) System.exit(0);//if cancel is selected
radius=Double.parseDouble(radiusString);
flag=false;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog(null,"You entered "+radiusString+"\nPlease enter a positive number.");
} while(flag); //loops until a valid number is parsed
JOptionPane.showMessageDialog(null,"You entered "+radius);
} // radius
Errors:
CompileServer output:
c:/emacs-21.2/bin/radius.java
c:/emacs-21.2/bin/radius.java:32: cannot resolve symbol
symbol : variable radius
location: class radius
radius=Double.parseDouble(radiusString);
^
c:/emacs-21.2/bin/radius.java:38: cannot resolve symbol
symbol : variable radius
location: class radius
JOptionPane.showMessageDialog(null,"You entered "+radius);
^
2 errors
Compilation exited abnormally with code 1 at Mon Jan 27 23:40:15
Similar Messages
-
Similar to JOptionPane in Java
Hi,
I am new to flex and started working on it.
I would like to know if there is any APIs similar to JOptionPane in Java.
That is it creates a dialogBox with OK/Cancel Buttons or with Yes/No Button and returns value based on the button clicked and which can be used for further computations.
Regards
SriniSomething similar to Alert.
In Java, if a pop up appears, until a button is clicked , there will be no activity at the background.
But if we use Alert, then the background activity is continued even if i dont click any button.
Srini -
Using the Insert statement in a Java program without hardcoding the data
hello.
this is james mcfadden. i have developed a program called Demo.java, which is used with another program called QueryTableModel.java (a program that allows data to be viewed in a JTable). The Demo.java program displays a menu, connects to a database, allows the user to add data into the database and allows the user to view data that is already in the database. I have a problem with the Demo.java program. I have hardcoded the Insert statement in it. How do you use the Insert statement to put data into a database without hardcoding the data?
import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
import javax.swing.JOptionPane;//provides a class that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something
import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
public class Demo extends JFrame{
static String url = "jdbc:odbc:VideoLibrary";//a static variable that allows a connection to be made to a database called VideoLibrary
static Statement stmt;//a static variable that allows a statement to be made once a connection is set up
static Connection con;//a static interface that allows a connection to be made to a database
//global variables
JTextField hostField;//a class that allows a line of text to be changed
JTextField queryField;//a class that allows a line of text to be changed
QueryTableModel qtm;//a class that shows and changes regular two-dimensional tables of cells
JComboBox comboBox;//a class that puts a button or editable field and a drop-down list together
public static void main(String args[]){
int choice=-1;//a variable of type int that is set to -1
do{
choice=getChoice();//invokes the method getChoice()
if(choice!=0){
getSelected(choice);//invokes the method getSelected(choice)
}//end if
//if the user chooses 5, it will cause him or her to exit the system
}while(choice!=5);//end do-while
System.exit(0);//closes down the menu screen
}//end main
public static int getChoice(){
String choice;//a variable of type string
int ch;//a variable of type int
choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice");//asks the user for some input
ch = Integer.parseInt(choice);//a class that wraps a value of the primitive type int in an object
return ch;//a method that returns an integer value
}//end getChoice
public static void getSelected(int choice){
if(choice==1){
maintainProductDetails();//invokes the method maintainProductDetails()
}//end if
if(choice==2){
maintainMemberDetails();//invokes the method maintainMemberDetails()
}//end if
if(choice==3){
maintainRentalDetails();//invokes the method maintainRentalDetails()
}//end if
if(choice==4){
Demo test = new Demo();//invokes the constructor Demo()
test.setVisible(true);//shows the JTable component by marking it as visible
}//end if
}//end getSelected
public static Connection getConnection(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used to create a JDBC connection using a database
}//end try
catch(java.lang.ClassNotFoundException e){//causes an exception to be thrown when an application tries to load in a class through its string name
System.err.print("ClassNotFoundException: ");//displays an error message
System.err.println(e.getMessage());//returns the exception that was raised if an error occurred while attempting to load the ClassNotFoundException class
}//end catch
try {
con=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
return con;
}//end getConnection
public static void maintainProductDetails(){
Connection con = getConnection();//creates a connection with the database
String addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;//string variables that represent information about the different types of product data that will be stored in the database
addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
addProduct10 = "insert into Product values (110010, 'Pussy Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
try {
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addProduct1);
stmt.executeUpdate(addProduct2);
stmt.executeUpdate(addProduct3);
stmt.executeUpdate(addProduct4);
stmt.executeUpdate(addProduct5);
stmt.executeUpdate(addProduct6);
stmt.executeUpdate(addProduct7);
stmt.executeUpdate(addProduct8);
stmt.executeUpdate(addProduct9);
stmt.executeUpdate(addProduct10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainProductDetails
public static void maintainMemberDetails(){
Connection con = getConnection();//creates a connection with the database
String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;//string variables that represent information about the member data that will be stored in the database
addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
try{
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addMember1);
stmt.executeUpdate(addMember2);
stmt.executeUpdate(addMember3);
stmt.executeUpdate(addMember4);
stmt.executeUpdate(addMember5);
stmt.executeUpdate(addMember6);
stmt.executeUpdate(addMember7);
stmt.executeUpdate(addMember8);
stmt.executeUpdate(addMember9);
stmt.executeUpdate(addMember10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainMemberDetails
public static void maintainRentalDetails(){
Connection con = getConnection();//creates a connection with the database
String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;//string variables that represent information about the loan data that will be stored in the database
addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
try{
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addRental1);
stmt.executeUpdate(addRental2);
stmt.executeUpdate(addRental3);
stmt.executeUpdate(addRental4);
stmt.executeUpdate(addRental5);
stmt.executeUpdate(addRental6);
stmt.executeUpdate(addRental7);
stmt.executeUpdate(addRental8);
stmt.executeUpdate(addRental9);
stmt.executeUpdate(addRental10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainRentalDetails
public Demo(){//a constructor
super("Demo Test Frame");//overrides the constructor
setSize(350, 200);//Resizes this component so that it has width of 350 and height of 200
comboBox = new JComboBox();//invokes the class JComboBox
comboBox.addItem("jdbc:odbc:VideoLibrary");//adds the specified item to the end of the scrolling list
qtm = new QueryTableModel();//invokes the class QueryTableModel
JTable table = new JTable(qtm);//a class that shows and changes regular two-dimensional tables of cells
JScrollPane scrollpane = new JScrollPane(table);//a class that provides a scrollable view of a lightweight component
JPanel p1 = new JPanel();//a class that puts the combo box and query field in a panel
p1.setLayout(new GridLayout(3, 2));//Sets the layout manager for this container
p1.add(comboBox);//Appends the specified component to the end of this container
p1.add(new JLabel("Enter your query: "));//Appends the specified component to the end of this container
p1.add(queryField = new JTextField());//Appends the specified component to the end of this container
p1.add(new JLabel("Click here to send: "));//Appends the specified component to the end of this container
JButton jb = new JButton("Search");//a class that is an implementation of a "push" button
jb.addActionListener(new ActionListener(){//Adds an ActionListener to the button
public void actionPerformed(ActionEvent e){
qtm.setHostURL();//invokes the method setHostURL
qtm.setQuery(queryField.getText().trim());//invokes the method setQuery; and returns the text that is presented by this text component and returns a copy of the string, with leading and trailing whitespaces omitted
} );//end addActionListener
p1.add(jb);//Appends the specified component to the end of this container
getContentPane().add(p1, BorderLayout.NORTH);//Returns the content pane
getContentPane().add(scrollpane, BorderLayout.CENTER);//Returns the content pane
}//end Demo
}//end class Demo
import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
import java.io.*;//Provides for system input and output through data streams, serialization and the file system
import java.util.Vector;//provides a class that implements a growable array of objects
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
public class QueryTableModel extends AbstractTableModel{
Vector cache;//a class that constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
int colCount;//a variable that counts the number of columns in the three tables
String[] headers;//a class that represents character strings and all string literals in this program are implemented as instances of the String class
Connection db;//an interface that allows a connection to be made to a database
Statement statement;//an interface that allows executes the given SQL statement, which returns a single ResultSet object
String currentURL;//a variable that allows the URL to be displayed in a combo box
public QueryTableModel(){//a constructor
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used by opening a JDBC connection using an URL
}//end try
catch(Exception e){
System.out.println("problem loading the driver ");//an error message
}//end catch
}//end QueryTableModel
public String getColumnName(int i){//Returns the designated column's name
return headers;//returns the name of each column in the three table
}//end getColumnName
public int getColumnCount(){//Returns the number of columns in the column model
return colCount;//returns the number of columns in the three tables
}//end getColumnCount
public int getRowCount(){//Returns the number of rows in this table's model
return cache.size();//returns the number of components in the vector
}//end getRowCount
public Object getValueAt(int row, int col){//Returns the cell value at row and column
return ((String[])cache.elementAt(row))[col];//Returns the component at the specified index
}//end getValueAt
public void setHostURL(){//sets the URL for the database
String url = "jdbc:odbc:VideoLibrary";//a variable that allows a connection to be made to a database called VideoLibrary
closeDB();//invokes the method closeDB()
try{
db=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
}//end try
catch(Exception e){
System.out.println("Could not initialize the database.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end setHostURL
public void setQuery(String q){//sets the kind of query that is to be sent to the database
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
String s="select * from Product";//a variable that causes all the data that is in the product table to be displayed in a JTable, which also means that all the data that is in both the member and rental tables can also be displayed in a JTable
try{
ResultSet rs=statement.executeQuery(q);//an interface that is used to generate a database result set by executing a statement that queries the database
ResultSetMetaData meta=rs.getMetaData();//an interface that is used to get information about the types and properties of the columns in a ResultSet object
colCount=meta.getColumnCount();//Returns the number of columns in this ResultSet object
headers=new String[colCount];//gets the name of each column in the three tables
for(int h=1;h<=colCount;h++){
headers[h-1]=meta.getColumnName(h);//Get the designated column's name
}//end for
while(rs.next()){
String[] record=new String[colCount];//stores the name of each column in the three tables in memory
for(int i=0;i<colCount;i++){
record[i]=rs.getString(i+1);//Retrieves the value of the designated column in the current row of this ResultSet object as a String
}//end for
cache.addElement(record);//Adds the specified component to the end of this vector, increasing its size by one
}//end while
fireTableChanged(null);//Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model
}//end try
catch(Exception e){
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end setQuery
public void initDB(String url){
try{
db=DriverManager.getConnection(url);//tries to create a connection with the database using the DriverManager class
statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
}//end try
catch(Exception e){
System.out.println("Could not initialize the database.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end initDB
public void closeDB(){
try{
if(statement!=null){
statement.close();//Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed
}//end if
if(db!=null){
db.close();//Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released
}//end if
}//end try
catch(Exception e){
System.out.println("Could not close the current connection.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end closeDB
}//end class QueryTableModelhere's an uncommented version of the code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JOptionPane;
import java.sql.*;
public class Demo extends JFrame{
static String url = "jdbc:odbc:VideoLibrary";
static Statement stmt;
static Connection con;
JTextField hostField;
JTextField queryField;
QueryTableModel qtm;
JComboBox comboBox;
public static void main(String args[]){
int choice=-1;
do{
choice=getChoice();
if(choice!=0){
getSelected(choice);
}while(choice!=5);
System.exit(0);
public static int getChoice(){
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice");
ch = Integer.parseInt(choice);
return ch;
public static void getSelected(int choice){
if(choice==1){
maintainProductDetails();
if(choice==2){
maintainMemberDetails();
if(choice==3){
maintainRentalDetails();
if(choice==4){
Demo test = new Demo();
test.setVisible(true);
public static Connection getConnection(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(java.lang.ClassNotFoundException e){
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
try {
con=DriverManager.getConnection(url,"","");
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
return con;
public static void maintainProductDetails(){
Connection con = getConnection();
String addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;
addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
addProduct10 = "insert into Product values (110010, '***** Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
try {
stmt = con.createStatement();
stmt.executeUpdate(addProduct1);
stmt.executeUpdate(addProduct2);
stmt.executeUpdate(addProduct3);
stmt.executeUpdate(addProduct4);
stmt.executeUpdate(addProduct5);
stmt.executeUpdate(addProduct6);
stmt.executeUpdate(addProduct7);
stmt.executeUpdate(addProduct8);
stmt.executeUpdate(addProduct9);
stmt.executeUpdate(addProduct10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public static void maintainMemberDetails(){
Connection con = getConnection();
String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;
addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
try{
stmt = con.createStatement();
stmt.executeUpdate(addMember1);
stmt.executeUpdate(addMember2);
stmt.executeUpdate(addMember3);
stmt.executeUpdate(addMember4);
stmt.executeUpdate(addMember5);
stmt.executeUpdate(addMember6);
stmt.executeUpdate(addMember7);
stmt.executeUpdate(addMember8);
stmt.executeUpdate(addMember9);
stmt.executeUpdate(addMember10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public static void maintainRentalDetails(){
Connection con = getConnection();
String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;
addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
try{
stmt = con.createStatement();
stmt.executeUpdate(addRental1);
stmt.executeUpdate(addRental2);
stmt.executeUpdate(addRental3);
stmt.executeUpdate(addRental4);
stmt.executeUpdate(addRental5);
stmt.executeUpdate(addRental6);
stmt.executeUpdate(addRental7);
stmt.executeUpdate(addRental8);
stmt.executeUpdate(addRental9);
stmt.executeUpdate(addRental10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public Demo(){
super("Demo Test Frame");
setSize(350, 200);
comboBox = new JComboBox();
comboBox.addItem("jdbc:odbc:VideoLibrary");
qtm = new QueryTableModel();
JTable table = new JTable(qtm);
JScrollPane scrollpane = new JScrollPane(table);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3, 2));
p1.add(comboBox);
p1.add(new JLabel("Enter your query: "));
p1.add(queryField = new JTextField());
p1.add(new JLabel("Click here to send: "));
JButton jb = new JButton("Search");
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
qtm.setHostURL();
qtm.setQuery(queryField.getText().trim());
p1.add(jb);
getContentPane().add(p1, BorderLayout.NORTH);
getContentPane().add(scrollpane, BorderLayout.CENTER);
import java.sql.*;
import java.io.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
public class QueryTableModel extends AbstractTableModel{
Vector cache;
int colCount;
String[] headers;
Connection db;
Statement statement;
String currentURL;
public QueryTableModel(){
cache=new Vector();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(Exception e){
System.out.println("problem loading the driver ");
public String getColumnName(int i){
return headers;
public int getColumnCount(){
return colCount;
public int getRowCount(){
return cache.size();
public Object getValueAt(int row, int col){
return ((String[])cache.elementAt(row))[col];
public void setHostURL(){
String url = "jdbc:odbc:VideoLibrary";
closeDB();
try{
db=DriverManager.getConnection(url,"","");
statement=db.createStatement();
catch(Exception e){
System.out.println("Could not initialize the database.");
e.printStackTrace();
public void setQuery(String q){
cache=new Vector();
String s="select * from Product";
try{
ResultSet rs=statement.executeQuery(q);
ResultSetMetaData meta=rs.getMetaData();
colCount=meta.getColumnCount();
headers=new String[colCount];
for(int h=1;h<=colCount;h++){
headers[h-1]=meta.getColumnName(h);
while(rs.next()){
String[] record=new String[colCount];
for(int i=0;i<colCount;i++){
record[i]=rs.getString(i+1);
cache.addElement(record);
fireTableChanged(null);
catch(Exception e){
cache=new Vector();
e.printStackTrace();
public void initDB(String url){
try{
db=DriverManager.getConnection(url);
statement=db.createStatement();
catch(Exception e){
System.out.println("Could not initialize the database.");
e.printStackTrace();
public void closeDB(){
try{
if(statement!=null){
statement.close();
if(db!=null){
db.close();
catch(Exception e){
System.out.println("Could not close the current connection.");
e.printStackTrace(); -
A CRY OF Help..To All Java Programmer
Iam desperate please help....I Have to finish this code until tommorrow...i have done some and its running but it doesnt show the right computation...
Prob:
Mail order house sells 5 different product..prod1-$2.98, prod2-$4.50, prod3- $9.98, prod4- $4.49 and prod 5- $6.87..Write an application that reads a series of pairs of numbers as follows:
a)Product number
b)Quantity sold for one day
Program should use a switch structure to help determine the retail price for each product.Your program should calculate and display total retail value of all product sold last week. Use a TextField to obtain the product number from the user. Use sentinel -controlled loop to determine when the product should stop looping and display final results.
Note: I change temporarily the product because I am not familiar with double data types..
this is the code i have currently done..Please.please.please i need all the help..
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class ProbMod {
public static void main( String args[] )
int quant,
prodnum,
Counter,total,input,lahatna,prodquan,
gtotal;
double
average;
String
num1,
num2;
total = 0;
Counter = 0;
gtotal = 1;
input = 0;
lahatna = 0;
prodquan = 0;
num1= JOptionPane.showInputDialog( "Enter Product Number, -1 to Quit");
prodnum = Integer.parseInt(num1);
while (prodnum != -1) {
switch ( prodnum ) {
case 1:
JOptionPane.showMessageDialog(null, "1 - $2.98");
break;
case 2:
JOptionPane.showMessageDialog(null, "2 - $4.50");
break;
case 3:
JOptionPane.showMessageDialog(null, "3 - $9.98");
break;
case 4:
JOptionPane.showMessageDialog(null, "4 - $4.49");
break;
case 5:
JOptionPane.showMessageDialog(null, "5 - $6.87");
break;
default:
JOptionPane.showMessageDialog(null, "Invalid value entered" );
break;
}//end switch
num2= JOptionPane.showInputDialog( "Enter Quantity, -1 to Quit");
quant = Integer.parseInt(num2);
num1= JOptionPane.showInputDialog( "Enter Product Number, -1 to Quit");
prodnum = Integer.parseInt(num1);
if (prodnum == 1) {
input = quant * 239;
else if (prodnum == 2) {
input = quant * 129;
else if (prodnum == 3) {
input = quant * 99;
else if (prodnum == 4) {
input = quant * 350;
else if (prodnum == 5) {
input = quant * 350;
}//endif
gtotal = input + 0;
Counter = Counter + 1;
} //end while
DecimalFormat twoDigits = new DecimalFormat( "0.00");
if ( Counter != 0) {
// average = (double) total/ Counter;
lahatna = lahatna + gtotal;
JOptionPane.showMessageDialog(null, "Retail Total " + twoDigits.format( lahatna ),
"Mail Order House",JOptionPane.INFORMATION_MESSAGE );
else
JOptionPane.showMessageDialog( null,"No Product number entered", " ",JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );Hi.
I hope the class below meets your needs. Please note that I didn't spend too much time testing it and that I cannot guarantee that it works perfectly. At least it should calculate the correct results for the input values.
public class ProbMod {
public ProbMod() {
public static void main(String[] args) {
int productNumber = 0;
int soldAmount = 0;
double price = 0.0;
int counter = 0;
double total = 0.0;
do {
try {
productNumber = Integer.parseInt(JOptionPane.showInputDialog("Enter product number (-1 to quit)"));
switch( productNumber ) {
case -1:
break;
case 1:
price = 2.98;
break;
case 2:
price = 4.5;
break;
case 3:
price = 9.98;
break;
case 4:
price = 4.49;
break;
case 5:
price = 6.87;
break;
default:
JOptionPane.showMessageDialog(null, "You have entered an invalid product number. Please try again.");
throw new Exception("");
if( productNumber != -1 ) {
soldAmount = Integer.parseInt(JOptionPane.showInputDialog("Enter quantity"));
total += (double)soldAmount * price;
counter++;
} catch( NumberFormatException e1 ) {
JOptionPane.showMessageDialog(null, "You have entered a non numeric value. Please try again.");
productNumber = 0;
} catch( Exception e2 ) {
productNumber = 0;
} while( productNumber != -1 );
JOptionPane.showMessageDialog(null, "Retail total (" + String.valueOf(counter) + " product(s)): " + new DecimalFormat("0.00").format(total));
}Regards,
Kai -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
I am getting error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
Pls tell me where I am wrong:
import javax.swing.JOptionPane;
import java.io.File;
import java.io.*;
import java.io.IOException;
import java.util.*;
class Test {
String lname, fname, finalLetterGrade, LetterGrade, sub1,sub2,sub3,sub4,sub5,sub;
int testone = 0;
int a=0,b,c,d,e, count= 0, abs = 0,j;
int testtwo = 0;
int testthree = 0;
int testfour = 0;
int testfive = 0;
int finalExamGrade = 0;
int i=0;
int participation = 0;
int lowScore = 0;
int abs1,abs2,abs3,abs4,abs5;
String s="absent";
Character ch;
String []name;
int []Mark;
double finalNumericGrade = 0;
public Test() {
public void inputGrades()
int input, row, col;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the length of the square matrix: ");
col = scan.nextInt();
name = new String[col];
Mark = new int[col];
for(i = 0; i < col ; i++)
name=JOptionPane.showInputDialog("Enter Student Name"+(i+1)+" Name: ");
System.out.println(name[i]);
for(j=0; j < col;j++)
Mark[j]=Integer.parseInt(JOptionPane.showInputDialog("Marks "+(j+1)+" Mark: "));
System.out.println(Mark[j]);
System.out.println("Average-->"+getAverage());
System.out.println("Student'-->"+toString());
public double getAverage()
if( Mark[0]==0 || Mark[1]==0 || Mark[2]==0 || Mark[3]==0 || Mark[4]==0)
finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/4);
else
finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/5);;
return finalNumericGrade;
private String letterGrade(){
//System.out.println(" +++ finalNumericGrade " + finalNumericGrade );
if ((finalNumericGrade >= 3.50) & (finalNumericGrade <= 4))
finalLetterGrade = "A";
else
if ((finalNumericGrade >= 2.50) & (finalNumericGrade < 3.50))
finalLetterGrade = "B";
else
if ((finalNumericGrade >= 2) & (finalNumericGrade < 2.50))
finalLetterGrade = "C";
else
if ((finalNumericGrade >= 1) & (finalNumericGrade < 2))
finalLetterGrade = "D";
else
if (finalNumericGrade == 0)
finalLetterGrade = "X";
else finalLetterGrade ="Z";
return finalLetterGrade;
public int getAbsentee()
if(testone == 0)
abs1=1;
if(testtwo == 0)
abs2=1;
if(testthree == 0)
abs3=1;
if(testfour == 0)
abs4=1;
if(testfive == 0)
abs5=1;
return abs=abs1+abs2+abs3+abs4+abs5;
public String AbsentSub()
if((testone < testtwo) & (testone < testthree) & (testone < testfour) & (testone < testfive))
sub=sub1;
if((testtwo < testone) & (testtwo < testthree) & (testtwo < testfour) & (testtwo < testfive))
sub=sub2;
if((testthree < testone) & (testthree < testtwo) & (testthree < testfour) & (testthree < testfive))
sub=sub3;
if((testfour < testone) & (testfour < testthree) & (testfour < testtwo) & (testfour < testfive))
sub=sub4;
if((testfive < testone) & (testfive < testtwo) & (testfive < testthree) & (testfive < testfour))
sub=sub5;
return sub;
public int getLowScore(){
//Determine and return the lowest score
lowScore = testone;
if (testtwo < lowScore) lowScore = testtwo;
if (testthree < lowScore) lowScore = testthree;
if (testfour < lowScore) lowScore = testfour;
if (testfive < lowScore) lowScore = testfive;
return lowScore;
public String toString() {
String studentStringValue="\n\nStudent " sub1 " "+sub2+" "+sub3+" "+sub4+" "+sub5+ " Lowest Final Marks \n\n";
studentStringValue+= name[i]+"\t";
if(Mark[0]==0)
studentStringValue+="" s "\t";
else
a=Mark[0];
ch = new Character(((char) ((69-a))));
studentStringValue+= Mark[0]+" "+ch+ "\t";
if(Mark[1]==0)
studentStringValue+="" s "\t";
else
b=Mark[1];
ch = new Character(((char) ((69-b))));
studentStringValue+= Mark[1]+" "+ch+ "\t";
if(Mark[2]==0)
studentStringValue+="" s "\t";
else
c=Mark[2];
ch = new Character(((char) ((69-c))));
studentStringValue+=Mark[2] +" "+ch+ "\t";
if(Mark[3]==0)
studentStringValue+="" s "\t";
else
d=Mark[3];
ch = new Character(((char) ((69-d))));
studentStringValue+= Mark[3] +" "+ch+ "\t";
if(Mark[4]==0)
studentStringValue+="" s "\t";
else
e=Mark[4];
ch = new Character(((char) ((69-e))));
studentStringValue+=Mark[4] +" "+ch+ "\t";
try {
BufferedWriter out = new BufferedWriter(new FileWriter(".//Marks3.txt", true));
out.write(studentStringValue);
out.close();
} catch (IOException e) {
//studentStringValue+=" " + abs + " ";
//studentStringValue+=" " sub"\t";
studentStringValue+=" " + finalNumericGrade + " \n\n";
//studentStringValue+=" Final Letter Grade is: " + finalLetterGrade +"\n";
return studentStringValue;
}// toString
public void printName(){
System.out.print(" "+lname);
System.out.print(" "+fname);
public static void main(String[] args)
Test s = new Test();
s.inputGrades();
System.out.println("Average-->" +s.getAverage());
//System.out.println("Average-->" +s.setAverage());
//System.out.println("Absent students in each Test-->" + s.getAbsentee());
// s.getLowScore();
//System.out.println("Final Letter Grade --> " + s.letterGrade());
// s.AbsentSub();
System.out.println(""+ s.toString());hi,
I am getting error on line 232 n 339
My error is :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Test.toString(Test.java:232)
at Test.main(Test.java:339)
my code is :
import javax.swing.JOptionPane;
import java.io.File;
import java.io.*;
import java.io.IOException;
import java.util.*;
class Test {
String lname, fname, finalLetterGrade, LetterGrade, sub1,sub2,sub3,sub4,sub5,sub;
int testone = 0;
int a=0,b,c,d,e, count= 0, abs = 0,j,ab,abm=0,abj=0,abn=0,abd=0;
int testtwo = 0;
int testthree = 0;
int testfour = 0;
int testfive = 0;
int finalExamGrade = 0;
int i=0;
int participation = 0;
int lowScore = 0;
int abs1,abs2,abs3,abs4,abs5;
String s="absent";
Character ch;
String []name;
String[] subj;
int []Mark;
double finalNumericGrade = 0;
public Test() {
public void inputGrades()
int input, row, col;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the length of Array: ");
col = scan.nextInt();
name = new String[col];
subj = new String[5];
Mark = new int[5];
for(i = 0; i < col ; i++)
name=JOptionPane.showInputDialog("Enter Student Name"+(i+1)+" Name: ");
System.out.println(name[i]);
for(j=0; j < 5;j++)
subj[j]=JOptionPane.showInputDialog("Enter Subject"+(j+1)+" Name: ");
Mark[j]=Integer.parseInt(JOptionPane.showInputDialog("Marks "+(j+1)+" Mark: "));
System.out.println(subj[j]);
System.out.println(Mark[j]);
System.out.println("Student'-->"+toString());
System.out.println("Average Stu-->"+getAverage());
getLowScore();
public double getAverage()
if( Mark[0]==0 || Mark[1]==0 || Mark[2]==0 || Mark[3]==0 || Mark[4]==0)
finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/4);
else
finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/5);;
return finalNumericGrade;
private String letterGrade(){
//System.out.println(" +++ finalNumericGrade " + finalNumericGrade );
if ((finalNumericGrade >= 3.50) & (finalNumericGrade <= 4))
finalLetterGrade = "A";
else
if ((finalNumericGrade >= 2.50) & (finalNumericGrade < 3.50))
finalLetterGrade = "B";
else
if ((finalNumericGrade >= 2) & (finalNumericGrade < 2.50))
finalLetterGrade = "C";
else
if ((finalNumericGrade >= 1) & (finalNumericGrade < 2))
finalLetterGrade = "D";
else
if (finalNumericGrade == 0)
finalLetterGrade = "X";
else finalLetterGrade ="Z";
return finalLetterGrade;
/*****Java Absentee***/
public int getAbsenteeJava()
if((Mark[0]==0))
abj=abj+1;
else
abj=0;
return abj;
public void setAbsenteeJava()
System.out.println("Absent in Java-->"+abj);
/***Maths Absentee****/
public int getAbsenteeMaths()
if(Mark[1]==0)
abm=abm+1;
else
abm=0;
return abm;
public void setAbsenteeMaths()
System.out.println("Absent in Maths-->"+abm);
/****Stats Absentee---*/
public int getAbsenteeStat()
sub3="Stats";
if(Mark[2]==0)
abs=abs+1;
else
abs=0;
return abs;
public void setAbsenteeStat()
System.out.println("Absent in Stats-->"+abs);
/*****NEt Absentee****/
public int getAbsenteeNet()
sub4="Network";
if(Mark[3]==0)
abn=abn+1;
else
abn=0;
return abn;
public void setAbsenteeNet()
System.out.println("Absent in Network-->"+abn);
/*****Database Absentee****/
public int getAbsenteeData()
sub5="Database";
if(Mark[4]==0)
abd=abd+1;
else
abd=0;
return abd;
public void setAbsenteeData()
System.out.println("Absent in Database-->"+abd);
public String getLowScore(){
//Determine and return the lowest score
if(((subj[0].equals(sub1)) || (Mark[0]==0)))
sub="Java";
else if(((subj[1].equals(sub2)) || (Mark[1]==0)))
sub="Maths";
else if(((subj[2].equals(sub3)) & (Mark[2]==0)))
sub="Stats";
else if(((subj[3].equals(sub4)) || (Mark[3]==0)))
sub="Network";
else if(((subj[4].equals(sub5)) || (Mark[4]==0)))
sub="Database";
return sub;
public String toString() {
String studentStringValue="\n\nStudent " subj[0] " "+subj[1]+" "+subj[2]+" "+subj[3]+" "+subj[4]+ " Lowest Final Marks \n\n";
String nm = name[i];
studentStringValue+= nm+"\t";
if(Mark[0]==0)
studentStringValue+="" s "\t";
else
{// 232: Line: getting ERROR here
a=Mark[0];
ch = new Character(((char) ((69-a))));
studentStringValue+= Mark[0]+" "+ch+ "\t";
if(Mark[1]==0)
studentStringValue+="" s "\t";
else
b=Mark[1];
ch = new Character(((char) ((69-b))));
studentStringValue+= Mark[1]+" "+ch+ "\t";
if(Mark[2]==0)
studentStringValue+="" s "\t";
else
c=Mark[2];
ch = new Character(((char) ((69-c))));
studentStringValue+=Mark[2] +" "+ch+ "\t";
if(Mark[3]==0)
studentStringValue+="" s "\t";
else
d=Mark[3];
ch = new Character(((char) ((69-d))));
studentStringValue+= Mark[3] +" "+ch+ "\t";
if(Mark[4]==0)
studentStringValue+="" s "\t";
else
e=Mark[4];
ch = new Character(((char) ((69-e))));
studentStringValue+=Mark[4] +" "+ch+ "\t";
//studentStringValue+=" " + abs + " ";
studentStringValue+=" " sub"\t";
studentStringValue+=" " + finalNumericGrade + " \n\n";
//studentStringValue+=" Final Letter Grade is: " + finalLetterGrade +"\n";
try {
BufferedWriter out = new BufferedWriter(new FileWriter(".//Marks3.txt", true));
out.write(studentStringValue);
out.close();
} catch (IOException e) {
return studentStringValue;
}// toString
public void printName(){
System.out.print(" "+lname);
System.out.print(" "+fname);
public static void main(String[] args)
Test s = new Test();
s.inputGrades();
System.out.println("Average-->" +s.getAverage());
//System.out.println("Average-->" +s.setAverage());
s.getAbsenteeJava();
s.setAbsenteeJava();
s.getAbsenteeMaths();
s.setAbsenteeMaths();
s.getAbsenteeStat();
s.setAbsenteeStat();
s.getAbsenteeNet();
s.setAbsenteeNet();
s.getAbsenteeData();
s.setAbsenteeData();
s.getLowScore();
//System.out.println("Final Letter Grade --> " + s.letterGrade());
System.out.println(""+ s.toString()); -
URGENT!! all the JAVA EXPERTS plssss help me!!
thanks for replying me....i m actually doing a coursework that i have to submit by next monday 29/4/2002. and i havent finish it yet.... ok .. finally i have finish level 1, now i m doing level two...
my program in level 2 should :
a.) Allow the user to specify certain criteria for a room that they wish to book on a particular day. e.g. X number of people, video conferencing, your program should find an appropriate room for them that is free on that day.
b.) Allow the user to add more rooms to the system and make these available to the user to book.
c.) Allow a user to attempt to delete a room. The room will only be deleted if it has no bookings.
d.) Allow the user to ask the system to find the minimum fit room free e.g.
* the smallest room to hold X people that has a connection to the internet.
* if the user requests a room for 40 people and there are rooms free for 50 and 60 people, then
it will allocate them the room for 50.
i really donno how to do....pls help me....
there is something wrong in the METHOD --> AddDeleteRoom()
and i donno how to code the AddNewRoom()
i need to add more rooms into my array
u can download these coding .....i got three files, 1 is the main class call CC.java, another 1 is the class filewhich is Rooms.java and the third file is CC.html file.
dont worry, u can save all the coding in here.... i try b4 it can run.....
<<save as CC.java>>
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JApplet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JOptionPane;
public class CC extends JApplet implements ActionListener,ItemListener
JPanel pnlPane = new JPanel();
JPanel pnlChoise = new JPanel();
JPanel pnlButton2 = new JPanel();
JPanel pnlRoomDisplay = new JPanel();
JPanel pnlRoom = new JPanel();
JPanel pnlDisplay = new JPanel();
JPanel pnlClear = new JPanel();
JButton btnDisplay = new JButton("Display");
JButton btnBookRoom = new JButton("Book Room");
JButton btnDelBookRoom = new JButton("Delete Booking");
JButton btnDelRoom = new JButton("Delete Room");
JButton btnAddNewRoom = new JButton("Add New Room");
JButton btnClear = new JButton("Clear");
JButton btnRoomQuery = new JButton("Room Query");
Rooms []room = new Rooms[11];
String[] Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
int [][] book = new int[11][7];
public int R, D;
JLabel lblRoomName = new JLabel();
JLabel lblCapacity = new JLabel();
JLabel lblInternet = new JLabel();
JLabel lblVideo = new JLabel();
JLabel lblStatus = new JLabel();
JComboBox cDays= new JComboBox(Days);
JComboBox cRooms = new JComboBox();
JTextField txtRoomName1 = new JTextField();
JTextField txtCapacity1 = new JTextField();
JCheckBox chkInternet = new JCheckBox("Internet Connection");
JCheckBox chkVideo = new JCheckBox("Video Conferencing");
JTextArea txtDisplay = new JTextArea("*****Rooms Detail*****" + "\n",12,30);
public void init()
pnlPane.add(pnlChoise);
pnlPane.add(pnlButton2);
pnlPane.add(pnlRoomDisplay);
pnlPane.add(pnlRoom);
pnlPane.add(pnlDisplay);
pnlPane.add(pnlClear);
pnlPane.setBorder(new TitledBorder(new BevelBorder(BevelBorder.RAISED),"Room Booking System"));
setContentPane(pnlPane);
AddChoisePanel();
AddButton2Panel();
AddRoomDisplayPanel();
AddRoomPanel();
AddDisplayAreaPanel();
AddClearPanel();
public void AddChoisePanel()
pnlChoise.setLayout(new GridLayout(1,3,5,5));
room[0]=new Rooms("Barrington","15","No","Yes");
room[1]=new Rooms("Carlton","25","Yes","No");
room[2]=new Rooms("Debyshire","35","No","No");
room[3]=new Rooms("Edwards","30","Yes","Yes");
room[4]=new Rooms("Farley","70","Yes","No");
room[5]=new Rooms("Goodwin","80","Yes","Yes");
room[6]=new Rooms("Harlow","90","No","Yes");
room[7]=new Rooms("IlFord","85","No","No");
for (int i=0; i<8; i++)
cRooms.addItem(room.rName);
pnlChoise.add(cRooms);
pnlChoise.add(cDays);
pnlChoise.add(btnRoomQuery);
btnRoomQuery.addActionListener(this);
cRooms.addItemListener(this);
public void AddButton2Panel()
pnlButton2.setLayout(new GridLayout(1,2,5,5));
pnlButton2.add(btnBookRoom);
pnlButton2.add(btnDelBookRoom);
btnDelBookRoom.addActionListener(this);
btnBookRoom.addActionListener(this);
public void AddRoomDisplayPanel()
pnlRoomDisplay.setLayout(new GridLayout(6,2,5,2));
pnlRoomDisplay.add(new JLabel("Room Name" ));
pnlRoomDisplay.add(lblRoomName);
pnlRoomDisplay.add(new JLabel("Room Capacity"));
pnlRoomDisplay.add(lblCapacity);
pnlRoomDisplay.add(new JLabel("Internet Connection"));
pnlRoomDisplay.add(lblInternet);
pnlRoomDisplay.add(new JLabel("Video Conferencing"));
pnlRoomDisplay.add(lblVideo);
pnlRoomDisplay.add(new JLabel("Room Status"));
pnlRoomDisplay.add(lblStatus);
pnlRoomDisplay.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED),"Rooms Detail"));
pnlRoomDisplay.add(btnDelRoom);
btnDelRoom.addActionListener(this);
public void AddRoomPanel()
pnlRoom.setLayout(new GridLayout(6,2,2,2));
pnlRoom.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED),"Add New Rooms"));
pnlRoom.add(new Label("Room Name"));
pnlRoom.add(txtRoomName1);
pnlRoom.add(new Label("Capacity"));
pnlRoom.add(txtCapacity1);
pnlRoom.add(chkInternet);
pnlRoom.add(new Label(""));
pnlRoom.add(chkVideo);
pnlRoom.add(new Label(""));
pnlRoom.add(new Label(""));
pnlRoom.add(new Label(""));
pnlRoom.add(btnAddNewRoom);
btnAddNewRoom.addActionListener(this);
public void AddDisplayAreaPanel()
pnlDisplay.setLayout(new GridLayout(1,1));
//pnlDisplay.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED),"Rooms Detail"));
Border pnlDisplayBorder = BorderFactory.createTitledBorder("Rooms Detail");
pnlDisplay.setBorder(pnlDisplayBorder);
pnlDisplay.add(txtDisplay);
public void AddClearPanel()
pnlClear.setLayout(new GridLayout(1,1));
pnlClear.add(btnClear);
btnClear.addActionListener(this);
public void actionPerformed(ActionEvent event)
//to call RoomQuery function
if (event.getSource() == btnRoomQuery){
AddRoomQuery(); }
else
//to call DeleteBookRoom function
if (event.getSource() == btnDelBookRoom){
AddDeleteBookRoom(); }
else
//to call DeleteRoom function
if (event.getSource() == btnDelRoom){
AddDeleteRoom(); }
else
//to call AddNewRoom function
if (event.getSource() == btnAddNewRoom){
AddNewRoom(); }
else
//to call ClearTextArea function
if (event.getSource() == btnClear){
AddClearTextArea(); }
else
//to call BookRoom function
if (event.getSource() == btnBookRoom){
AddBookRoom(); }
public void AddRoomQuery()
R= (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
JOptionPane.showMessageDialog(null, R + " " + D);
txtDisplay.setText(" *************** Room Status For "+ Days[D] + " *************** " + "\n");
txtDisplay.append("Rooms" + "\t\t " + " Status");
for (int t=0; t< (int) cRooms.getItemCount(); t++)
{ JOptionPane.showMessageDialog(null," is" + cRooms.getItemCount());
if (book[t][D]==0)
txtDisplay.append("\n" + ">>" + room[t].rName);
txtDisplay.append("\t\t " + " Room is Available");
else
if (book[t][D]==1)
txtDisplay.append("\n" + ">>" + room[t].rName);
txtDisplay.append("\t\t " + " Room Booked");
JOptionPane.showMessageDialog(null, "end " );
public void AddDeleteBookRoom()
R = (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
if(book[R][D] == 1)
txtDisplay.setText("*****Rooms Detail*****" + "\n" + "Room is Available" + "\n");
book[R][D] = 0;
else
txtDisplay.setText("*****Rooms Detail*****" + "\n" + "Room Available"+ "\n");
book[R][D] = 0;
public void AddDeleteRoom()
R = (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
JOptionPane.showMessageDialog(null,"Room selected index " + R);
int intCount =(int) cRooms.getSelectedIndex();
if (intCount != -1)
if(book[R][D] == 0 )
JOptionPane.showMessageDialog(null,"Room "+room[intCount].rName + " had Deleted");
cRooms.removeItemAt(intCount);
int i;
for( i=intCount;i< cRooms.getItemCount();i++)
JOptionPane.showMessageDialog(null,"Room "+room[i+1].rName + "to");
room[i]=new Rooms(room[i+1]);
JOptionPane.showMessageDialog(null,"Room "+ room[i].rName );
//cRooms.getSelectedIndex());
// intCount--;
else
if(book[R][D] == 1 )
JOptionPane.showMessageDialog(null,"Room "+room[intCount].rName+" Can Not be Delete");
else
JOptionPane.showMessageDialog(null,"Select A Room To be Delete ");
public void AddNewRoom()
JOptionPane.showMessageDialog(null,"Add new room");
public void AddClearTextArea()
txtDisplay.setText("*****Rooms Detail*****" + "\n");
public void AddBookRoom()
R= (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
if(book[R][D] == 0)
txtDisplay.setText("*****Rooms Detail*****" + "\n" + "Room is Booked" + "\n");
book[R][D] = 1;
else
txtDisplay.setText("*****Rooms Detail*****" + "\n" + "Room Not Available"+ "\n");
book[R][D] = 1;
public void itemStateChanged(ItemEvent itv)
if( itv.getSource() == cRooms )
R = (int) cRooms.getSelectedIndex();
lblRoomName.setText(room[R].rName);
lblCapacity.setText(room[R].rCapacity);
lblInternet.setText(room[R].rInternet);
lblVideo.setText(room[R].rVideo);
// lblStatus.setText(room[R].rStatus);
<<save as Rooms.java>>
public class Rooms
String rName;
String rCapacity;
String rInternet;
String rVideo;
// String rStatus;
Rooms(String a, String b, String c, String d)//, String e)
rName = a;
rCapacity = b;
rInternet = c;
rVideo = d;
// rStatus = e;
Rooms(Rooms r)
rName = r.rName;
rCapacity = r.rCapacity;
rInternet = r.rInternet;
rVideo = r.rVideo;
// rStatus = r.e;
<<saves as CC.html>>
<html>
<body>
<Applet code = CC.class
width = 600
height = 510>
</Applet>
</body>
</html>The important thing is to put the related functionality in the class Room and not everywhere in the class CC.
The types of the data member in the class Room are also very important to reflect exactly what they should store.
Here I post a new version of your files as example of how we can improve your version. It does not implement all the functionality you will need but it is a first step.
Serge
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JApplet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JOptionPane;
import java.util.LinkedList;
public class CC extends JApplet implements ActionListener, ItemListener {
JPanel pnlPane = new JPanel();
JPanel pnlChoise = new JPanel();
JPanel pnlButton2 = new JPanel();
JPanel pnlRoomDisplay = new JPanel();
JPanel pnlRoom = new JPanel();
JPanel pnlDisplay = new JPanel();
JPanel pnlClear = new JPanel();
JButton btnDisplay = new JButton("Display");
JButton btnBookRoom = new JButton("Book Room");
JButton btnDelBookRoom = new JButton("Delete Booking");
JButton btnDelRoom = new JButton("Delete Room");
JButton btnAddNewRoom = new JButton("Add New Room");
JButton btnClear = new JButton("Clear");
JButton btnRoomQuery = new JButton("Room Query");
LinkedList roomList = new LinkedList();
String[] Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
public int R, D;
JLabel lblRoomName = new JLabel();
JLabel lblCapacity = new JLabel();
JLabel lblInternet = new JLabel();
JLabel lblVideo = new JLabel();
JLabel lblStatus = new JLabel();
JComboBox cDays = new JComboBox(Days);
JComboBox cRooms = new JComboBox();
JTextField txtRoomName1 = new JTextField();
JTextField txtCapacity1 = new JTextField();
JCheckBox chkInternet = new JCheckBox("Internet Connection");
JCheckBox chkVideo = new JCheckBox("Video Conferencing");
JTextArea txtDisplay = new JTextArea("*****Rooms Detail*****" + "\n", 12, 30);
public void init() {
pnlPane.add(pnlChoise);
pnlPane.add(pnlButton2);
pnlPane.add(pnlRoomDisplay);
pnlPane.add(pnlRoom);
pnlPane.add(pnlDisplay);
pnlPane.add(pnlClear);
pnlPane.setBorder(new TitledBorder(new BevelBorder(BevelBorder.RAISED), "Room Booking System"));
setContentPane(pnlPane);
AddChoisePanel();
AddButton2Panel();
AddRoomDisplayPanel();
AddRoomPanel();
AddDisplayAreaPanel();
AddClearPanel();
public void AddChoisePanel() {
pnlChoise.setLayout(new GridLayout(1, 3, 5, 5));
Room[]room = new Room[8];
room[0] = new Room("Barrington", "15", false, true);
room[1] = new Room("Carlton", "25", true, false);
room[2] = new Room("Debyshire", "35", false, false);
room[3] = new Room("Edwards", "30", true, true);
room[4] = new Room("Farley", "70", true, false);
room[5] = new Room("Goodwin", "80", true, true);
room[6] = new Room("Harlow", "90", false, true);
room[7] = new Room("IlFord", "85", false, false);
for (int i = 0; i < 8; i++) {
cRooms.addItem(room.getName());
roomList.add(room[i]);
pnlChoise.add(cRooms);
pnlChoise.add(cDays);
pnlChoise.add(btnRoomQuery);
btnRoomQuery.addActionListener(this);
cRooms.addItemListener(this);
public void AddButton2Panel() {
pnlButton2.setLayout(new GridLayout(1, 2, 5, 5));
pnlButton2.add(btnBookRoom);
pnlButton2.add(btnDelBookRoom);
btnDelBookRoom.addActionListener(this);
btnBookRoom.addActionListener(this);
public void AddRoomDisplayPanel() {
pnlRoomDisplay.setLayout(new GridLayout(6, 2, 5, 2));
pnlRoomDisplay.add(new JLabel("Room Name"));
pnlRoomDisplay.add(lblRoomName);
pnlRoomDisplay.add(new JLabel("Room Capacity"));
pnlRoomDisplay.add(lblCapacity);
pnlRoomDisplay.add(new JLabel("Internet Connection"));
pnlRoomDisplay.add(lblInternet);
pnlRoomDisplay.add(new JLabel("Video Conferencing"));
pnlRoomDisplay.add(lblVideo);
pnlRoomDisplay.add(new JLabel("Room Status"));
pnlRoomDisplay.add(lblStatus);
pnlRoomDisplay.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED), "Rooms Detail"));
pnlRoomDisplay.add(btnDelRoom);
btnDelRoom.addActionListener(this);
public void AddRoomPanel() {
pnlRoom.setLayout(new GridLayout(6, 2, 2, 2));
pnlRoom.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED), "Add New Rooms"));
pnlRoom.add(new Label("Room Name"));
pnlRoom.add(txtRoomName1);
pnlRoom.add(new Label("Capacity"));
pnlRoom.add(txtCapacity1);
pnlRoom.add(chkInternet);
pnlRoom.add(new Label(""));
pnlRoom.add(chkVideo);
pnlRoom.add(new Label(""));
pnlRoom.add(new Label(""));
pnlRoom.add(new Label(""));
pnlRoom.add(btnAddNewRoom);
btnAddNewRoom.addActionListener(this);
public void AddDisplayAreaPanel() {
pnlDisplay.setLayout(new GridLayout(1, 1));
//pnlDisplay.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED),"Rooms Detail"));
Border pnlDisplayBorder = BorderFactory.createTitledBorder("Rooms Detail");
pnlDisplay.setBorder(pnlDisplayBorder);
pnlDisplay.add(txtDisplay);
public void AddClearPanel() {
pnlClear.setLayout(new GridLayout(1, 1));
pnlClear.add(btnClear);
btnClear.addActionListener(this);
public void actionPerformed(ActionEvent event) {
//to call RoomQuery function
if (event.getSource() == btnRoomQuery) {
AddRoomQuery();
} else {
//to call DeleteBookRoom function
if (event.getSource() == btnDelBookRoom) {
AddDeleteBookRoom();
} else {
//to call DeleteRoom function
if (event.getSource() == btnDelRoom) {
AddDeleteRoom();
} else {
//to call AddNewRoom function
if (event.getSource() == btnAddNewRoom) {
AddNewRoom();
} else {
//to call ClearTextArea function
if (event.getSource() == btnClear) {
AddClearTextArea();
} else {
//to call BookRoom function
if (event.getSource() == btnBookRoom) {
AddBookRoom();
public void AddRoomQuery() {
R = (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
// JOptionPane.showMessageDialog(null, R + " " + D);
txtDisplay.setText(" *************** Room Status For " + Days[D] + " *************** " + "\n");
txtDisplay.append("Rooms" + "\t\t " + " Status");
Room aRoom = (Room)roomList.get(R);
for (int t = 0; t < (int) cRooms.getItemCount(); t++) {
// JOptionPane.showMessageDialog(null, " is" + cRooms.getItemCount());
aRoom = (Room)roomList.get(t);
txtDisplay.append("\n" + ">>" + aRoom.getName());
if (aRoom.isBooked(D)) {
txtDisplay.append("\t\t " + " Room Booked");
} else {
txtDisplay.append("\t\t " + " Room is Available");
// JOptionPane.showMessageDialog(null, "end ");
public void AddDeleteBookRoom() {
R = (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
Room aRoom = (Room)roomList.get(R);
aRoom.checkOut(D);
txtDisplay.setText("*****Rooms Detail*****" + "\n" + "Room is Available" + "\n");
public void AddDeleteRoom() {
R = (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
// JOptionPane.showMessageDialog(null, "Room selected index " + R);
int intCount = (int) cRooms.getSelectedIndex();
Room aRoom = (Room)roomList.get(R);
if (intCount != -1) {
if (aRoom.isBooked() == false) {
JOptionPane.showMessageDialog(null, "Room " + ((Room)roomList.get(intCount)).getName() + " had Deleted");
cRooms.removeItemAt(intCount);
roomList.remove(intCount);
} else {
JOptionPane.showMessageDialog(null, "Room " + ((Room)roomList.get(intCount)).getName() + " Can Not be Delete");
} else {
JOptionPane.showMessageDialog(null, "Select A Room To be Delete ");
public void AddNewRoom() {
String rName = txtRoomName1.getText();
String rCapacity = txtCapacity1.getText();
boolean rInternet = chkInternet.isSelected();
boolean rVideo = chkVideo.isSelected();
Room nRoom = new Room(rName,rCapacity,rInternet,rVideo);
cRooms.addItem(rName);
int i = cRooms.getItemCount();
roomList.add(nRoom);
public void AddClearTextArea() {
txtDisplay.setText("*****Rooms Detail*****" + "\n");
public void AddBookRoom() {
R = (int) cRooms.getSelectedIndex();
D = (int) cDays.getSelectedIndex();
Room aRoom = (Room)roomList.get(R);
if (aRoom.reserve(D) == 0) {
txtDisplay.setText("*****Rooms Detail*****" + "\n" + "Room is Booked" + "\n");
} else {
txtDisplay.setText("*****Rooms Detail*****" + "\n" + "Room Not Available" + "\n");
public void itemStateChanged(ItemEvent itv) {
if (itv.getSource() == cRooms) {
R = (int) cRooms.getSelectedIndex();
Room aRoom = (Room)roomList.get(R);
lblRoomName.setText(aRoom.getName());
lblCapacity.setText(String.valueOf(aRoom.getCapacity()));
lblInternet.setText(aRoom.getInternet());
lblVideo.setText(aRoom.getVideo());
// lblStatus.setText(aRoom.rStatus);
public class Room {
public final String YES = "Yes";
public final String NO = "No";
private String rName = null;
private int rCapacity = 0;
private boolean rInternet = false;
private boolean rVideo = false;
private boolean [] booked = { false, false, false, false, false, false, false };
Room(String name, String capacity, boolean hasInternet, boolean hasVideo)
rName = new String(name);
rCapacity = Integer.parseInt(capacity);
rInternet = hasInternet;
rVideo = hasVideo;
public int reserve(int day) {
if (booked[day] == true)
return -1;
booked[day] = true;
return 0;
public void checkOut(int day) {
booked[day] = false;
public boolean isBooked() {
for (int i = 0; i < booked.length; i++)
if (booked[i] == true)
return true;
return false;
public boolean isBooked(int day) {
return booked[day];
public String getName() {
return rName;
public int getCapacity() {
return rCapacity;
public String getInternet() {
if (rInternet == false)
return NO;
return YES;
public String getVideo() {
if (rVideo == false)
return NO;
return YES;
public boolean matchCriterias(boolean hasInternet, boolean hasVideo) {
if ((hasInternet == rInternet) && (hasVideo == rVideo))
return true;
return false; -
JTable - isEditing does not work in Java 1.4
I just upgraded jdk1.1.8 with swing 1.1.1 to Java1.4. The isEditing method doesn't work on Java1.4. When I edit a cell in the JTable and click a button , the value of the last edited cell is lost. I was able to catch the edited value by calling isEditing in jdk1.1.8 but Java 1.4 does not detect that the cell was edited. Is this a bug? Has anyone experience this problem? Is there a work around solution? Please help!!!
Hi,
Below is the code that I modified from a sample code in Java Tutorial. I added an OK button. The isEditing method does not trap the edit the first time but does on the second edit in JDK1.4. However, it works in JDK1.1.8. Am I doing something wrong or is this a bug? I desperately have to solve this problem to upgrade to JDK1.4. Thank-you for your help! I really appreciate it!
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableDemo extends JFrame {
private boolean DEBUG = true;
private JPanel buttonPanel;
private JTable table;
public TableDemo() {
super("TableDemo");
MyTableModel myModel = new MyTableModel();
table = new JTable(myModel);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this window.
getContentPane().add(scrollPane, BorderLayout.CENTER);
// create OK, Reset, and Cancel buttons
createButtons();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
class MyTableModel extends AbstractTableModel {
final String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
final Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Chasing toddlers", new Integer(2), new Boolean(false)},
{"Mark", "Andrews",
"Speed reading", new Integer(20), new Boolean(true)},
{"Angela", "Lih",
"Teaching high school", new Integer(4), new Boolean(false)}
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
return true;
* Don't need to implement this method unless your table's
* data can change.
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
if (data[0][col] instanceof Integer
&& !(value instanceof Integer)) {
//With JFC/Swing 1.1 and JDK 1.2, we need to create
//an Integer from the value; otherwise, the column
//switches to contain Strings. Starting with v 1.3,
//the table automatically converts value to an Integer,
//so you only need the code in the 'else' part of this
//'if' block.
//XXX: See TableEditDemo.java for a better solution!!!
try {
data[row][col] = new Integer(value.toString());
fireTableCellUpdated(row, col);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(TableDemo.this,
"The \"" + getColumnName(col)
+ "\" column accepts only integer values.");
} else {
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
System.out.println();
System.out.println("--------------------------");
private void createButtons() {
// create panel to hold buttons
buttonPanel = new JPanel();
JButton buttonOK = new JButton("OK");
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// detect if a value was edited when OK was pressed without entering
// return or changing focus
if (table.isEditing()) {
System.out.println("****** Table is edited ******");
// value was edited when OK was pressed without entering return
// or changing focus
int row = table.getEditingRow();
int column = table.getEditingColumn();
System.out.println("row: " + row + ", column: " + column + " is edited");
buttonPanel.add(buttonOK);
public static void main(String[] args) {
TableDemo frame = new TableDemo();
frame.pack();
frame.setVisible(true); -
Having an issue with event handling - sql & java
HI all am trying to construct this hybrid of java and mysql. the data comes from a mysql database and I want it to display in the gui. this I have achieved thus far. However I have buttons that sort by surname, first name, ID tag etc....I need event handlers for these buttons but am quite unsure as to how to do it. any help would be much appreciated. Thanks in advance.
/* Student Contact Database GUI
* Phillip Wells
import java.awt.BorderLayout;
// imports java class. All import class statements tell the compiler to use a class that is defined in the Java API.
// Borderlayout is a layout manager that assists GUI layout.
import javax.swing.*; // imports java class. Swing enables the use of a GUI.
import javax.swing.JOptionPane; // imports java class. JOptionPane displays messages in a dialog box as opposed to a console window.
import javax.swing.JPanel; // imports java class. A component of a GUI.
import javax.swing.JFrame; // imports java class. A component of a GUI.
import javax.swing.JButton; // imports java class. A component of a GUI.
import javax.swing.JScrollPane; // imports java class. A component of a GUI.
import javax.swing.JTable; // imports java class. A component of a GUI.
import java.awt.*; // imports java class. Similar to Swing but with different components and functions.
import java.awt.event.*; // imports java class. Deals with events.
import java.awt.event.ActionEvent; // imports java class. Deals with events.
import java.awt.event.ActionListener; // imports java class. Deals with events.
import java.sql.*; // imports java class. Provides API for accessing and processing data stored in a data source.
import java.util.*; // imports java class. Contains miscellaneous utility classes such as strings.
public class studentContact extends JFrame { // public class declaration. The �public� statement enables class availability to other java elements.
private JPanel jContentPane; // initialises content pane
private JButton snam, id, fname, exit; // initialises Jbuttons
String firstname = "firstname"; //initialises String firstname
String secondname = "secondname"; //initialises String
public studentContact() {
Vector columnNames = new Vector(); // creates new vector object. Vectors are arrays that are expandable.
Vector data = new Vector();
initialize();
try {
// Connect to the Database
String driver = "com.mysql.jdbc.Driver"; // connect to JDBC driver
String url = "jdbc:mysql://localhost/Studentprofiles"; //location of Database
String userid = "root"; //user logon information for MySQL server
String password = ""; //logon password for above
Class.forName(driver); //reference to JDBC connector
Connection connection = DriverManager.getConnection(url, userid,
password); // initiates connection
// Read data from a table
String sql = "Select * from studentprofile order by "+ firstname;
//SQL query sent to database, orders results by firstname.
Statement stmt = connection.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//statement to create connection.
//Scroll sensitive allows movement forth and back through results.
//Concur updatable allows updating of database.
ResultSet rs = stmt.executeQuery(sql); // executes SQL query stated above and sets the results in a table
ResultSetMetaData md = rs.getMetaData(); // used to get the properties of the columns in a ResultSet object.
int columns = md.getColumnCount(); //
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i)); // Get column names
while (rs.next()) {
Vector row = new Vector(columns); // vectors data from table
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i)); // Get row data
data.addElement(row); // adds row data
rs.close();
stmt.close();
} catch (Exception e) { // catches exceptions
System.out.println(e); // prints exception message
JTable table = new JTable(data, columnNames) { //constructs JTable
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
return Object.class;
JScrollPane scrollPane = new JScrollPane( table ); // constructs scrollpane 'table'
getContentPane().add(new JScrollPane(table), BorderLayout.SOUTH); //adds table to a scrollpane
private void initialize() {
this.setContentPane(getJContentPane());
this.setTitle("Student Contact Database"); // sets title of table
ButtonListener b1 = new ButtonListener(); // constructs button listener
snam = new JButton ("Sort by surname"); // constructs Jbutton
snam.addActionListener(b1); // adds action listener
jContentPane.add(snam); //adds button to pane
id = new JButton ("Sort by ID"); // constructs Jbutton
id.addActionListener(b1); // adds action listener
jContentPane.add(id); //adds button to pane
fname = new JButton ("Sort by first name"); // constructs Jbutton
fname.addActionListener(b1); // adds action listener
jContentPane.add(fname); //adds button to pane
exit = new JButton ("Exit"); // constructs Jbutton
exit.addActionListener(b1); // adds action listener
jContentPane.add(exit); //adds button to pane
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel(); // constructs new panel
jContentPane.setLayout(new FlowLayout()); // sets new layout manager
return jContentPane; // returns Jcontentpane
private class ButtonListener implements ActionListener { // create inner class button listener that uses action listener
public void actionPerformed (ActionEvent e)
if (e.getSource () == exit) // adds listener to button exit.
System.exit(0); // exits the GUI
if (e.getSource () == snam)
if (e.getSource () == id)
if (e.getSource () == fname)
public static void main(String[] args) { // declaration of main method
studentContact frame = new studentContact(); // constructs new frame
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //exits frame on closing
frame.setSize(600, 300); // set size of frame
frame.setVisible(true); // displays frame
}p.s. sorry about the untidy comments!OK, so you've got this code here:
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource () == exit) {
System.exit(0); // exits the GUI
if (e.getSource () == snam) {
if (e.getSource () == id) {
}Perfect fine way to do this; although I think creating anonymous would be a bit cleaner:
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
});But I think that the real question you have is "what do I put for logic when the JButtons are hit?", right?
I would answer that you want to dynamically build your SQL statement changing your ordering based on the button.
So you'd have a method that builds the SQL based on what you pass in - so it takes one argument perhaps?
private static final int NAME = 1;
ID = 2;
/* ... some code ... */
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
buildSQL(NAME);
/* ... some code ... */
private void buildSQL(int type) {
if ( type == NAME ) {
/* ... build SQL by name ... */
else if ( type == ID ) {
/* ... build SQL by id ... */
}That kind of thing.
Or you might choose to have several build methods with no parameter type; each building the SQL differently, and calling whichever one you need. I did not read your entire pgm, so I don't know how you'd want to organize it. You need to ask more specific questions at that point.
~Bill -
Having an issue with event handling - sql database & java gui
HI all, have posted this on another forum but I think this is the correct one to post on. I am trying to construct this hybrid of java and mysql. the data comes from a mysql database and I want it to display in the gui. this I have achieved thus far. However I have buttons that sort by surname, first name, ID tag etc....I need event handlers for these buttons but am quite unsure as to how to do it. any help would be much appreciated. Thanks in advance.
/* Student Contact Database GUI
* Phillip Wells
import java.awt.BorderLayout;
// imports java class. All import class statements tell the compiler to use a class that is defined in the Java API.
// Borderlayout is a layout manager that assists GUI layout.
import javax.swing.*; // imports java class. Swing enables the use of a GUI.
import javax.swing.JOptionPane; // imports java class. JOptionPane displays messages in a dialog box as opposed to a console window.
import javax.swing.JPanel; // imports java class. A component of a GUI.
import javax.swing.JFrame; // imports java class. A component of a GUI.
import javax.swing.JButton; // imports java class. A component of a GUI.
import javax.swing.JScrollPane; // imports java class. A component of a GUI.
import javax.swing.JTable; // imports java class. A component of a GUI.
import java.awt.*; // imports java class. Similar to Swing but with different components and functions.
import java.awt.event.*; // imports java class. Deals with events.
import java.awt.event.ActionEvent; // imports java class. Deals with events.
import java.awt.event.ActionListener; // imports java class. Deals with events.
import java.sql.*; // imports java class. Provides API for accessing and processing data stored in a data source.
import java.util.*; // imports java class. Contains miscellaneous utility classes such as strings.
public class studentContact extends JFrame { // public class declaration. The �public� statement enables class availability to other java elements.
private JPanel jContentPane; // initialises content pane
private JButton snam, id, fname, exit; // initialises Jbuttons
String firstname = "firstname"; //initialises String firstname
String secondname = "secondname"; //initialises String
public studentContact() {
Vector columnNames = new Vector(); // creates new vector object. Vectors are arrays that are expandable.
Vector data = new Vector();
initialize();
try {
// Connect to the Database
String driver = "com.mysql.jdbc.Driver"; // connect to JDBC driver
String url = "jdbc:mysql://localhost/Studentprofiles"; //location of Database
String userid = "root"; //user logon information for MySQL server
String password = ""; //logon password for above
Class.forName(driver); //reference to JDBC connector
Connection connection = DriverManager.getConnection(url, userid,
password); // initiates connection
// Read data from a table
String sql = "Select * from studentprofile order by "+ firstname;
//SQL query sent to database, orders results by firstname.
Statement stmt = connection.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//statement to create connection.
//Scroll sensitive allows movement forth and back through results.
//Concur updatable allows updating of database.
ResultSet rs = stmt.executeQuery(sql); // executes SQL query stated above and sets the results in a table
ResultSetMetaData md = rs.getMetaData(); // used to get the properties of the columns in a ResultSet object.
int columns = md.getColumnCount(); //
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i)); // Get column names
while (rs.next()) {
Vector row = new Vector(columns); // vectors data from table
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i)); // Get row data
data.addElement(row); // adds row data
rs.close();
stmt.close();
} catch (Exception e) { // catches exceptions
System.out.println(e); // prints exception message
JTable table = new JTable(data, columnNames) { //constructs JTable
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
return Object.class;
JScrollPane scrollPane = new JScrollPane( table ); // constructs scrollpane 'table'
getContentPane().add(new JScrollPane(table), BorderLayout.SOUTH); //adds table to a scrollpane
private void initialize() {
this.setContentPane(getJContentPane());
this.setTitle("Student Contact Database"); // sets title of table
ButtonListener b1 = new ButtonListener(); // constructs button listener
snam = new JButton ("Sort by surname"); // constructs Jbutton
snam.addActionListener(b1); // adds action listener
jContentPane.add(snam); //adds button to pane
id = new JButton ("Sort by ID"); // constructs Jbutton
id.addActionListener(b1); // adds action listener
jContentPane.add(id); //adds button to pane
fname = new JButton ("Sort by first name"); // constructs Jbutton
fname.addActionListener(b1); // adds action listener
jContentPane.add(fname); //adds button to pane
exit = new JButton ("Exit"); // constructs Jbutton
exit.addActionListener(b1); // adds action listener
jContentPane.add(exit); //adds button to pane
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel(); // constructs new panel
jContentPane.setLayout(new FlowLayout()); // sets new layout manager
return jContentPane; // returns Jcontentpane
private class ButtonListener implements ActionListener { // create inner class button listener that uses action listener
public void actionPerformed (ActionEvent e)
if (e.getSource () == exit) // adds listener to button exit.
System.exit(0); // exits the GUI
if (e.getSource () == snam)
if (e.getSource () == id)
if (e.getSource () == fname)
public static void main(String[] args) { // declaration of main method
studentContact frame = new studentContact(); // constructs new frame
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //exits frame on closing
frame.setSize(600, 300); // set size of frame
frame.setVisible(true); // displays frame
}OK, so you've got this code here:
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource () == exit) {
System.exit(0); // exits the GUI
if (e.getSource () == snam) {
if (e.getSource () == id) {
}Perfect fine way to do this; although I think creating anonymous would be a bit cleaner:
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
});But I think that the real question you have is "what do I put for logic when the JButtons are hit?", right?
I would answer that you want to dynamically build your SQL statement changing your ordering based on the button.
So you'd have a method that builds the SQL based on what you pass in - so it takes one argument perhaps?
private static final int NAME = 1;
ID = 2;
/* ... some code ... */
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
buildSQL(NAME);
/* ... some code ... */
private void buildSQL(int type) {
if ( type == NAME ) {
/* ... build SQL by name ... */
else if ( type == ID ) {
/* ... build SQL by id ... */
}That kind of thing.
Or you might choose to have several build methods with no parameter type; each building the SQL differently, and calling whichever one you need. I did not read your entire pgm, so I don't know how you'd want to organize it. You need to ask more specific questions at that point.
~Bill -
Passing command line argument in java
I was writting a calendar pogram that took user input from the command line. What I want to know is how can I write my program so that if the user doesn't enter the info. it will automatically assign a value to the variable in the array, eg:
if they typed: java calendarmonth 10 2005
they would get a printout for the calendar month of October 2005, but I want it so that if they typed
java calendarmonth 10
it would automatically assign they year to be the current year, and if they typed
java calendarmonth
it would auctomattically assign the current month and year to the program, heres the source code:
import javax.swing.JOptionPane;
import java.util.*;
public class calendarmonth {
/** Main method */
public static void main(String argv[]) {
String monthString = argv[0];
int month = Integer.parseInt(monthString);
String yearString = argv[1];
int year = Integer.parseInt(yearString);
printMonth(year, month);
if (month > 12) {
System.out.println("Invalid Number Please Try");
//code to perform OK action
/** Print the calendar for a month in a year */
static void printMonth(int year, int month) {
//Print the heading of the calendar
printMonthTitle(year, month);
//Print the headings of the calendar
printMonthBody(year, month);
/** Print the month title, e.g., May, 1999 */
static void printMonthTitle(int year, int month) {
System.out.println(" " + getMonthName(month)
+ " " + year);
System.out.println("------------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
/** Get the English name for the month */
static String getMonthName(int month) {
String monthName = null;
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December"; break;
return monthName;
/** Print month body*/
static void printMonthBody(int year, int month){
//Get start day of the week for the first date in the month
int startDay = getStartDay(year, month);
//Get number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);
//Pad space before the first day of the month
int i = 0;
for (i = 0; i < startDay; i++)
System.out.print(" ");
for (i = 1; i <= numberOfDaysInMonth; i++) {
if (i < 10)
System.out.print(" " + i);
else
System.out.print(" " + i);
if ((i + startDay) % 7 == 0)
System.out.println();
System.out.println();
/** Get the start day of the first day in a month */
static int getStartDay(int year, int month) {
//Get total number of days since 1/1/1800
int startDay1800 = 3;
int totalNumberOfDays = getTotalNumberOfDays(year, month);
//Return the start day
return (totalNumberOfDays + startDay1800) % 7;
/** Get the total number of days since Jan 1, 1800 */
static int getTotalNumberOfDays(int year, int month) {
int total = 0;
// Get the total days from 1800 to year - 1
for (int i = 1800; i < year; i++)
if (isLeapYear(i))
total = total + 366;
else
total = total + 365;
// Add days from Jan to the month prior to the calendar month
for (int i = 1; i < month; i++)
total = total + getNumberOfDaysInMonth(year, i);
return total;
/** Get the number of days in a month */
static int getNumberOfDaysInMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12)
return 31;
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if (month == 2) return isLeapYear(year) ? 29 : 28;
return 0; // If month is incorrect
thanks
/** Determine if it is a leap year */
static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}hey smallsouljah , to use code tags just put your code inside code tags.
to create code tags you just need to press the button code that is located bellow the subject, this will automatically create code tags.
System.out.println("testing");
try yourself. -
Right you prob saw me having problems with this earlier. I think i am making progress. I think i have created two constructors within a class, and for one of these constructors i have initialised a time object to 3.45.
What i am stuck on is outputting this object, you will see in my main what i have attempted to do and you might be able to advise me. This also might sound really stupid but i am learning, but do you need a main in java?? Just wondering because when i compiled my constructors without a main, the process was completed.
Anyway, heres what i have done:
import javax.swing.JOptionPane;
public class Time
public int hour;
public int minute;
public boolean isMorning;
public Time(){
hour = 1;
minute = 0;
isMorning = true;
public Time(int hr, int min, boolean bool){
hour = hr;
minute = min;
isMorning = bool;
public void Time(int hr, int min, boolean bool){
Time setTime = new Time(3, 45, false);
public static void main (String[]args)
System.out.println(setTime.Time());
}That was fun...
package forums;
import javax.swing.JOptionPane;
import java.util.Calendar;
// see: http://forum.java.sun.com/post!reply.jspa?messageID=10019378
// see also: http://forum.java.sun.com/thread.jspa?threadID=726758&messageID=4187127
// especially 24*60*60*1000 won't work because of leap years, days, and seconds.
public class Time
public final int hour;
public final int minute;
public final boolean isMorning;
public Time(int hour, int minute, boolean isMorning) {
this.hour = hour;
this.minute = minute;
this.isMorning = isMorning;
public Time(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
int hr = cal.get(Calendar.HOUR_OF_DAY);
this.isMorning = (hr <= 12);
if (!isMorning) hr-=12;
this.hour = hr;
this.minute = cal.get(Calendar.MINUTE);
public Time() {
this(System.currentTimeMillis());
public String toString() {
return String.format("%d:%02d %s", this.hour, this.minute, (this.isMorning?"AM":"PM"));
public static void main(String... args) {
System.out.println( "1:32 AM = " + new Time(1,32,false) );
System.out.println( "now = " + new Time() );
System.out.println( "3:02 PM = " + new Time(1197781366609L) );
private static void debug(String msg) {
System.out.println("DEBUG: "+msg);
}Cheers. Keith. -
Help! Simple Java Program.
Here is the problem: Write a program that creates a loan amortization table. The user of the program will supply values for Initial Loan Principal, Annual Percentage Rate and Monthly Payment. The program should print out the appropriate amortization table including the number of Monthly Payments and the Total Interest paid for the life of the loan. The program should allow multiple
runs (up to 4 different versions) of the table process and should allow the
user to compare runs in a tabular format.
This is what I have so far and should work one I completely debug it. I am really new to Java, and I thinks it is somthing to do with the Array. I recently switched from C++ to Java, so I don't think I have the syntax down correctly. Thanks.
import javax.swing.JOptionPane;
public class Program_01
public static void main(String [] args)
int Runs;
do{
String Run_Question = JOptionPane.showInputDialog(null, "How many times,would you like to run" +
" the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
Runs = Integer.parseInt(Run_Question);
if( Runs < 0 || Runs > 4)
JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
JOptionPane.INFORMATION_MESSAGE);
}while(Runs < 0 || Runs > 4);
Questions(Runs);
public static void Questions(int Runs)
for(int index = 0;index < Runs;index ++)
String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
JOptionPane.QUESTION_MESSAGE);
String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
"Interest Rate", JOptionPane.QUESTION_MESSAGE);
String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
JOptionPane.QUESTION_MESSAGE);
double Loan_Principle = Double.parseDouble(Loan_Principle_String);
double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);
public static void Calculate (double Loan, double Percentage, double Monthly)
double[] Principle = new double[]{0,0};
double[] Interest = new double[]{0,0};
double[] Remain = new double[]{0,0};
double Monthly_Percent = Percentage/12;
double MPR = ((int)((Monthly_Percent + .005) * 100.) / 100.);
boolean Over = true;
double Borrowed = Loan;
int Month = 0;
for (int index = 0; Over != false; index++)
double Rate = MPR * Loan;
double decimalRate = ((int)((Rate + .005) * 100.) / 100.);
Interest[index] = decimalRate;
double Prince = Monthly - decimalRate;
double decimalPrince = ((int)((Prince + .005) * 100.) / 100.);
Principle[index]= decimalPrince;
double Rmn = Borrowed - decimalPrince;
Borrowed = Rmn;
double decimalRmn = ((int)((Rmn + .005) * 100.) / 100.);
Remain[index] = decimalRmn;
if(Monthly > Remain[index] && Remain[index] > 0)
Monthly = Remain[index];
Over = false;
Month += 1;
System.out.println("I am here!" + Month);
System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "APR" + " " + "MPR" +
" " + "Interest Payment" + " " + "Principle Payment");
System.out.println("------------------------------------------------------------------------");
for(int index = 0; index < Month; index++)
System.out.println((index + 1) + "\t" + Remain[index] + "\t" + Percentage + "\t" + MPR + "\t" + Interest[index]
+ "\t" + Principle[index]);
}Okay, here is my updated code. I am having trouble outputting my formate to align with each category.
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Program_01
public static void main(String [] args)
int Runs;
do
String Run_Question = JOptionPane.showInputDialog(null, "How many times would you like to run" +
" the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
Runs = Integer.parseInt(Run_Question);
if( Runs < 0 || Runs > 4)
JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
JOptionPane.INFORMATION_MESSAGE);
}while(Runs < 0 || Runs > 4);
Questions(Runs);
public static void Questions(int Runs)
for(int index = 0;index < Runs;index ++)
String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
JOptionPane.QUESTION_MESSAGE);
String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
"Interest Rate", JOptionPane.QUESTION_MESSAGE);
String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
JOptionPane.QUESTION_MESSAGE);
double Loan_Principle = Double.parseDouble(Loan_Principle_String);
double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);
public static void Calculate (double Loan, double Percentage, double Monthly)
double[] Principle = new double[100];
double[] Interest = new double[100];
double[] Remain = new double[100];
double[] Payment = new double[100];
DecimalFormat Decimal = new DecimalFormat(".00");
double Total_Interest = 0;
double T_Interest;
double Monthly_Percent = (Percentage/12)/100;
double MPR = Monthly_Percent;
boolean Over = true;
double Borrowed = Loan;
double Deposit = Monthly;
int Month = 0;
for (int index = 0; Over = true; index++)
double Rate = MPR * Borrowed;
double decimalRate = round(Rate,2);
Interest[index] = decimalRate;
Remain[index] = Borrowed;
Month += 1;
if(Monthly > Remain[index ] && Remain[index ] > 0)
for(int count = 0; count <= Month; count++)
Total_Interest += Interest[count];
T_Interest = round(Total_Interest,2);
Payment[index] = T_Interest;
Deposit = T_Interest;
else
Payment[index] = Deposit;
double Prince = Deposit - decimalRate;
double decimalPrince = round(Prince,3);
Principle[index]= decimalPrince;
System.out.println("I am here!" + decimalPrince);
double Rmn = Borrowed - decimalPrince;
double decimalRmn = round(Rmn,2);
Borrowed = decimalRmn;
if(Monthly > Remain[index ] && Remain[index ] > 0)
Over = false;
break;
System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "Percentage" + " " + "MPR" +
" " + "Interest Payment" + " " + "Principle Payment");
System.out.println("----------------------------------------------------------------------------");
for(int index = 0; index < Month; index++)
System.out.println(" " + (index + 1) + "\t " + Decimal.format(Remain[index]) + " " +
Decimal.format(Payment[index]) + " " + Decimal.format(Percentage) + " " + MPR +
"\t" + Decimal.format(Interest[index]) + "\t\t" + Decimal.format(Principle[index]));
T_Interest = ((int)((Total_Interest + .005) * 100.) / 100.);
System.out.println("\n\t\t\t" + "Total Interest Paid \t" + T_Interest + "\n");
for(int index = 0; index < Month; index++)
System.out.printf("%f %f\n", Principle[index],Remain[index]);
public static double round(double val, int places) {
long factor = (long)Math.pow(10,places);
// Shift the decimal the correct number of places
// to the right.
val = val * factor;
// Round to the nearest integer.
long tmp = Math.round(val);
// Shift the decimal the correct number of places
// back to the left.
return (double)tmp / factor;
} -
Tooltiptext in a JOptionPane's Combobox?
Hi, Im wounder if it's possible to add
ToolTipsTexts to a JOptionPane.showInputDialog that is created in this way.
sortedFunctionSet.toArray gives a array of strings making the showinputdialog create a combobox with all values. I want to show a tooltiptext for each item in the combobox.
JOptionPane.showInputDialog(
getCurrentView(),
"SomeText",
"Heading",
JOptionPane.QUESTION_MESSAGE,
getIcon(),
sortedFunctionSet.toArray(),
null
);Thanks!
Message was edited by:
AnyAndyRead the article on "Beyond the Basics of JOptionPane":
http://java.sun.com/developer/JDCTechTips/
It shows you how to add a component directly to the option pane. So you can build your combo box externally and add tooltips to it and then add the combo box to the option pane. -
Can someone please help me with this compiling error....java:17: incompatible types
found : void
required: java.lang.String
String output = JOptionPane.showMessageDialog(null,message,"Rectangle Properties", JOptionPane.PLAIN_MESSAGE);
1 error
I know it probally has to do with the null but i dont know what to change it to....can someone please help
import javax.swing.JOptionPane;
import java.text.NumberFormat;
public class RectangleApp
public static void main(String[] args)
String lenString = JOptionPane.showInputDialog(null,"Enter the length of a rectangle",
"Length input", JOptionPane.INFORMATION_MESSAGE);
double length = DataValidator.parseDouble(lenString);
String widString = JOptionPane.showInputDialog(null,"Enter the width of a rectangle",
"Width input", JOptionPane.INFORMATION_MESSAGE);
double width = DataValidator.parseDouble(widString);
Rectangle rectangle;
rectangle = new Rectangle(length,width);
String message = rectangle.toString();
String output = JOptionPane.showMessageDialog(null,message,"Rectangle Properties", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}If you look at the API docs, which you always should...
showMessageDialog() returns void and you are assigning it to String.
Change the last line
String output = JOptionPane.showMessageDialog(null,message,"Rectangle Properties", JOptionPane.PLAIN_MESSAGE);
to
JOptionPane.showMessageDialog(null,message,"Rectangle Properties", JOptionPane.PLAIN_MESSAGE);
Regards
$ Carol -
JOptionPane in applet - Help!
Beginning to write a program and narrowed down the problem. When I ask for an input for the number of sticks to take away, the popup keeps coming back! How do I make the program accept the first input and stop?
Thanks!
import java.util.*;
import java.applet.Applet;
import javax.swing.JOptionPane;
import java.awt.*;
public class jaeglenim2 extends Applet
public void paint(Graphics g)
Graphics2D g2 = (Graphics2D)g;
g2.drawString("The Game of Nim", 100,30);
Random generator = new Random();
boolean smart = true;
boolean firstPlayer = true;
int totalNumber = 10 + generator.nextInt(100);
g2.drawString("Total number of sticks left: " + totalNumber,300,50);
if (firstPlayer == true)
g2.drawString("You go first.", 0,60);
String input = JOptionPane.showInputDialog("Choose the number of sticks to take away.");
int number = Integer.parseInt(input);
g2.drawString("You take " + number, 0,80);
totalNumber = totalNumber - number;
g2.drawString("Total number of sticks left: " + totalNumber, 300, 80);
else
g2.drawString("Computer goes first.",0,60);
System.exit(0)You shouldn't ask for input in the paint method, that method should restrict its actions to graphics.
Maybe you are looking for
-
Hi Everyone I used this in SP calculated column field. =IF([Shift Sched]="1pm to 10pm","0",IF([Shift Sched]="2pm to 11pm","1",IF([Shift Sched]="3pm to 12am","2",IF([Shift Sched]="4pm to 1am","3",IF([Shift Sched]="5pm to 2am","4",IF([Shift Sched]="6pm
-
USB Ethernet will not configure
Hello, Today I started to have problems with my USB Ethernet dongle on my Yosemite Macbook Pro Late 2013 Retina. I deleted the device from Network Utility then rebooted thinking I would re-initialze it. After rebooting, the System Info recognizes
-
Interface Project System to Catalog OCI
I am trying to implement SciQuest within Project Systems SPRO > Project Systems > Material > Interface for Procurement Using Catalog (OCI) and I am difficulty navigating around SciQuest site. The actual punch out works but when I click on 'Add to C
-
Hi, I ' ve finished oca certification.but i dont know how to enter into this field? how to prepare for an interview? please tell me what questions are frequently asked?
-
What do I need to add to my comp to have two or three hdmi ports to run video or cable TV and are some better than others ?