Try again when error occurs - java

I want to try 3 times when error happened.
What I have done so far....
public class TryTest {
public static void main(String[] args) {
TryTest test = new TryTest();
test.tryThis();
}
public void tryThis() {
int a = 10;
int x = 0;
int count = 1;
try {
System.out.println("Test " + count);
a = a / x;
System.out.println("Success !");
} catch (Exception e) {
if (count <= 3) {
// I want to try again with new x value
count++;
x++;
}
System.out.println("ERROR:\t" + e);
} finally {
System.out.println("Finish");
}
}
}
How can I do this?

Use a loop, which loops using you have a done values [0, 3)
for(int i = 0; i < 3; i++) {
try {
System.out.println("Test " + count);
int a = 10 / i;
System.out.println("Success !");
break;
} catch (Exception e) {
System.out.println("ERROR:\t" + e);
}
}
System.out.println("Finish");

Related

KeyListener Supposedly Calling upon other Key's code (JDBC)

I have a system so that you can press space to pause the simulation, and then arrows move the camera etc. and then if you press e, a JFrame pops up with a JTable inside it with the results from a SQL search of a connected database.
This works fine, I can close the JFrame and carry on running the simulation as usual, all the buttons and functions work.
The problem is after 20 seconds, the system takes the collected data and writes this data to the end of the database, which is fine, that works it writes to the end if the data is not already their. However if I press e to open the table, and then close the table, when returning to the simulation screen whatever button I press that has a listener attached to it, will just keep opening new tables, and I am stumped as to the reason why.
Any solution that would allow for when I close this JFrame for my key's to begin to function the way they did before writing to the file, would be greatly appreciated.
Here are the relevant pieces of code (let me know if there is any more you may need)
public void databaseConnector(boolean read){
try{
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/Outputs", "Sam", "sam");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT INDEX FROM SHM";
ResultSet rs = st.executeQuery(sql);
int len = 0;
while(rs.next()) {
len++;
}
if (read){
databaseReader(st, len);
} else {
double data[] = {modulus[0] , natural[0], modulus[1], natural[1], length, startPosition, endPosition, amplitude, equilibrium};
for (int i = 4; i < data.length; i++){
data[i] /= 100;
}
PreparedStatement sqls = con.prepareStatement( "SELECT * FROM SHM WHERE " + columnNames[1] + " = " + data[0] + " AND " + columnNames[2] + " = " + data[1] + " AND "
+ columnNames[3] + " = " + data[2] + " AND " + columnNames[4] + " = " + data[3] + " AND "
+ columnNames[5] + " = " + data[4] + " AND " + columnNames[6] + " = " + data[5]);
databaseWriter(st, len, sqls, data);
}
st.close();
con.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void databaseReader(Statement st, int len){
try{
Object[][] data;
//Get data from table and convert to 2D array
data = new Object[len][columnNames.length];
String sql = "SELECT * FROM SHM";
ResultSet rs = st.executeQuery(sql);
int x = 0;
while (rs.next()){
for(int i = 0; i < columnNames.length; i++){
data[x][i] = new Double(rs.getDouble(columnNames[i]));
}
x++;
}
rs.close();
//Output data
JFrame frame = new JFrame("Table");
TableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setAlwaysOnTop(true);
frame.pack();
frame.setVisible(true);
} catch (Exception e){
System.err.println(e.getMessage());
}
}
public void databaseWriter(Statement st, int len, PreparedStatement sql, double[] data){
try{
//checker
ResultSet rs = sql.executeQuery();
if (!rs.next()){ //if not empty then
rs = st.executeQuery("SELECT * FROM SHM");
rs.moveToInsertRow();
rs.updateInt(columnNames[0],len + 1);
for (int i = 0; i < data.length; i++) {
rs.updateDouble(columnNames[i+1],data[i]);
}
rs.insertRow();
}
rs.close();
} catch (Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
public void gravity(){
if (moving){
double force = tension();
Player.ha = force / Player.mass;
Player.hSpeed += Player.ha * delta / 60;
//}
Player.vSpeed += Player.va;
Player.move(1, (int) (Player.hSpeed * delta));
if (milliSecondTimer < 20){
calculationChecker();
}
if (milliSecondTimer > 20 && !hasWritten){
endPosition = (int) (maxX - rect.get(0).getMaxX());
databaseConnector(false);
hasWritten = true;
}
} else {
milliSecondTimer = 0;
hasWritten = false;
amplitude = 0;
equilibrium = 0;
MaxX = new ArrayList<Integer>();
MinX = new ArrayList<Integer>();
Equilibrium = new ArrayList<Integer>();
Player.hSpeed = 0;
Player.ha = 0;
}
}
public class MyKeyListener implements KeyListener{
public void action(){
int s = 4;
if (keysDown.contains(KeyEvent.VK_SHIFT)){
s = 10;
} else {
s = 4;
}
if (keysDown.contains(KeyEvent.VK_UP) /*|| keysDown.contains(KeyEvent.VK_W)*/){
scaleChange = true;
moverY += 10;
}
if (keysDown.contains(KeyEvent.VK_RIGHT) /*|| keysDown.contains(KeyEvent.VK_D)*/){
if (!moving) {
Player.move(1,s);
right = true;
} else {
moverX -= 10;
}
}
if (keysDown.contains(KeyEvent.VK_DOWN) /*|| keysDown.contains(KeyEvent.VK_S)*/){
scaleChange = true;
moverY -= 10;
}
if (keysDown.contains(KeyEvent.VK_LEFT) /*|| keysDown.contains(KeyEvent.VK_A)*/){
if (!moving) {
Player.move(3,s);
right = false;
} else {
moverX += 10;
}
}
if (keysDown.contains(KeyEvent.VK_E)){
databaseConnector(true);
}
if (keysDown.contains(KeyEvent.VK_SPACE)){
Player.ha = 0;
Player.va = 0;
Player.vSpeed = 0;
Player.hSpeed = 0;
if (!moving){
modulus[0] = mod1.getValue();
modulus[1] = mod2.getValue();
natural[0] = len1.getValue();
natural[0] /= 10;
natural[1] = len2.getValue();
natural[1] /= 10;
setRectangles();
startPosition = (int) (Player.getCenterX() - rect.get(0).getMaxX());
}
moving = !moving;
}
if (keysDown.contains(KeyEvent.VK_EQUALS)){
scaleScreen += 1;
scaleChange = true;
}
if (keysDown.contains(KeyEvent.VK_SLASH)){
scaleScreen -= 1;
if(scaleScreen == 0){
scaleScreen = 1;
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode())){
keysDown.add(e.getKeyCode());
}
action();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
}

SVM Predict reading datatest

I have such a big problem with implementation the svm_predict function. I have trained svm, and prepare datatest. Both files are in .txt. file.Datatest are from LBP( Local Binary patterns) and it looks like:
-0.6448744548418511
-0.7862774302452588
1.7746263060948377
I'm loading it to the svm_predict function and at my console after compiling my program there is:
Accuracy = 0.0% (0/800) (classification)
So it's look like it can't read datatest?
import libsvm.*;
import java.io.*;
import java.util.*;
class svm_predict {
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
private static void predict(BufferedReader input, DataOutputStream output, svm_model model, int predict_probability) throws IOException
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
int svm_type=svm.svm_get_svm_type(model);
int nr_class=svm.svm_get_nr_class(model);
double[] prob_estimates=null;
if(predict_probability == 1)
{
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="+svm.svm_get_svr_probability(model)+"\n");
}
else
{
int[] labels=new int[nr_class];
svm.svm_get_labels(model,labels);
prob_estimates = new double[nr_class];
output.writeBytes("labels");
for(int j=0;j<nr_class;j++)
output.writeBytes(" "+labels[j]);
output.writeBytes("\n");
}
}
while(true)
{
String line = input.readLine();
if(line == null) break;
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
double target = atof(st.nextToken());
int m = st.countTokens()/2;
svm_node[] x = new svm_node[m];
for(int j=0;j<m;j++)
{
x[j] = new svm_node();
x[j].index = atoi(st.nextToken());
x[j].value = atof(st.nextToken());
}
double v;
if (predict_probability==1 && (svm_type==svm_parameter.C_SVC || svm_type==svm_parameter.NU_SVC))
{
v = svm.svm_predict_probability(model,x,prob_estimates);
output.writeBytes(v+" ");
for(int j=0;j<nr_class;j++)
output.writeBytes(prob_estimates[j]+" ");
output.writeBytes("\n");
}
else
{
v = svm.svm_predict(model,x);
output.writeBytes(v+"\n");
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Mean squared error = "+error/total+" (regression)\n");
System.out.print("Squared correlation coefficient = "+
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+
" (regression)\n");
}
else
System.out.print("Accuracy = "+(double)correct/total*100+
"% ("+correct+"/"+total+") (classification)\n");
}
private static void exit_with_help()
{
System.err.print("usage: svm_predict [options] test_file model_file output_file\n"
+"options:\n"
+"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n");
System.exit(1);
}
public static void main(String argv[]) throws IOException
{
int i, predict_probability=0;
// parse options
for(i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
++i;
switch(argv[i-1].charAt(1))
{
case 'b':
predict_probability = atoi(argv[i]);
break;
default:
System.err.print("Unknown option: " + argv[i-1] + "\n");
exit_with_help();
}
}
if(i>=argv.length-2)
exit_with_help();
try
{
BufferedReader input = new BufferedReader(new FileReader(argv[i]));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(argv[i+2])));
svm_model model = svm.svm_load_model(argv[i+1]);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
System.out.print("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
catch(FileNotFoundException e)
{
exit_with_help();
}
catch(ArrayIndexOutOfBoundsException e)
{
exit_with_help();
}
}
}
It's difficult to know becasue its a big process
make sure you follow their classification guide
the data should be scaled it seems it goes above 1 right now

java image processing sobel edge detection

I have a problem with java program, in which i'm using sobel operator for edge detection, but when I'm trying to use that funcion, console says:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 262144
at sun.awt.image.ByteInterleavedRaster.getPixels(ByteInterleavedRaster.java:1015)
at Obrazek.jButtonSobelActionPerformed(Obrazek.java:566)
And the code for that is:
FileInputStream inFile = null;
try {
long beginTime = (new java.util.Date()).getTime();
int i, j;
double Gx[][], Gy[][], G[][];
inFile = new FileInputStream("D://lenacsmall.bmp");
BufferedImage bi = ImageIO.read(inFile);
int width = bi.getWidth();
int height = bi.getHeight();
int[] pixels = new int[width * height];
int[][] output = new int[width][height];
int[] raster = bi.getRaster().getPixels(0,0,width,height,pixels);
int counter = 0;
for(i = 0 ; i < width ; i++ )
{
for(j = 0 ; j < height ; j++ )
{
output[i][j] = pixels[counter];
counter = counter + 1;
}
}
Gx = new double[width][height];
Gy = new double[width][height];
G = new double[width][height];
for (i=0; i<width; i++) {
for (j=0; j<height; j++) {
if (i==0 || i==width-1 || j==0 || j==height-1)
Gx[i][j] = Gy[i][j] = G[i][j] = 0;
else{
Gx[i][j] = output[i+1][j-1] + 2*output[i+1][j] + output[i+1][j+1] -
output[i-1][j-1] - 2*output[i-1][j] - output[i-1][j+1];
Gy[i][j] = output[i-1][j+1] + 2*output[i][j+1] + output[i+1][j+1] -
output[i-1][j-1] - 2*output[i][j-1] - output[i+1][j-1];
G[i][j] = Math.abs(Gx[i][j]) + Math.abs(Gy[i][j]);
}
}
}
counter = 0;
for(int ii = 0 ; ii < width ; ii++ )
{
for(int jj = 0 ; jj < height ; jj++ )
{
pixels[counter] = (int) G[ii][jj];
counter = counter + 1;
}
}
BufferedImage outImg = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
outImg.getRaster().setPixels(0,0,width,height,pixels);
FileOutputStream outFile = null;
try {
outFile = new FileOutputStream("D://copyTop.bmp");
} catch (FileNotFoundException ex) {
}
try {
ImageIO.write(outImg,"BMP",outFile);
} catch (IOException ex) {
}
JFrame TheFrame = new JFrame("obrazek " + width + " " + height);
JLabel TheLabel = new JLabel(new ImageIcon(outImg));
TheFrame.getContentPane().add(TheLabel);
TheFrame.setSize(600, 600);
TheFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
TheFrame.setVisible(true);
} catch (FileNotFoundException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inFile.close();
} catch (IOException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'm really need some help. I hope someone will answer for that post, thank you.
Greetings :)
Try this, edge detection using sobel approach, I just did this yesterday.
`
static BufferedImage inputImg,outputImg;
static int[][] pixelMatrix=new int[3][3];
public static void main(String[] args) {
try {
inputImg=ImageIO.read(new File("your input image"));
outputImg=new BufferedImage(inputImg.getWidth(),inputImg.getHeight(),TYPE_INT_RGB);
for(int i=1;i<inputImg.getWidth()-1;i++){
for(int j=1;j<inputImg.getHeight()-1;j++){
pixelMatrix[0][0]=new Color(inputImg.getRGB(i-1,j-1)).getRed();
pixelMatrix[0][1]=new Color(inputImg.getRGB(i-1,j)).getRed();
pixelMatrix[0][2]=new Color(inputImg.getRGB(i-1,j+1)).getRed();
pixelMatrix[1][0]=new Color(inputImg.getRGB(i,j-1)).getRed();
pixelMatrix[1][2]=new Color(inputImg.getRGB(i,j+1)).getRed();
pixelMatrix[2][0]=new Color(inputImg.getRGB(i+1,j-1)).getRed();
pixelMatrix[2][1]=new Color(inputImg.getRGB(i+1,j)).getRed();
pixelMatrix[2][2]=new Color(inputImg.getRGB(i+1,j+1)).getRed();
int edge=(int) convolution(pixelMatrix);
outputImg.setRGB(i,j,(edge<<16 | edge<<8 | edge));
}
}
File outputfile = new File("your output image");
ImageIO.write(outputImg,"jpg", outputfile);
} catch (IOException ex) {System.err.println("Image width:height="+inputImg.getWidth()+":"+inputImg.getHeight());}
}
public static double convolution(int[][] pixelMatrix){
int gy=(pixelMatrix[0][0]*-1)+(pixelMatrix[0][1]*-2)+(pixelMatrix[0][2]*-1)+(pixelMatrix[2][0])+(pixelMatrix[2][1]*2)+(pixelMatrix[2][2]*1);
int gx=(pixelMatrix[0][0])+(pixelMatrix[0][2]*-1)+(pixelMatrix[1][0]*2)+(pixelMatrix[1][2]*-2)+(pixelMatrix[2][0])+(pixelMatrix[2][2]*-1);
return Math.sqrt(Math.pow(gy,2)+Math.pow(gx,2));
}
`
In your for loops when you check
if (i==0 || i==width-1 || j==0 || j==height-1)
you should probably be checking for i >= width-2 rather than i==width-1.
For example, if width is 10 it falls into the statement if i == 9.
you want to catch if i == 8 since you later check [i+1], which in your code would be out of the bounds of your image array, since the maximum you can have is 9 (width-1).
Obviously the same applies for j.

Java - Reading files into array

I want to save a library for a small scale java application which stores technical manuals. Right now I am able to save the library to an external file but I am unable to load it back into the library itself, currently "-1" just gets printed to the console.
How can I solve this?
Here is my code:
//Choice 7: Load Library:
if(Menu.menuChoice == 7){
boolean loadYesNo = Console.readYesNo("\n\nThe manualKeeper app is able to load and display any 'Library.txt' files \nfound in your home folder directory.\n\nWould you like to load and display library? (Y/N):\n");
String fileName = "Library.bin";
if(loadYesNo==true){
try {
FileInputStream fileIs = new FileInputStream(fileName);
ObjectInputStream is = new ObjectInputStream(fileIs);
int x = is.read();
System.out.println(x);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Menu.displayMenu();
}
else if(loadYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not loaded!\n");
System.out.println("--------------------------------------------------------------------------\n");
Menu.displayMenu();
}
}
//Choice 0: Exit the program:
if(Menu.menuChoice == 0){
if(Menu.menuChoice == 0){
if(Library.ManualList.size() > 0){
boolean saveYesNo = Console.readYesNo("\nThe manualKeeper app is able to save your current library to a '.txt' \nfile in your home folder directory (C:\\Users\\ 'YOUR NAME').\n\nWould you like to save the current library? (Y/N):\n");
String fileName = "Library.bin";
if(saveYesNo==true){
try {
FileOutputStream fileOs = new FileOutputStream(fileName);
ObjectOutputStream os = new ObjectOutputStream(fileOs);
for (int i = 0; i < Library.ManualList.size(); i++){
os.writeObject(Library.ManualList.get(i).displayManual());
os.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE WRITING!");
} else if(saveYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not saved!\n");
System.out.println("--------------------------------------------------------------------------\n");
break exit;
}
Menu.displayMenu();
}else if(Library.ManualList.isEmpty()){
Menu.displayMenu();
}
}
}
}
System.out.println("\n ~ You have exited the manualKeeper app! ~ ");
System.out.println("\n Developed by Oscar Moore - 2014 - UWL\n");
System.out.println("\n <3\n");
}
}
Here is also my library class:
package library;
import java.util.ArrayList;
public class Library {
public static int ManualChoice;
static String returnManualTitle;
static String status1 = "Available";
static String status2 = "Borrowed";
public static ArrayList<Manual> ManualList = new ArrayList<Manual>();
static ArrayList<Manual> borrowedManuals = new ArrayList<Manual>();
static void addManual(){
Manual newManual = new Manual();
newManual.createManual();
ManualList.add(newManual);
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Manual added to library!\n");
System.out.println("--------------------------------------------------------------------------\n");
}
static void displayManualList(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
System.out.printf("\n\nHere are the Manual/s currently stored in the library:\n\n\n");
for (int i = 0; i < ManualList.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(ManualList.get(i).displayManual());
System.out.println("---------------------------------------------------------\n");
}
}
}
static void displayBorrowedManuals(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
for (int i = 0; i < borrowedManuals.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(borrowedManuals.get(i).displayManual());
System.out.println("---------------------------------------------------------");
}
}
}
public static void borrowManual(){
displayManualList();
ManualChoice = (Console.readInteger(Messages.enterManualIndexMessage, Messages.ManualIndexNotInListMessage, 0, Library.ManualList.size() - 1));
borrowLoop:
while(Menu.menuChoice == 3){
if ((ManualList.get(ManualChoice).status.equalsIgnoreCase(status1)) && (ManualList.size() >= ManualChoice)){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n Manual borrowed!\n");
System.out.println("--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualList.get(ManualChoice).status.equalsIgnoreCase(status2) && ManualList.size() >= ManualChoice){
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n "
+ " The Manual you wish to borrow is already on loan.");
System.out.println("\n--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualChoice > ManualList.size()-1){
System.out.println(Messages.noSuchManualMessage);
break borrowLoop;
}
if(ManualList.size() > 1){
displayManualList();
}
else if(ManualList.size() == 1){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.printf("\n\n %s\n\n", ManualList.get(ManualChoice).displayManual());
System.out.println("Please return the Manual within two weeks!\n");
displayManualList();
}
}
Menu.displayMenu();
}
static void returnManual(){
System.out.printf("\n\nHere are the Manual/s currently out on loan:\n\n");
if(borrowedManuals.size() > 0){
for (int i = 0; i < borrowedManuals.size(); i++)
System.out.println(borrowedManuals.get(i).displayManual());
returnManualTitle = Console.readString(Messages.enterManualSerial, Messages.tooShortMessage, 3);
}
int x = 0;
boolean serialExistance = false;
while (x < ManualList.size()){
if (ManualList.get(x).serial.equalsIgnoreCase(returnManualTitle)){
ManualList.get(x).status = "Available";
ManualList.get(x).borrower = "N/A";
ManualList.get(x).borrowDate = "N/A";
ManualList.get(x).returnDate = "N/A";
int p = 0;
while (p < borrowedManuals.size()) {
Manual borrowed = borrowedManuals.get(p);
if (borrowed.serial.equalsIgnoreCase(returnManualTitle)) {
borrowedManuals.remove(p);
break;
}
p++;
}
System.out.println(Messages.successReturnMessage);
serialExistance = true;
break;
}
x = x+1;
}
if(serialExistance == false){
boolean repeatReturnManual = Console.readYesNo("\n--------------------------------------------------------------------------" + "\n\nThe Manual with the serial "+"\""+returnManualTitle +"\""+ " wasn't found!"
+"\n\nDo you want to try again? (Y/N):\n");
System.out.println("\n--------------------------------------------------------------------------");
if(repeatReturnManual){
returnManual();
}
}else if(serialExistance){
Menu.menuChoice = 8;
}
}
public static void removeManual(){
if(ManualList.size() >0){
displayManualList();
ManualChoice = Console.readInteger(Messages.enterRemoveManualIndex ,Messages.ManualIndexNotInListMessage, 0, ManualList.size());
int p = 0;
while (p < borrowedManuals.size()){
if (borrowedManuals.get(p).title.equalsIgnoreCase(returnManualTitle)){
borrowedManuals.remove(p);
}
}
ManualList.remove(ManualChoice);
System.out.print(Messages.successRemovedManualMessages);
Menu.menuChoice = 8;
}
}
static void emptyLibrary(){
System.out.println("\n WARNING!");
System.out.println("\n You have chosen to delete all Manuals in the library.\n");
System.out.println("--------------------------------------------------------------------------");
boolean emptyLibraryChoice = Console.readYesNo("\nAre you sure you wish to destroy the library? (Y/N): \n");
System.out.println("\n--------------------------------------------------------------------------\n");
if(emptyLibraryChoice){
Library.ManualList.clear();
System.out.println(Messages.successEmptyLibraryMesssage);
System.out.println("--------------------------------------------------------------------------\n");
Menu.menuChoice = 8;
}
}
}
You are using ObjectInputStream not in the intended manner. The correct way would be like:
ObjectInputStream is = new ObjectInputStream(fileIs);
Library x = (Library) is.readObject(); // change Library to the type of object you are reading
System.out.println(x);
You probably need to change Library, but I could not find out, what type of object you are reading.

Loading contact from phone book in J2ME

I implemented this code below in order to read contacts from the addressbook of the phone
The problem is, In a case when all the numbers in the phonebook are saved in the SIM it reads and displays the contacts for selection.
But in a case whereby any number is included on the phone memory, it gives an application error.(OutOfMemoryException)
What do I do (PS do not mind some System.out.println statements there. I used them for debugging)
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i] + " " + allContactLists[1]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute() error");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
// ----
// System.out.println("loadErr1");
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// System.out.println(contactList.getName());//--Phone Contacts or Sim Contacts
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME)
&& contactList.isSupportedField(Contact.TEL)) {
// ContactLst.append("Reading contacts...", null);
// System.out.println("sup1");
Enumeration items = contactList.items();
// System.out.println("sup2");
Vector telNumbers = new Vector();
telNames = new Vector();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
// System.out.println(telCount);
// System.out.println(nameCount);
// we're only interested in contacts with a phone number
// nameCount should always be > 0 since FORMATTED_NAME is
// mandatory
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone numbers
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
System.out.println(telNumber + " " + "tel");
// check if ATTR_MOBILE is supported
if (contactList.isSupportedAttribute(Contact.TEL, Contact.ATTR_MOBILE)) {
if ((telAttributes & Contact.ATTR_MOBILE) != 0) {
telNames.insertElementAt(telNames, i);
telNumbers.insertElementAt(telNumber, i);
} else {
telNumbers.addElement(telNumber);
telNames.addElement(telNames);
}
}
// else {
//// telNames.addElement(contactName);
// telNumbers.addElement(telNumber);
// }
System.out.println("telephone nos");
}
// Shorten names which are too long
shortenName(contactName, 20);
for (int i = 0; i <= telNumbers.size(); i++) {
System.out.println(contactName + " here " + telNames.size());
telNames.addElement(contactName);
System.out.println(telNames.elementAt(i) + " na " + i);
}
names = new String[telNames.size()];
for (int j = 0; j < names.length; j++) {
names[j] = (String) telNames.elementAt(j);
System.out.println(names[j] + "....");
}
// allTelNames.addElement(telNames);
System.out.println("cap :" + telNames.size() + " " + names.length);
// telNames.removeAllElements();
// telNumbers.removeAllElements();
}
}
available = true;
} else {
// ContactLst.append("Contact list required items not supported", null);
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}

Categories

Resources