Character in java program
Hello:
i am supporting a web application that fails when some spanish characters are introduced "�, �.." Is there anyway to limit the characters an user can introduce in the web application without changing the code. I am looking for a -D option to do it.
Regards,
Mario.
JFormattedTextField?
Similar Messages
-
To display chinese/japanese language Character filename - Java Programming
In Our application supports to upload a file with name in chinese/japanese language Character. When user tries to download filedownload dialog box is appearing with the filename as junk characters.
How to solve this issue to display the filename as uploaded.Have your tried googling your problem?
I found this article: [http://www.chinesecomputing.com/programming/java.html|http://www.chinesecomputing.com/programming/java.html] That seems promising, but ofcourse I cant tell if it will work on your application without seeing a shred of code.
Im certain there is others that has had the same problem before, and put up their solutions on the net. -
Error running java program (testing oracle-character-set-31 against ab?c )
Hi
When i run my java program from eclipse , i get these errors : how to correct these errors and run the program
testing oracle-character-set-31 against <ab?c>
PASSED LOSSY
testing oracle-character-set-31 against <XYZ>
PASSED LOSSY
testing oracle-character-set-31 against <longlonglonglong...>
PASSED LOSSY
testing oracle-character-set-870 against <abc>
PASSED
testing oracle-character-set-870 against <ab?c>
PASSED
testing oracle-character-set-870 against <XYZ>
PASSED
testing oracle-character-set-870 against <longlonglonglong...>
PASSED
testing oracle-character-set-871 against <abc>
PASSED
testing oracle-character-set-871 against <ab?c>
PASSED
testing oracle-character-set-871 against <XYZ>
PASSED
testing oracle-character-set-871 against <longlonglonglong...>
PASSEDrxg wrote:
Hi
When i run my java program from eclipse , i get these errors : how to correct these errors and run the program
...Sun's not Oracle (yet). You will have better luck on a forum relating to whatever is producing that "oracle-character-set..." output.
Edit:
Although a Google search for "testing oracle-character-set" yields only this thread. Are you sure that output isn't part of your program?
Edited by: endasil on 7-Oct-2009 3:40 PM -
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(); -
Dear Forummembers,
I am student doing postgraduate studies in IT.i have some queries related to one of my programming staff.i am very much new into Java programming and i am finding it a bit difficult to handle this program.The synopsis of the program is given below -
You are required to design and code an object-oriented java program to process bookings for a theatre perfomance.
Your program will read from a data file containing specifications of the performance,including the names of the theatre, the play and its author and the layout of the theatre consisting of the number of seats in each row.
It will then run a menu driven operation to accept theatre bookings or display the current
status of seating in the theatre.
The name of the file containing the details of the performance and the theatre should be
provided at the command line, eg by running the program with the command:
java Booking Theatre.txt
where Theare.txt represents an example of the data file.
A possible data file is:
Opera
U and Me
Jennifer Aniston
5 10 10 11 12 13 14
The data provided is as follows
Line 1
Name of the Theatre
Line 2
Name of the play being performed
Line 3
Name of the author of the play being performed
Line 4
A list of the lengths (number of seats) of each row in the theatre, from front to
back.
The program must start by reading this file, storing all the appropriate parameters and
establishing an object to accept bookings for this performance with all details for the theatre
and performance.
The program should then start a loop in which a menu is presented to the user, eg:
Select from the following:
B - Book seats
T - Display Theatre bookings
Q - Quit from the program
Enter your choice:
And keep performing selected operations until the user�s selects the quit option, when the
program should terminate.
T - Display Theatre bookings
The Display Theatre Bookings option should display a plan of the theatre. Every available
seat should be displayed containing its identification, while reserved seats should contain an
Rows in each theatre are indicated by letters starting from �A� at the front. Seats are
numbered from left to right starting from 1. A typical seat in the theatre might be designated
D12, representing seat 12 in row D.
B - Book seats
The booking of seats is to offer a number of different options.
First the customer must be asked how many adjacent seats are
required. Then start a loop offering a further menu of choices:
Enter one of the following:
The first seat of a selected series, eg D12
A preferred row letter, eg F
A ? to have the first available sequence selected for you
A # to see a display of all available seats
A 0 to cancel your attempt to book seats
Enter your selection:
1. If the user enters a seat indentifier such B6, The program should attempt to
reserve the required seats starting from that seat. For example if 4 seats are
required from B6, seats B6, B7, B8 and B9 should be reserved for the customer,
with a message confirming the reservation and specifying the seats reserved..
Before this booking can take place, some testing is required. Firstly, the row
letter must be a valid row. Then the seat number must be within the seats in the
row and such that the 4 seats would not go beyond the end of the row. The
program must then check that none of the required seats is already reserved.
If the seats are invalid or already reserved, no reservation should be made and the
booking menu should be repeated to give the customer a further chance to book
seats.
If the reservation is successful, return to the main menu.
2. The user can also simply enter a row letter, eg B.IN this case, the program should
first check that the letter is a valid row and then offer the user in turn each
adjacent block of the required size in the specified row and for each ask whether
the customer wants to take them. Using the partly booked theatre layout above, if
the customer wanted 2 seats from row B, the customer should be offered first:
Seats B5 to B6
then if the customer does not want them:
Seats B10 to B11
and finally
Seats B11 to B12
If the customer selects a block of seats, then return to the main menu. If none are
selected, or there is no block of the required size available in the row, then report
that no further blocks of the required size are available in the row and repeat the
booking menu.
3. If the user enters a ? the program should offer the customer every block of seats
of the required size in the whole theatre. This process should start from the first
row and proceed back a row at a time. For example, again using the partially
booked theatre shown above, if the user requested 9 seats, the program should
offer in turn:
Seats A1 to A9
Seats C1 to C9
Seats C2 to C10
Seats E3 to E11
Seats E4 to E12
If the customer selects a block of seats, then return to the main menu. If none are
selected, or there is no block of the required size available in the whole theatre,
then report that no further blocks of the required size are available and repeat the
booking menu.
4. If the user enters a # the program should display the current status of the seating
in the theatre, exactly the same as for the T option from the main menu and then
repeat the booking menu.
5. If the user enters a 0 (zero), the program should exit from the booking menu back
to the main menu. If for example the user wanted 9 seats and no block of 9 was
left in the theatre, he would need to make two separate smaller bookings.
The program should perform limited data validation in the booking process. If a single
character other than 0, ? and # is entered, it should be treated as a row letter and then tested
for falling within the range of valid rows, eg A to H in the example above. Any invalid row
letters should be rejected.
If more than one character is entered, the first character should be tested as a valid row letter,
and the numeric part should be tested for falling within the given row. You are NOT
required to test for valid numeric input as this would require the use of Exception handling.
You are provided with a class file:
Pad.java
containing methods that can be used for neat alignment of the seat identifiers in the theatre
plan.
File Processing
The file to be read must be opened within the program and if the named file does not exist, a
FileNotFoundException will be generated. It is desirable that this Exception be caught and
a corrected file name should be asked for.
This is not required for this assignment, as Exception handling has not been covered in this
Unit. It will be acceptable if the method simply throws IOException in its heading.
The only checking that is required is to make sure that the user does supply a file on the
command line, containing details of the performance. This can be tested for by checking the
length of the parameter array args. The array length should be 1. If not, display an error
message telling the user the correct way to run the program and then terminate the program
System.exit(0);
The file should be closed after reading is completed.
Program Requirements
You are expected to create at least three classes in developing a solution to this problem.
There should be an outer driving class, a class to represent the theatre performance and its
bookings and a class to represent a single row within the theatre.
You will also need to use arrays at two levels. You will need an array of Rows in the Theatre
class.
Each Row object will need an array of seats to keep track of which seats have been reserved.
Your outer driving class should be called BookingOffice and should be submitted in a file named BookingOffice.java
Your second, third and any additional classes, should be submitted in separate files, each
class in a .java file named with the same name as the class
I am also very sorry to give such a long description.but i mainly want to know how to approach for this program.
also how to designate each row about it's column while it is being read from the text file, how to store it, how to denote first row as row A(second row as row B and so on) and WHICH CLASS WILL PERFORM WHICH OPERATIONS.
pls do give a rough guideline about designing each class and it's reponsibilty.
thanking u and looking forward for your help,
sincerely
RKyes i do know that........but can u ppl pls mention
atleast what classes shud i consider and what will be
the functions of each class?No, sorry. Maybe somebody else will, but in general, this is not a good question for this forum. It's too broad, and the question you're asking is an overall problem solving approach that you should be familiar with at this point.
These forums are best suited to more specific questions. "How do I approach this homework?" is not something that most people are willing or able to answer in a forum like this. -
How to send sms through java program?
hi,
i am trying to send sms through java program.i am usining ubuntu 6.04.i am using modem MC35i.i use the jSMSEnjine.jar and rxtxcomm.jar.
these are the following program.
import org.jsmsengine.*;
import java.util.*;
class SendMessage
public static void main(String[] args)
int status;
// Create jSMSEngine service.
CService srv = new CService("Com2",9600);
//CService srv = new CService("COM2",9600);
System.out.println();
System.out.println("SendMessage(): sample application.");
System.out.println(" Using " + srv._name + " " + srv._version);
System.out.println();
try
// Initialize service.
srv.initialize();
Thread thread =Thread.currentThread();
thread.sleep(1000);
System.out.println(srv);
// Set the cache directory.
srv.setCacheDir(".\\");
// Set the phonebook.
// srv.setPhoneBook("../misc/phonebook.xml");
// Connect to GSM device.
status = srv.connect();
// Did we connect ok?
int st=CService.ERR_OK;
System.out.println(st);
System.out.println(status);
if (status == CService.ERR_OK)
// Set the operation mode to PDU - default is ASCII.
srv.setOperationMode(CService.MODE_PDU);
// Set the SMSC number (set to default).
srv.setSmscNumber("");
// Print out GSM device info...
System.out.println("Mobile Device Information: ");
System.out.println(" Manufacturer : " + srv.getDeviceInfo().getManufacturer());
System.out.println(" Model : " + srv.getDeviceInfo().getModel());
System.out.println(" Serial No : " + srv.getDeviceInfo().getSerialNo());
System.out.println(" IMSI : " + srv.getDeviceInfo().getImsi());
System.out.println(" S/W Version : " + srv.getDeviceInfo().getSwVersion());
System.out.println(" Battery Level : " + srv.getDeviceInfo().getBatteryLevel() + "%");
System.out.println(" Signal Level : " + srv.getDeviceInfo().getSignalLevel() + "%");
// Create a COutgoingMessage object and dispatch it.
// *** Please update the phone number with one of your choice ***
// String smsLengthTest="Hi"+"\nTesting is going on.Test for sending unlimited number of charecter.So you will get N number of SMS.Initially I trancate the whole string by 70 charecter.Later I will put it upto 90 charecter.Some chararecter should kept for header portion.I don't know the total number.It is just test.If you got the sms u should appreciate me...This is Ripon...I have written sms program";
String smsLengthTest="Hi\n"+"This is Govindo";
int mao=smsLengthTest.length();
System.out.println("Length of sms :"+mao);
String smsNo="9433314095";
smsNo="+91"+smsNo;
if(mao<70)
COutgoingMessage msg = new COutgoingMessage(smsNo,smsLengthTest);
// Character set is 7bit by default - lets make it UNICODE :)
// We can do this, because we are in PDU mode (look at line 63). When in ASCII mode,
// this does not make ANY difference...
msg.setMessageEncoding(CMessage.MESSAGE_ENCODING_UNICODE);
if (srv.sendMessage(msg) == CService.ERR_OK) System.out.println("Message Sent!");
else System.out.println("Message Failed!");
else
// COutgoingMessage msg = new COutgoingMessage(smsNo,smsLengthTest);
// LinkedList messageList;
// messageList = new LinkedList();
// messageList.add(msg);
// LinkedList maooo=new LinkedList();
// maooo=srv.splitLargeMessages(messageList);
int sizelength=0;
int counter=0;
sizelength=smsLengthTest.length();
System.out.println("SMS length :"+sizelength);
int smsCntr=sizelength/70;
System.out.println("smsCntr :"+smsCntr);
counter=smsCntr+1;
int j=70;
int k=0;
try
for(int i=0;i<smsCntr;i++)
String test="";
test=test+i;
test=smsLengthTest.substring(k,j);
System.out.println(test);
System.out.println(test.length());
COutgoingMessage msg = new COutgoingMessage(smsNo, test);
System.out.println("hi this is suman" + smsNo);
// Character set is 7bit by default - lets make it UNICODE :)
// We can do this, because we are in PDU mode (look at line 63). When in ASCII mode,
// this does not make ANY difference...
msg.setMessageEncoding(CMessage.MESSAGE_ENCODING_UNICODE);
if (srv.sendMessage(msg) == CService.ERR_OK) System.out.println("Message Sent!");
else System.out.println("Message Failed!");
k=k+70;
j=j+70;
catch(Exception e)
System.out.println("Error...1");
e.printStackTrace();
e.getMessage();
String lastPortion=smsLengthTest.substring(k);
System.out.println(lastPortion);
COutgoingMessage msg = new COutgoingMessage(smsNo, lastPortion);
// Character set is 7bit by default - lets make it UNICODE :)
// We can do this, because we are in PDU mode (look at line 63). When in ASCII mode,
// this does not make ANY difference...
msg.setMessageEncoding(CMessage.MESSAGE_ENCODING_UNICODE);
if (srv.sendMessage(msg) == CService.ERR_OK) System.out.println("Message Sent!");
else System.out.println("Message Failed!");
// Disconnect from GSM device.
srv.disconnect();
else System.out.println("Connection to mobile failed, error: " + status);
catch (Exception e)
e.printStackTrace();
System.exit(0);
the error is:
SendMessage(): sample application.
Using jSMSEngine API 1.2.6 (B1)
org.jsmsengine.CService@addbf1
0
-101
Connection to mobile failed, error: -101
please help me,its very urgent.come back in about 5 years, we may have time for you by then.
In the meantime, how about contacting the people who wrote that library and asking them nicely for help (rather than trying to order people to drop whatever they're doing and jump through hoops to accommodate your every wish as you're doing here)? -
Sorting Names in a text file using java program
h1. Deleting numbers in a text file, sorting the names and writing in to a new file
h2. Sample data
=================
71234 RAJA
89763 KING
89877 QUEEN
==================
h2. Java Program
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
class Sortnames {
public static void main(String args[]) {
try {
ArrayList storeWordList = new ArrayList();
ArrayList storeWordList2 = new ArrayList();
int i;
char c;
String inputfile = "names_konda.txt";
String tempfile = "newdatafile.txt";
String outputfile = "sortedoutput.txt";
StringBuffer strBuff=null;
Writer output = null;
File file =null;
Writer sortedoutput = null;
boolean select =false;
//*********************************************** Reading data from Input file
FileInputStream fstream = new FileInputStream(inputfile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
storeWordList.add(strLine);
//Close the input stream
in.close();
//*********************************************** Adding only alphabets to buffer and writing to file
file= new File(tempfile);
output = new BufferedWriter(new FileWriter(file));
strBuff = new StringBuffer();
for (Iterator iter = storeWordList.iterator(); iter.hasNext();) {
String s = (String) iter.next();
//System.out.println("String "+s);
for (i = 0; i < s.length() ; i++)
c = s.charAt(i);
if (Character.isLetter(c)) {
strBuff.append(c);
strBuff.append("\n");
String myout = strBuff.toString();
output.write(myout);
output.close();
//============================================== Reading the created file,Sorting and placing in Collections
FileInputStream fstream2 = new FileInputStream(tempfile);
// Get the object of DataInputStream
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine2;
//Read File Line By Line
while ((strLine2 = br2.readLine()) != null) {
storeWordList2.add(strLine2);
Collections.sort(storeWordList2);
//===================================================
File sortedfile = new File(outputfile);
sortedoutput = new BufferedWriter(new FileWriter(sortedfile));
for(int m=0; m<storeWordList2.size(); m++)
if (storeWordList2.get(m).toString().trim().length() > 0)
sortedoutput.write(storeWordList2.get(m).toString());
sortedoutput.write("\n");
sortedoutput.close();
System.out.println("Names Sorted SUCCESFULLY");
br.close();
br2.close();
in.close();
fstream.close();
fstream2.close();
///==========================================
File f1 = new File(tempfile);
boolean success = f1.delete();
if (!success){
System.out.println("failed deletion ");
System.exit(0);
}else{
System.out.println("deleted");
// ==========================================
} catch (Exception e) {//Catch exception if any
System.out.println("Error: " + e);
h2. Thanks and regards
h1. BalaNagaRaju.M
h1. [email protected]Do you have a question? Also see the sticky welcome post on how to post formatted code.
-
Help with Java programming project
Hi,
I need help in writing this Java program. The purpose of this program is to read a variable-length stream of 0, 1 characters from an input text file (call it input.txt) one character at a time, and generate the corresponding B8ZS output stream consisting of the +, - , and 0 characters (with appropriate substitutions) one-character-at-a-time into a text file (called output.txt).
The program must use a class called AMIConverter with an object called AMI . Class AMIConverter must have a method called convert which converts an individual input character 0 or 1 into the appropriate character 0 or + or - of AMI.
It first copy the line to file output.txt. Then read the line one character at a time and pass only valid characters (0 or 1) to AMI.convert, which assumes only valid characters. The first 1 in each new 'Example' should be converted to a +.
This is what is read in, but this is just a test case.
0101<1000
1100a1000b00
1201g101
should now produce two lines of output for each 'Example', as shown below:
This should be the output of the output.txt file
Example 1
in :0101<1000
out:0+0-+000
Example 2
in :1100a1000b00
out:+-00+00000
Example 3
in :1201g101
out:+0-+0-
To elaborate more, only 1 and 0 are passed to "convert" method. All others are ignored. 0 become 0 and 1 become either + or - and the first "1" in each new example should be a +.
This is what I have so far. So far I am not able to get the "in" part, the characters (e.g. : 0101<1000 ) out to the output.txt file. I am only able to get the "out" part. And I also can't get it to display a + for the first "1" in each new examples.
import java.io.*;
public class AMIConverter
public static void main (String [] args) throws IOException
AMI ami = new AMI();
try
int ch = ' ';
int lineNum = 1;
int THE_CHAR_0 = '0';
int THE_CHAR_1 = '1';
BufferedReader infile = new BufferedReader(new FileReader("input.txt"));
PrintWriter outfile = new PrintWriter("output.txt");
outfile.write("Example " + lineNum);//prints Example 1
outfile.println();
outfile.write("in :");
outfile.println();
outfile.write("out:");
while ((ch = infile.read()) != -1)
if (ch == '\r' || ch == '\n')
lineNum++;
outfile.println();
outfile.println();
outfile.write("Example " + lineNum);
outfile.println();
outfile.write("in :");
outfile.println();
outfile.write("out:");
else
if (ch == THE_CHAR_0)
int output = ami.convert(ch);
outfile.write(output);
else
if (ch == THE_CHAR_1)
int output = ami.convert(ch);
outfile.write(output);
}//end while
infile.close();
outfile.close();
}catch (IOException ex) {}
}//main method
}//class AMIConverter
This is my AMI class
import java.io.*;
public class AMI
int THE_CHAR_0 = '0';
int THE_CHAR_1 = '1';
int total = '+';
int minus = '-';
int count = 0;
public int convert(int ch)
try
PrintWriter outfile = new PrintWriter("output.txt");
if (ch == THE_CHAR_0)
return ch;
else
if (ch == THE_CHAR_1)
count++;
if (count%2 == 1)
ch = total;
return (ch);
else
ch = minus;
return (ch);
}catch (FileNotFoundException e) {}
return ch;
}//method convert
}//class AMI
Any help would be appreicated.
Thanks!Hi,
I need help in writing this Java program. The purpose of this program is to read a variable-length stream of 0, 1 characters from an input text file (call it input.txt) one character at a time, and generate the corresponding B8ZS output stream consisting of the +, - , and 0 characters (with appropriate substitutions) one-character-at-a-time into a text file (called output.txt).
The program must use a class called AMIConverter with an object called AMI . Class AMIConverter must have a method called convert which converts an individual input character 0 or 1 into the appropriate character 0 or + or - of AMI.
It first copy the line to file output.txt. Then read the line one character at a time and pass only valid characters (0 or 1) to AMI.convert, which assumes only valid characters. The first 1 in each new 'Example' should be converted to a +.
This is what is read in, but this is just a test case.
0101<1000
1100a1000b00
1201g101
should now produce two lines of output for each 'Example', as shown below:
This should be the output of the output.txt file
Example 1
in :0101<1000
out:0+0-+000
Example 2
in :1100a1000b00
out:+-00+00000
Example 3
in :1201g101
out:+0-+0-
To elaborate more, only 1 and 0 are passed to "convert" method. All others are ignored. 0 become 0 and 1 become either + or - and the first "1" in each new example should be a +.
This is what I have so far. So far I am not able to get the "in" part, the characters (e.g. : 0101<1000 ) out to the output.txt file. I am only able to get the "out" part. And I also can't get it to display a + for the first "1" in each new examples.
import java.io.*;
public class AMIConverter
public static void main (String [] args) throws IOException
AMI ami = new AMI();
try
int ch = ' ';
int lineNum = 1;
int THE_CHAR_0 = '0';
int THE_CHAR_1 = '1';
BufferedReader infile = new BufferedReader(new FileReader("input.txt"));
PrintWriter outfile = new PrintWriter("output.txt");
outfile.write("Example " + lineNum);//prints Example 1
outfile.println();
outfile.write("in :");
outfile.println();
outfile.write("out:");
while ((ch = infile.read()) != -1)
if (ch == '\r' || ch == '\n')
lineNum++;
outfile.println();
outfile.println();
outfile.write("Example " + lineNum);
outfile.println();
outfile.write("in :");
outfile.println();
outfile.write("out:");
else
if (ch == THE_CHAR_0)
int output = ami.convert(ch);
outfile.write(output);
else
if (ch == THE_CHAR_1)
int output = ami.convert(ch);
outfile.write(output);
}//end while
infile.close();
outfile.close();
}catch (IOException ex) {}
}//main method
}//class AMIConverterThis is my AMI class
import java.io.*;
public class AMI
int THE_CHAR_0 = '0';
int THE_CHAR_1 = '1';
int total = '+';
int minus = '-';
int count = 0;
public int convert(int ch)
try
PrintWriter outfile = new PrintWriter("output.txt");
if (ch == THE_CHAR_0)
return ch;
else
if (ch == THE_CHAR_1)
count++;
if (count%2 == 1)
ch = total;
return (ch);
else
ch = minus;
return (ch);
}catch (FileNotFoundException e) {}
return ch;
}//method convert
}//class AMIAny help would be appreicated.
Thanks! -
How can my java program launch other applications?
can anyone link me, provide some keywords, or information on how a java program can execute another program... for example, a button click would launch acrobat, firefox, or (in particular) another java application.
don't read all that much fantasy.
I've read Eddings' Belgariad and Malloreon, which I really liked at the time but which are not even in the same league as GRRM. The characters are much more one-dimensional, and the plot gets cornier as you go along.
IVE READ BELGARIOD... AGREE THAT IT WAS PRETTY SHALLOW AND I READ IT AFTER LOTR SO IT WAS SUCH A PALE RIPOFF IN COMPARISON
His Elenium and Tamuli series were a little better, but still far from Ice and Fire.
Tolkein, of course, but you've probably heard of him. :-)
Donaldson's Mirror of Her Dreams and A Man Rides through were good.
HAVENT READ THESE, WILL ADD TO MY LIST, THANKS!
Terry Brooks' Shanara series is supposed to be pretty good, and I think Anne McCaffery's Dragonriders of Pern series is considered to be among the classics, but I've never read either one.
READ SOME BROOKS AND FOUND IT SHALLOW LIKE EDDINGS. HAVE READ MCCAFFERY BUT NOT DRAGONRIDERS, AND THE TRILOGY I READ WAS OK BUT THE TONE WAS REALLY GOOFY. A GROUP OF REFUGES ON A NEW PLANET AT A TIME WHEN THE HUMAN RACE IS ENSLAVED BY ALIENS, AND THE BOOK SEEMED TO FOCUS ON HOW FUN BUILDING A CAMP WAS ON THE NEW PLANET AND EVERYONE WAS REALLY PEPPY WHICH FELT ODD GIVEN THE CIRCUMSTANCES OF THE SETTING.
Michael Moorcock's Elric series was very good, also very dark. It was kind of... I don't know... odd. Like you'd want to light up a bong and put on some Floyd while reading it.
HAVENT READ EITHER, ANOTHER FOR THE LIST, THANKS AGAIN!
There's another series of 2 or 3 books that I read a few years ago and really liked, but I can't for the life of me remember the author, the books, any characters names...
P.S. If you want to talk about a nag of a female character, you gotta love (as in hate) Cersei. She gets her on POV in Feast. Good stuff.
YEAH I LIKE CERSEI ACTUALLY. GRRM IS GOOD IN HOW THERE REALLY IS NO MAIN CHARACTER AND EVERYONE IS VERY EXCITING TO READ. RJ ON THE OTHERHAND HAS A DEFINATE CENTRAL CHARACTER TO THE PLOT, AND CHAPTER AFTER CHAPTER OF SOME OF THE FEMALE POV'S GOT AGGRAVATING ESPECIALLY WHEN THEY NAG SO MUCH THE TRUER HEROS OF THE STORY (MY OPINION)... ITS LIKE, SHUT YOUR MOUTH AND LET THEM SAVE THE DAY ALREADY... HEHE... BUT YOU'LL SEE OR HAVE A DIFFERENT OPINION ENTIRELY.
to you i recommend orson scott card... you've probably read ender's game but he has some really good fantasy too... the homecoming series (first book call of earth or memory of earth) was really good, and the alvin maker series is ok plotwise but the characters are incredible... i found a lot of humor and witty dialog in that series and enjoyed it immensely. anyways, thanks again for the list additions, will read feast of crows first, hopefully soon. glad to hear you're liking it... some reviews on amazon weren't stellar. -
Pass in date from shell script to java program
Hi,
I need to pass in some parameter to my java program.
eg 'java SomeProgram yyyy mm dd hh mm ss'
How do i use the shell script to generate the valeus for the year, mth day etc?
The program is running once everyday.
I tried $argu0 = `date+%y`
java SomeProgram $argu0
but not working... thanks for your help!Then, why would you want to use 'date' to provide
'now' to a Java program when you could just use new
java.util.Date() which probably makes the same call
as the Unix 'date' command?That works until you need to use a date other than 'now.'
public static final String ISO_DATE = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) {
SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat
.getDateTimeInstance();
sdf.applyPattern(ISO_DATE);
try {
Date d = sdf.parse(args[0]);
// rest of code here
} catch (ParseException e) {
// handle exception
}Users will have to enclose there input with quotes otherwise the JVM will consider their input as two parameters, or you can change the pattern to include a character between dd and HH. -
Accessing Sql Server from AS400 Java program
Hi everybody,
I am trying to access Sql Server from an AS400 Java program. I have tried various Sql Server JDBC drivers including the Microsoft one but no luck yet. When i try to compile my Java program (with driver file in the classpath) it gives some errors on the driver jar file and also it throws out lots of unreadable text characters. This gave me a feeling that probably its a character coding issue with the jar file, so i tried ftp the file in binary mode as well as copying through the Operations Navigator. But still compilation is giving the same kind of errors.
Do I need to have some special JDBC Drivers compiled for AS400 specifically. My understanding was that Java is platform independent so any JDBC Type 4 driver will work.
We are running Java 1.3 on the AS400. Any help on this issue would be great.
Thanks
InderThanks for the help. I am writing a Java program after a long time that's why was making that mistake. Now the program gets compiled correctly but on running the program i am getting the following error message:
java 001-0070: Exception JVAB544 not expected
/myjava/test/msbase.jar: 001-0050 Syntax error on Line 1: token ')' not expected
/myjava/test/msutil.jar: 001-0050 Syntax error on Line 1: token ')' not expected
/myjava/test/mssqlserver.jar: 001-0050 Syntax error on Line 1: token ')' not expected
I have no idea what is this error about. Though the same driver files don't give any error when running on a Windows machine.
Thanks -
Help needed on a TicTacToe java program
I am very new to java and our teacher has given us a program
that i am having quite a bit of trouble with. I was wondering if anyone could help me out.
This is the program which i have bolded.
{You will write a Java class to play the TicTacToe game. This program will have at least two data members, one for the status of the board and one to keep track of whose turn it is. All data members must be private. You will create a user interface that allows client code to play the game.
The user interface must include:
� Boolean xPlay(int num) which allows x to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
� Boolean oPlay(int num) which allows o to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
� Boolean isEmpty(int num) will check to see if the square labeled by num is empty.
� Void display() which displays the current game status to the screen.
� Char whoWon() which will return X, O, or C depending on the outcome of the game.
� You must not allow the same player to play twice in a row. Should the client code attempt to, xPlay or oPlay should print an error and do nothing else.
� Also calling whoWon when the game is not over should produce an error message and return a character other than X, O, or C.
� Client code for the moment is up to you. Assume you have two human players that can enter the number of the square in which they want to play.
Verifying user input WILL be done by the client code.}Hi,
This forum is exclusively for discussions related to Sun Java Studio Creator. Please post your question at the Java Programming forum. The URL to this forum is:
http://forum.java.sun.com/forum.jspa?forumID=31
Cheers
Giri -
Downloading unix archive file (.Z extension) from java program
Hi,
I am trying to download unix archive files with .Z extension from java program. When I use
BufferedReader zReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
and then read line by line and write it to file, downloaded file can't be decompressed. I tried to open it with winZip which supports .Z files but I get the message : Cannot open file, it does not appear to be a valid archive.
How can I download file correctly?
Any help would be appreciated.Hi,
I am trying to download unix archive files with .Z
extension from java program. When I use
BufferedReader zReader = new BufferedReader(new
InputStreamReader(urlConn.getInputStream()));
and then read line by line and write it to file,How are you writing the file? Since it is binary data you need to be careful about using Reader/Writers, which are meant for character data. Look at using classes from the InputStream/OutputStream hierarchy.
- N -
QuickTime installation breaks all Java programs.
There is a bug in the QuickTime installation program for Windows that causes all Java programs to fail whenever QuickTime is installed or updated. As part of the installation, QuickTime updates the system environment variable CLASSPATH to reference a Java .jar file needed by QuickTine in order to run properly. This reference is C:\Program Files\Java\jre1.6.0_01\lib\ext\QTJava.zip.
The problem is that in Windows, any file path that contains whitespace characters must be enclosed in quotation marks. This is because on the command line, Windows interprets any whitespace character to be a parameter seperator. So when Windows tries to resolve the file path, it resolves to two seperate paths, "C:\Program" and "Files\Java\jre1.6.0_01\lib\ext\QTJava.zip". This causes all Java applications to generate the following error: java.lang.NoClassDefFoundError: Files\Java\jre1/6/0_01\lib\ext\QTJava/zip.
The solution to this problem has been well known for years, is widely published, and is very simple to implement. Enclose the file path in quotation marks, so that the CLASSPATH entry is exactly as follows (including quotation marks) "C:\Program Files\Java\jre1.6.0_01\lib\ext\QTJava.zip". This tells Windows that everything inside the quotation marks is a single parameter, which then lets all Java applications run properly. Everytime there is a new version of QuickTime I have to field numerous complaints from co-workers that they can no longer run our Java applications. This bug has existed for at least two major release versions, 6.x and 7.x.
Please fix this bug.
Windows XP Pro
Windows XP ProA jar file does not have to be an installation program. The jar file can be your entire program neatly encased into one file. If you mess around with the manifest file, the jar file can be executed by double clicking on it.
Example: You have a program that you execute from the command line using: java Program
First, write a text file that has:
Main-Class: Tagssave it as manifest.txt. Make sure to put a blank line at the end of the file. Then, on the command line, type:
jar cvfm Prog.jar manifest.txt *.class
Done! Double click on Prog.jar and let me know if that is what you were looking for.
Brad -
How to get oc4j version from Java program
i have the following in my Java Program
Runtime r = Runtime.getRuntime();
Process p = r.exec("java -jar oc4j.jar version");
and then i try to read the InputStream from the Process p.
but this line is not executing, it returns the following error.
Unknown switch: ?version, type java -jar oc4j.jar -? for help
if i change it to ----------
Runtime r = Runtime.getRuntime();
Process p = r.exec("java -jar $ORACLE_HOME/j2ee/home/oc4j.jar version");
then i get another error :
Exception in thread "main" java.util.zip.ZipException: No such file or directory
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:112)
at java.util.jar.JarFile.<init>(JarFile.java:127)
at java.util.jar.JarFile.<init>(JarFile.java:65)
but if i cd to /oracle/j2ee/home and then run the command java -jar oc4j.jar version, then it gives me the right output with the right version, but for some reason the samething from inside the java program is giving me errors,
please help. i just need to read the oc4j version running on the server and display it in JSP.Process p = r.exec("java -jar oc4j.jar version");The character before "version" should be a hyphen; yours is not.
Process p = r.exec("java -jar $ORACLE_HOME/j2ee/home/oc4j.jar version");
then i get another error : Exception in thread "main"
java.util.zip.ZipException: No such file or directory
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:112)
at java.util.jar.JarFile.<init>(JarFile.java:127)
at java.util.jar.JarFile.<init>(JarFile.java:65)One more problem here: $ORACLE_HOME will be not be interpreted in the runtime.exec even if it is defined as an environment variable. So you get an error that tells you oc4j.jar is not found.
Hope this helps you.
Maybe you are looking for
-
How to ask for an array and how to save the values
I'm supposed to be learning the differences between a linear search and a binary search, and the assignment is to have a user input an array and search through the array for a given number using both searches. My problem is that I know how to ask the
-
Java 1.6.0_19 MD2withRSA is disabled issue
Some of our clients have been upgraded to the latest jre 1.6.0_19. They get the following exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorExce
-
When i run the below query i get the following error. ORA - 00904: t.associate_id : invalid identifier. SELECT t.product_id, t.associate_id, pd.status, CASE WHEN pd.status NOT IN ('DEAD', 'COMPLETED') THEN
-
No funciona camara lenta en mi ipad air 2 ya actualize a ios 8.1.1 y no se ha resuelto el problema, y ya restaure a valores de fabrica
-
Dreamweaver crashes and freezes
I have had the same issue just like some others with DW8 crashes when editing visually. I tried every folder in the apps folder and nothing worked. Mine crashed only when I use the php code not html or any other. It also crashed only on the index .ph