Boolean Datatype declaration in PowerBuilder...Please HELP
Hi,
I have Oracle Stored procedure with last parameter as boolean, When I am calling this stored procedure in
PowerBuilder 6.5 in the DECLARE I am getting compilation error and it is not working...
I heard that there is some round about way to solve this problem...
Any one knows the solution...please help me out...
I don't know about PowerBuilder but we had a similar problem with Java not understanding Oracle's BOOLEAN implementation. I'm afraid we solved this by substituting a VARCHAR2 parameter with values of 'TRUE' and 'FALSE'. Not very elegant I'm afraid, but if your stored procedure is in a package you can at least overload it.
cheers, APC
Similar Messages
-
SAXParser type declaration not found - PLEASE HELP!!
I am using XML to parse an incoming string of XML. I want to use an SAXParser to do this, but I cannot create an object of this type. I have the jar file jaxp.jar, xalan.jar, and crimson.jar in my classpath.
Is there anything else that I need to do in order to get the parser to work.
This is a very urgent need so any help is appreciated. Here is the error:
Class SAXParser not found in type declaration;I have figured out the issue. Thanks for the help. I do have one more issue though. I am trying to parse a string of xml data and I need to pass my parse() method an InputSource object that I guess I will make from my incoming String.
Any thoughts on how to do this? -
Please help me, boolean function
Hello everyone, this is my first post in this forum. I have this function but I cant get it to work because I get this "missing return statement". Im desperate now, I cant figure how to fix it. Please help me.
public static boolean es(String inst) { // Verificador de validez
int ad=inst.indexOf("ADELANTE");
int at=inst.indexOf("ATRAS");
int iz=inst.indexOf("IZQUIERDA");
int de=inst.indexOf("DERECHA");
int bo=inst.indexOf("BORRAR");
int ho=inst.indexOf("HOGAR");
double numero;
try {
if ((ad==0)&&(inst.charAt(8)==' ')) {
numero = Double.parseDouble(inst.substring(9));
if (numero>0)
return true;
else return false;
if ((at==0)&&(inst.charAt(5)==' ')) {
numero = Double.parseDouble(inst.substring(6));
if (numero>0)
return true;
else return false;
if ((iz==0)&&(inst.charAt(9)==' ')) {
numero = Double.parseDouble(inst.substring(10));
if ((numero>0)&&(numero<360))
return true;
else return false;
if ((de==0)&&(inst.charAt(7)==' ')) {
numero = Double.parseDouble(inst.substring(8));
if ((numero>0)&&(numero<360))
return true;
else return false;
if (bo==0) return true;
if (ho==0) return true;
else return false;
catch (NumberFormatException ex) {
}The objective of this function is to check if the user entered one of these words: "adelante", "atras", "izquierda" or "derecha" followed by a positive number. Thank you in advance for your help.you need to have a return statement at the very end of you method.
here's a rewrite of what you provided...instead of a bunch of returns everywhere, i set a variable to return. i also put else if statements instead of if since you only want to see if one of the instances exist
public static boolean es(String inst) { // Verificador de validez
int ad=inst.indexOf("ADELANTE");
int at=inst.indexOf("ATRAS");
int iz=inst.indexOf("IZQUIERDA");
int de=inst.indexOf("DERECHA");
int bo=inst.indexOf("BORRAR");
int ho=inst.indexOf("HOGAR");
double numero;
boolean answer = false;
try {
if ((ad==0)&&(inst.charAt(8)==' ')) {
numero = Double.parseDouble(inst.substring(9));
if (numero>0)
answer = true;
else answer = false;
else if ((at==0)&&(inst.charAt(5)==' ')) {
numero = Double.parseDouble(inst.substring(6));
if (numero>0)
answer = true;
else answer = false;
else if ((iz==0)&&(inst.charAt(9)==' ')) {
numero = Double.parseDouble(inst.substring(10));
if ((numero>0)&&(numero<360))
answer = true;
else answer = false;
else if ((de==0)&&(inst.charAt(7)==' ')) {
numero = Double.parseDouble(inst.substring(8));
if ((numero>0)&&(numero<360))
answer = true;
else answer = false;
else if (bo==0) answer = true;
else if (ho==0) answer = true;
else answer = false;
catch (NumberFormatException ex) {
answer = false;
return answer;
Message was edited by:
muzic -
SQL Server 2012 Time(7) DataType values Comparison giving wrong result. Please help
We have a Table with StartTime and EndTime columns in Time(7) datatype, so we want to count the rows for each hour from 6 AM to 5 AM. If a record in table is as StartTime= 7 PM to EndTime = 5 AM (a shift of an employee) then the result is wrong beacause
being time(7) datatype the EndTime(5AM)< StartTime(7PM) in 24 hours format so following query gives wrong results.
select
* from EmpSchedule
where (StartTime>='19:00:00.0000000'
OR EndTime>='19:00:00.0000000')
Please help me out. ThanksDECLARE @clockIns TABLE (employeeID INT, startDateTime DATETIME, endDateTime DATETIME)
INSERT INTO @clockIns (employeeID, startDateTime, endDateTime)
VALUES
(1, '2014-07-01 19:01:00.000', '2014-07-02 04:27:00.000'),
(2, '2014-07-01 18:01:00.000', '2014-07-02 05:27:00.000'),
(3, '2014-07-01 19:01:00.000', '2014-07-02 05:27:00.000'),
(4, '2014-07-01 18:01:00.000', '2014-07-02 04:27:00.000')
SELECT *
FROM @clockIns
WHERE datepart(HOUR,startDateTime) BETWEEN 19 AND 23
OR datepart(HOUR,startDateTime) BETWEEN 0 AND 4
OR datepart(HOUR,endDateTime) BETWEEN 19 AND 23
OR datepart(HOUR,endDateTime) BETWEEN 0 AND 4
Try this out. -
Please help, java program terminating unexpectedly without reason
ok, so I have a project I'm working on, here's its description:
Create a new project named FML_Pig where F is your first initial, M is your middle initial, and L is your last initial. For example, if your name is Alfred Edward Neuman then you would name your project AEN_Pig. If necessary, add a new Java file to this project named FML_Pig.
Add a java file to the project named FML_Dice.
Design and implement a Dice class as follows. The Dice class has 2 twenty‑sided dice with numbers on the faces (1 � 20) and 2 twenty-six-sided dice with letters on the faces (a � z).
import java.util.Random;
public class FML_Dice
private static Random gen = new Random();
private final static int NUM_SIDES = 20;
private int die1, die2, numSnakeEyes, numVowels, totalPoints;
private char die3, die4;
Part 1
Add a rollDice() method to your FML_Dice class that sets die1 and die2 to a random number between 1 and 20 and it sets die3 and die4 to a random character between �a� and �z�.
Helpful Hint:
dice3 = (char)(�a� + gen.nextInt(26)); // sets dice3 to a random char between �a� and �z�.
Part 2
Write a constructor that sets die1 and die2 to a random number between 1 and 20 and it sets die3 and die4 to a random character. Your constructor can simply call rollDice() to do this. It should also initialize numSnakeEyes, numVowels, and totalPoints to 0 (after you roll the dice).
Part 3
Write methods getDie1(), getDie2(), getDie3(), and getDie4() that returns the value of the respective die. Write a method numSnakes() that returns the number of snake eyes that have been rolled. Write a method numVowels() that returns the number of vowels that have been rolled. Write a method totalPts() that returns the totalPoints.
Part 4
Write a toString() method that overwrites the default toString() method. It should return a String representation of the value of all 4 die. For example, 17 2 h w.
Part 5
Write a method updateTotals that updates numVowels, numSnakeEyes, and totalPoints based on the current values of die1, die2, die3, and die4. numVowels should be incremented by 1 if either die3 or die4 are a vowel. However, if both die3 and die4 are vowels, the totalPoints should be reset to 0 and numVowels should be reset to 0 also. numSnakeEyes should be incremented by 1 if either die1 or die2 have a face value of 1 (this is not truly a snake eyes, but it gives better odds for the game). totalPoints should be incremented by the sum of die1 and die2 multiplied by (numSnakeEyes + 1).
Part 6
Write a main program (use the one in FML_Pig.java) that plays a game of Pig. In this game, two people play against each other. Player1 begins by rolling the dice. The total of die1 and die2 is added to his total score. Player1�s turn continues until he/she rolls a total of 4 vowels then the turn switches to Player2. Whenever a turn switches to the other player, the number of vowels is reset to zero. Also, if at any time both die3 and die4 are vowels, the total score is reset to 0 and the turn switches to the other player. (So the turn switches to the other player whenever the total number of vowels reaches four or there are two vowels rolled at the same time.)
If a player rolls snakeeyes (for our game, snakeeyes occurs whenever either of the dice have a face value of one � in reality, both die1 and die2 should have a face value of one but then snakeeyes would occur only once every 400 rolls), then his point values are doubled from that point on (all future rolls for the rest of the game, point values for this player are doubled). When a player rolls snake eyes again, point values are tripled for that roll and all future rolls. (Three snake eyes, quadrupled, etc.)
(continued on the next page)
Be sure to display the results of the roll for each turn.
First player to get to 2000 points wins the game and gets to oink like a pig.
Note: Both players need their own set of Dice since the Dice keeps track of the totalPoints, the number of snake eyes rolled so far, and the number of vowels rolled so far for that particular player. You can do this simply by declaring it that way in the main program:
Dice player1 = new Dice();
Dice player2 = new Dice();
You may add additional methods and instance variables to the class as needed. For example, I would probably write a private helper method isVowel() that is passed a char argument ch and returns true if ch is a vowel.
Also, you can have the computer play for both player 1 and player 2. Simply loop it until somebody wins. Print out the result for each turn including who rolled the dice (player 1 or player 2), what they rolled, how many snakeeyes do they have, how many points did they get for this turn, and how many total points do they have.
When you are completely finished, hand in just the java files (FLM_Dice & FLM_Pig). If you happened to write any other classes, make sure they are named with the FML format, and turn these in as well. I do not need EasyReader or p.
Oink! Oink!
This pig won the game --------->
so here's my code:
this isn't my code but is required to compile my code: // package com.skylit.io;
import java.io.*;
* @author Gary Litvin
* @version 1.2, 5/30/02
* Written as part of
* <i>Java Methods: An Introduction to Object-Oriented Programming</i>
* (Skylight Publishing 2001, ISBN 0-9654853-7-4)
* and
* <i>Java Methods AB: Data Structures</i>
* (Skylight Publishing 2003, ISBN 0-9654853-1-5)
* EasyReader provides simple methods for reading the console and
* for opening and reading text files. All exceptions are handled
* inside the class and are hidden from the user.
* <xmp>
* Example:
* =======
* EasyReader console = new EasyReader();
* System.out.print("Enter input file name: ");
* String fileName = console.readLine();
* EasyReader inFile = new EasyReader(fileName);
* if (inFile.bad())
* System.err.println("Can't open " + fileName);
* System.exit(1);
* String firstLine = inFile.readLine();
* if (!inFile.eof()) // or: if (firstLine != null)
* System.out.println("The first line is : " + firstLine);
* System.out.print("Enter the maximum number of integers to read: ");
* int maxCount = console.readInt();
* int k, count = 0;
* while (count < maxCount && !inFile.eof())
* k = inFile.readInt();
* if (!inFile.eof())
* // process or store this number
* count++;
* inFile.close(); // optional
* System.out.println(count + " numbers read");
* </xmp>
public class EasyReader
protected String myFileName;
protected BufferedReader myInFile;
protected int myErrorFlags = 0;
protected static final int OPENERROR = 0x0001;
protected static final int CLOSEERROR = 0x0002;
protected static final int READERROR = 0x0004;
protected static final int EOF = 0x0100;
* Constructor. Prepares console (System.in) for reading
public EasyReader()
myFileName = null;
myErrorFlags = 0;
myInFile = new BufferedReader(
new InputStreamReader(System.in), 128);
* Constructor. opens a file for reading
* @param fileName the name or pathname of the file
public EasyReader(String fileName)
myFileName = fileName;
myErrorFlags = 0;
try
myInFile = new BufferedReader(new FileReader(fileName), 1024);
catch (FileNotFoundException e)
myErrorFlags |= OPENERROR;
myFileName = null;
* Closes the file
public void close()
if (myFileName == null)
return;
try
myInFile.close();
catch (IOException e)
System.err.println("Error closing " + myFileName + "\n");
myErrorFlags |= CLOSEERROR;
* Checks the status of the file
* @return true if en error occurred opening or reading the file,
* false otherwise
public boolean bad()
return myErrorFlags != 0;
* Checks the EOF status of the file
* @return true if EOF was encountered in the previous read
* operation, false otherwise
public boolean eof()
return (myErrorFlags & EOF) != 0;
private boolean ready() throws IOException
return myFileName == null || myInFile.ready();
* Reads the next character from a file (any character including
* a space or a newline character).
* @return character read or <code>null</code> character
* (Unicode 0) if trying to read beyond the EOF
public char readChar()
char ch = '\u0000';
try
if (ready())
ch = (char)myInFile.read();
catch (IOException e)
if (myFileName != null)
System.err.println("Error reading " + myFileName + "\n");
myErrorFlags |= READERROR;
if (ch == '\u0000')
myErrorFlags |= EOF;
return ch;
* Reads from the current position in the file up to and including
* the next newline character. The newline character is thrown away
* @return the read string (excluding the newline character) or
* null if trying to read beyond the EOF
public String readLine()
String s = null;
try
s = myInFile.readLine();
catch (IOException e)
if (myFileName != null)
System.err.println("Error reading " + myFileName + "\n");
myErrorFlags |= READERROR;
if (s == null)
myErrorFlags |= EOF;
return s;
* Skips whitespace and reads the next word (a string of consecutive
* non-whitespace characters (up to but excluding the next space,
* newline, etc.)
* @return the read string or null if trying to read beyond the EOF
public String readWord()
StringBuffer buffer = new StringBuffer(128);
char ch = ' ';
int count = 0;
String s = null;
try
while (ready() && Character.isWhitespace(ch))
ch = (char)myInFile.read();
while (ready() && !Character.isWhitespace(ch))
count++;
buffer.append(ch);
myInFile.mark(1);
ch = (char)myInFile.read();
if (count > 0)
myInFile.reset();
s = buffer.toString();
else
myErrorFlags |= EOF;
catch (IOException e)
if (myFileName != null)
System.err.println("Error reading " + myFileName + "\n");
myErrorFlags |= READERROR;
return s;
* Reads the next integer (without validating its format)
* @return the integer read or 0 if trying to read beyond the EOF
public int readInt()
String s = readWord();
if (s != null)
return Integer.parseInt(s);
else
return 0;
* Reads the next double (without validating its format)
* @return the number read or 0 if trying to read beyond the EOF
public double readDouble()
String s = readWord();
if (s != null)
return Double.parseDouble(s);
// in Java 1, use: return Double.valueOf(s).doubleValue();
else
return 0.0;
}same with this:
public class p
public static void l(String S)
{ System.out.println(S);}
public static void o(String S)
{System.out.print(S);}
public static void l(int i)
{ System.out.println(i);}
public static void o(int i)
{System.out.print(i);}
public static void l(boolean b)
{ System.out.println(b);}
public static void o(boolean b)
{System.out.print(b);}
public static void l(char c)
{ System.out.println(c);}
public static void o(char c)
{System.out.print(c);}
public static void l(double d)
{ System.out.println(d);}
public static void o(double d)
{System.out.print(d);}
public static void l(Object obj)
{ System.out.println(obj.toString());}
public static void o(Object obj)
{System.out.print(obj.toString());}
public static void l()
{System.out.println();}
} here's my code:
import java.util.*;
public class JMM_Pig
public static void main(String[] args)
int winner=0;
int pts=0;
JMM_Dice player1=new JMM_Dice();
JMM_Dice player2=new JMM_Dice();
p.l("Player 1 rolls the dice...");
player1.rollDice();
player1.updateTotals();
boolean loop=true;
while(loop)
while(player1.numVowels()<=4)
p.l("Player 1 continues his turn...");
player1.rollDice();
player1.updateTotals();
p.l("Player 1 rolled a "+player1.getDie1()+" and a "+player1.getDie2()+" and a '"+player1.getDie3()+"' and a '"+player1.getDie4()+"'");
p.l("Player 1 rolled "+player1.currvowels()+" vowels.");
p.l("Player 1 has "+player1.totalvowels()+" total vowels.");
//if(player1.getMagic()==1)
//player1.totalPoints=(player1.totalPoints+player1.getDie1()+player1.getDie2())*player1.mult;
//pts=(player1.totalPts()+player1.getDie1()+player1.getDie2())*player1.getMult();
//player1.setTpts(pts);
//if(player1.getMagic()!=1)
//player1.totalPoints=player1.totalPoints+player1.getDie1()+player1.getDie2();
//pts=player1.totalPts()+player1.getDie1()+player1.getDie2();
//player1.setTpts(pts);
p.l("Player 1 has "+player1.numSnakes()+" snake eyes.");
p.l("Player 1 earned "+player1.ptsreturn()+" points this turn.");
p.l("Player 1 has "+player1.totalPts()+" total points.");
pts=0;
if(player1.totalPts()>=2000)
winner=1;
player1.setNv(4);loop=false;
if((player1.isavowel(player1.getadice()))&&player1.isavowel(player1.getadice2()))
player1.setTpts(0);player1.setNv(0);player1.setNv(4);
p.l("Player 1's turn has ended...");
player1.setNv(0);
p.l("Player 2 rolls the dice...");
player2.rollDice();
player2.setTpts(player2.totalPts()+player2.getDie1()+player2.getDie2());
while(player2.numVowels()<=4)
p.l("Player 2 continues his turn...");
player2.rollDice();
player2.updateTotals();
p.l("Player 2 rolled a "+player2.getDie1()+" and a "+player2.getDie2()+" and a '"+player2.getDie3()+"' and a '"+player2.getDie4()+"'");
p.l("Player 2 rolled "+player2.currvowels()+" vowels.");
p.l("Player 2 has "+player2.totalvowels()+" total vowels.");
//if(player1.getMagic()==1)
//player1.totalPoints=(player1.totalPoints+player1.getDie1()+player1.getDie2())*player1.mult;
//pts=(player1.totalPts()+player1.getDie1()+player1.getDie2())*player1.getMult();
//player1.setTpts(pts);
//if(player1.getMagic()!=1)
//player1.totalPoints=player1.totalPoints+player1.getDie1()+player1.getDie2();
//pts=player1.totalPts()+player1.getDie1()+player1.getDie2();
//player1.setTpts(pts);
p.l("Player 2 has "+player2.numSnakes()+" snake eyes.");
p.l("Player 2 earned "+player2.ptsreturn()+" points this turn.");
p.l("Player 2 has "+player2.totalPts()+" total points.");
pts=0;
if(player2.totalPts()>=2000)
winner=2;
player2.setNv(4);loop=false;
if((player2.isavowel(player2.getadice()))&&player2.isavowel(player2.getadice2()))
player2.setTpts(0);player2.setNv(0);player2.setNv(4);
p.l("Player 2's turn has ended...");
player2.setNv(0);
if(player1.totalPts()>=2000)
winner=1;
loop=false;
if(player2.totalPts()>=2000)
winner=2;
loop=false;
} //main loop
if(winner==1)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 1 wins, oink oink!");
if(winner==2)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 2 wins, oink oink!");
and dice class:
import java.util.*;
public class JMM_Dice {
private static Random gen = new Random();
private final static int NUM_SIDES = 21;
private int die1, die2, numSnakeEyes, numVowels, totalPoints;
private char die3, die4;
private int dice=0;
//dice=
private int dice2=0;
//dice2=;
private String adice="";
//adice=;
private String adice2="";
//adice2;
private int magic=0;
private int mult=0;
private int currvowels=0;
private int totalvowels=0;
public static EasyReader key = new EasyReader();
public JMM_Dice()
dice=0;dice2=0;
String alpha="abcdefghijklmnopqrstuvwxyz";
adice="";adice2="";
rollDice();
numSnakeEyes=0;numVowels=0;totalPoints=0;
public void setTpts(int tpts)
this.totalPoints=tpts;
public void setNv(int nv)
this.numVowels=nv;
public int getDie1()
return dice;
public int getDie2()
return dice2;
public String getDie3()
return adice;
public String getDie4()
return adice2;
public int numSnakes()
return numSnakeEyes;
public void setSnakes(int s)
this.numSnakeEyes=s;
public String getadice()
return this.adice;
public String getadice2()
return this.adice2;
public int numVowels()
return numVowels;
public int getMagic()
return this.magic;
public int getNv()
return this.numVowels;
public void setMagic(int mag)
this.magic=mag;
public int getMult()
return this.mult;
public void setMult(int m)
this.mult=m;
public int totalPts()
return totalPoints;
public String toString()
return dice+""+dice2+""+adice+""+adice2;
public boolean isavowel(String str)
if(str.equals("a")||str.equals("e")||str.equals("i")||str.equals("o")||str.equals("u"))
return true;
else
return false;
public int ptsreturn()
return dice+dice2;
public int currvowels()
int tmp=currvowels;
currvowels=0;
return tmp;
public int totalvowels()
return numVowels;
public void updateTotals()
if(adice.equalsIgnoreCase("a")||adice.equalsIgnoreCase("e")||adice.equalsIgnoreCase("i")||adice.equalsIgnoreCase("o")||adice.equalsIgnoreCase("u")||adice2.equalsIgnoreCase("a")||adice2.equalsIgnoreCase("e")||adice2.equalsIgnoreCase("i")||adice2.equalsIgnoreCase("o")||adice2.equalsIgnoreCase("u"))
numVowels++;currvowels++;
if((isavowel(adice))&&isavowel(adice2))
totalPoints=0;numVowels=0;
if(dice==1||dice2==1)
numSnakeEyes++;
int fd=dice;
int sd=dice2;
int sum=fd+sd;
totalPoints+=sum*(numSnakeEyes+1);
public void rollDice()
dice=gen.nextInt(20)+1;
dice2=gen.nextInt(20)+1;
String alpha="abcdefghijklmnopqrstuvwxyz";
adice=String.valueOf(alpha.charAt(gen.nextInt(26)));
adice2=String.valueOf(alpha.charAt(gen.nextInt(26)));
public static void sleep (int wait)
{ long timeToQuit = System.currentTimeMillis() + wait;
while (System.currentTimeMillis() < timeToQuit)
; // take no action
}the program works fine except it's supposed to terminate when one of the two AIs get a score of 2000, right now it terminates no matter what score the AIs get and no matter what I've tried to do it keeps doing that...can someone please tell me why it's terminating so oddly? Thanks! :)Here's how my code works in a nutshell, the main program starts with the boolean loop=true;
while(loop)
{then comes the loops for the two AIs, first the player 1 AI goes with this loop: while(player1.numVowels()<=4)
{there the player 1 roles the dice and it keeps going until player 1 gets a total of 2000 points at which time this is supposed to execute: if(player1.totalPts()>=2000)
winner=1;
player1.setNv(4);loop=false;
}, player1.setNv(4); sets numVowels to 4 so that the inner loop exits, loop=false exits the other loop and winner=1; specifies that player 1 won which is used outside of the loops here: if(winner==1)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 1 wins, oink oink!");
if(winner==2)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 2 wins, oink oink!");
} the same thing happens for player 2 if player 1 didn't already get 2000 points...but the if statement despite everything pointing to the variables containing the right values don't seem to be working, as shown by the example program output I posted it just ends at any random number...hopefully this helps make figuring out what's wrong easier :) ...so can anyone please help me out? thanks! :) -
Variable calling not working. please help
Hi there,
I am trying to include a nslookup utility I have, to run with my messenger server proxy below.
The idea is, is that the address lookup found is saved to a string, which is called dottedQuad, and then using string variable name, I just put that in the consturctor of the socket below.
No matter what I try, I cannot get access to that variable from the try/catch block where that socket declaration is????? please help!!
cheers
// MultiThreadsServer.java: The server can communicate with
// multiple clients concurrently using the multiple threads
import java.io.*;
import java.net.*;
public class MultiThreadServerRead
String result;
MultiThreadServerRead server;
// Main method
public static void main(String[] args)
try
System.out.println("Messenger Server proxy");
System.out.println("Please enter the PC name of the user you wish to talk to:");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String host = in.readLine();
System.out.println(lookup(host));
catch (IOException ex){
System.err.println(ex);
try
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
// To number a client
int clientNo = 1;
while (true)
// Listen for a new connection request
Socket connectToClient = serverSocket.accept();
// Print the new connect number on the console
System.out.println("Start thread for client " + clientNo);
// Find the client's hostname, and IP address
InetAddress clientInetAddress = connectToClient.getInetAddress();
System.out.println("Client " + clientNo + "'s hostname is "
+ clientInetAddress.getHostName());
System.out.println("Client " + clientNo + "'s IP Address is "
+ clientInetAddress.getHostAddress());
// Create a new thread for the connection
HandleAClient thread = new HandleAClient(connectToClient, clientNo);
// Start the new thread
thread.start();
// Increment clientNo
clientNo++;
catch(IOException ex)
System.err.println(ex);
} //end catch
}//end main
public static String lookup(String host )
InetAddress thisComputer;
byte[] address;
//get the bytes of the IP address
try
thisComputer = InetAddress.getByName(host);
address = thisComputer.getAddress();
catch
(UnknownHostException e)
return "Cannot find host " + host;
if( isHostName(host))
MultiThreadServerRead server = new MultiThreadServerRead();
//print the IP address
String dottedQuad = "";
for (int i = 0 ; i< address.length; i++)
int unsignedByte = address[i] < 0 ? address[i] + 256 : address;
dottedQuad += unsignedByte;
if (i != address.length-1) dottedQuad += ".";
server.result = dottedQuad;
return dottedQuad;
else
{ //this is an IP address
return thisComputer.getHostName();
} // end lookup
public static boolean isHostName(String host)
char[] ca = host.toCharArray();
//if we see a character that is neither a digit nor a period
// then host is proberbly a host name
for (int i = 0; i < ca.length; i++)
if (!Character.isDigit(ca[i]))
if ( ca[i] != '.') return true;
//Everything was either a digit or a period
//so host looks like an IP address in dotted quad format
return false;
} //end isHostName
} //end class
// Define the thread class for handling a new connection
class HandleAClient extends Thread
String timeString ;
private Socket connectToClient; // A connected socket
private int clientNo; // Indicate client no
// Construct a thread
public HandleAClient(Socket socket, int clientNo)
connectToClient = socket;
this.clientNo = clientNo;
// Implement the run() method for the thread
public void run()
try
// Create data input and output streams
InputStream isFromClient = connectToClient.getInputStream();
//OutputStreamWriter osToClient = new OutputStreamWriter(connectToClient.getOutputStream());
StringBuffer time = new StringBuffer();
int c;
while ((c = isFromClient.read()) != -1) time.append((char) c);
timeString = time.toString().trim();
System.out.println("it is " + timeString + " at " );
catch(IOException ex)
System.err.println(ex);
} //end catch
try
// Create data input and output streams
StringBuffer time = new StringBuffer();
int c;
Socket connectToServer = new Socket("192.168.0.3", 8001);
OutputStreamWriter osToServer = new OutputStreamWriter(connectToServer.getOutputStream());
// Continuously serve the client
// while (true)
// System.out.println(lookup(host));
osToServer.write("WRITE BACK TO CLIENT " + timeString + "\r\n" );
osToServer.flush();
connectToServer.close();
catch(IOException ex)
System.err.println(ex);
} //end catch
} //end run
} // end classIf you want to access a variable from outside of a block, then don't declare it inside the block.
-
Hi i want to create custom data source as i have read in different post and also on sun site
I tried to create one one for my self,
where am getting stream from tcp port.
before that i test the data by using socket programming, i saved the input stream into file and played and its working fine and then i transfer that file using avtransmiter2.java and it work fine again its mean it confirm that the data i am getting from skype is working fine . now my question is how to get that input stream and instead of saving to the file i can play it using jmf player or send it on rtp session. i read different post how to create custom data source from inputstreams but have not work for me ... i modified a user code posted http://archives.java.sun.com/cgi-bin/wa?A2=ind0106&L=jmf-interest&D=0&P=25865 in that post some body recommanded to implement seekable so i implemented that one als in that code..... below is the code
the error is
LoadInputStream.loadBytes() - realizing player
Exception in thread "JMF thread: com.sun.media.PlaybackEngine@8ed465[ com.sun.media.PlaybackEngine@8ed465 ] ( configureThread)" java.lang.NullPointerException
at com.skype.sample.InputSourceStream.read(InputSourceStream.java:89)
at com.sun.media.parser.BasicPullParser.readBytes(BasicPullParser.java:142)
at com.sun.media.parser.BasicPullParser.readBytes(BasicPullParser.java:114)
at com.sun.media.parser.BasicPullParser.readInt(BasicPullParser.java:191)
at com.sun.media.parser.audio.AuParser.readHeader(AuParser.java:109)
at com.sun.media.parser.audio.AuParser.getTracks(AuParser.java:76)
at com.sun.media.BasicSourceModule.doRealize(BasicSourceModule.java:180)
at com.sun.media.PlaybackEngine.doConfigure1(PlaybackEngine.java:229)
at com.sun.media.PlaybackEngine.doConfigure(PlaybackEngine.java:193)
at com.sun.media.ConfigureWorkThread.process(BasicController.java:1370)
at com.sun.media.StateTransitionWorkThread.run(BasicController.java:1339)
i need urgent help to this matter so please help me in that i would be very thankfulll ......
below is the code
skype use the standard audio format
Audio format
File: WAV PCM
Sockets: raw PCM samples
16 KHz mono, 16 bit
Note
import javax.media.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class LoadInputStream extends JFrame implements ControllerListener {
private Player player;
/** Creates new LoadInputStream */
public LoadInputStream() {
try{
// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
ServerSocket SkypeServer = null;
DataInputStream is;
Socket clientSocket = null;
try {
SkypeServer = new ServerSocket(4447);
catch (IOException e) {
System.out.println(e);
// Open input stream
clientSocket = SkypeServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
loadBytes(is);
setBounds(100, 100, 300, 300);
setVisible(true);
catch(Exception e){
System.out.println(e);
/* Loads the given byte [] into the MediaPlayer and starts playing it immediately. */
public void loadBytes(InputStream is){
DataSource ds=new DataSource(is);
System.out.println("LoadInputStream.loadBytes() - Creating DataSource (InputStream)");
System.out.println("LoadInputStream.loadBytes() - Creating Player");
try {
player = Manager.createPlayer(ds);
} catch(NoPlayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("LoadInputStream.loadBytes() - Adding Controller Listener");
player.addControllerListener(this);
System.out.println("LoadInputStream.loadBytes() - realizing player");
player.realize();
public static void main(String[] args){
new LoadInputStream();
public void controllerUpdate(javax.media.ControllerEvent e) {
if(e instanceof RealizeCompleteEvent){
System.out.println("Adding visual component");
getContentPane().add(player.getVisualComponent());
player.start();
=============================Datasource==========================================================
import java.io.*;
import java.nio.ByteBuffer;
import javax.media.*;
import javax.media.protocol.*;
public class DataSource extends PullDataSource {
private InputStream is;
private byte [] bytes;
/** Creates new MediaViewerDataSource */
public DataSource(InputStream is) {
super();
this.is = is;
try{
int byteCount = is.available();
bytes = new byte [byteCount];
is.read(bytes);
catch (Exception e){
System.out.println(e);
public PullSourceStream [] getStreams() {
PullSourceStream [] streams = new PullSourceStream [1];
InputSourceStream iss = new InputSourceStream(new ByteArrayInputStream(bytes), new FileTypeDescriptor(ContentDescriptor.RAW_RTP));
streams[0] = iss;
return streams;
public void connect() {}
public void disconnect() {}
public String getContentType() {
return new String("audio.x-wav");
public MediaLocator getLocator() {
return null;
public void initCheck() {}
public void setLocator(MediaLocator source) {}
public void start() {}
public void stop() {}
public Object getControl(String s){
return null;
public Object [] getControls(){
return null;
public Time getDuration(){
return null;
=================================InputStream======================================================
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.PullSourceStream;
import javax.media.protocol.Seekable;
import javax.media.protocol.SourceStream;
* Build a source stream out of an input stream.
* @see DataSource
* @see SourceStream
* @see java.io.InputStream
* @version %I%, %E%.
public
class InputSourceStream implements PullSourceStream, Seekable {
protected InputStream stream;
protected boolean eosReached;
ContentDescriptor contentType;
protected ByteBuffer inputBuffer;
* Construct an <CODE>InputSourceStream</CODE> from an input stream.
* @param s The input stream to build the source stream from.
* @param type The content-type of the source stream.
public InputSourceStream(InputStream s, ContentDescriptor type) {
stream = s;
eosReached = false;
contentType = type;
* Get the content type for this stream.
* @return content descriptor for the stream.
public ContentDescriptor getContentDescriptor() {
return contentType;
* Obtain the content length
* @return content length for this stream.
public long getContentLength() {
return SourceStream.LENGTH_UNKNOWN;
* Query if the next read will block.
* @return true if a read will block.
public boolean willReadBlock() {
if( eosReached == true) {
return true;
} else {
try {
return stream.available() == 0;
} catch (IOException e) {
return true;
* Read a buffer of data.
* @param buffer The buffer to read data into.
* @param offset The offset into the buffer for reading.
* @param length The number of bytes to read.
* @return The number of bytes read or -1 indicating end-of-stream.
public int read(byte[] buffer, int offset, int length) throws IOException {
int bytesRead = stream.read(buffer, offset, length);
if( bytesRead == -1) {
eosReached = true;
inputBuffer.get(buffer,offset,length);
return bytesRead;
* Turn the stream off.
* @exception IOException Thrown if there is a problem closing the stream.
public void close() throws IOException {
stream.close();
* Return if the end of stream has been reached.
* @return true if the end of the stream has been reached.
// $jdr: This is a bug. Need to figure out
// the "correct" way to determine, before a read
// is done, if we're at EOS.
public boolean endOfStream() {
return eosReached;
* Returns an zero length array because no controls
* are supported.
* @return a zero length <code>Object</code> array.
public Object[] getControls() {
return new Object[0];
* Returns <code>null</code> because no controls are implemented.
* @return <code>null</code>.
public Object getControl(String controlName) {
return null;
public long seek(long where) {
try {
inputBuffer.position((int)(where));
return where;
catch (IllegalArgumentException E) {
return this.tell(); // staying at the current position
public long tell() {
return inputBuffer.position();
public void SeekableStream(ByteBuffer byteBuffer) {
inputBuffer = byteBuffer;
this.seek((long)(0)); // set the ByteBuffer to to beginning
public boolean isRandomAccess() {
// TODO Auto-generated method stub
return false;
}Use a BufferedImage where you draw the other images.
You have to know the size.
For example if the size is (50*50) for each image :
int width =50;
int height = 50;
BufferedImage bufIm = new BufferedImage(width*3,height*3,BufferedImage.TYPE_INT_ARGB);
Graphics gr = bufIm.createGraphics();
int k, j;
Toolkit tk = Toolkit.getDefaultToolkit();
Image imTemp;
for (k = 0; k<3; k++) {
for (j = 0; j<3; j++) {
imTemp = tk.getImage(imageNames[k][j]);
gr.drawImage(imTemp,width*k,height*j, this); // replace this by the Image observer you want (this if you are in a panel for example)
}After that bufIm contains the images as you want and you can paint it on a Graphics.
Denis -
Some procedure can not run,Please help
--Please Help me where is wrong
--The Procedure can be compiler,but can not run
--Maybe there has some wrong with Ref Cursor or dynamic SQL
--Please,Thanks ver much
--Follow is my full code
Create or Replace package ref_types
AS
TYPE ref_cursor is REF CURSOR;
End;
Create or Replace package userinfo as
procedure Get_usermenu (baduser out boolean,
menu out ref_types.ref_cursor
End;
Create or Replace package body userinfo as
procedure Get_usermenu (baduser out boolean,
menu out ref_types.ref_cursor
) is
v_sqltext varchar2(100);
v_sql varchar2(300);
begin
baduser:=FALSE;
v_sqltext:='''A001'',''A002'',''A003''';
v_sql:='select MENUID,P_NAME from MENU_LIST
where MENUID in (';
v_sql:=v_sql||v_sqltext||) order by MENUID asc';
--explain:Get v_sqktext values overpass some process
open menu FOR v_sql;
end;
end;
/thanks,
error number is : Ora-01001
I use it In Form:
declare
v_baduser boolean;
v_menu ref_types.ref_cursor;
v_menuid number;
v_menuname varchar2(50);
v_menucount number;
begin
v_menucount:=1;
userinfo.Get_usermenu(v_baduser,v_menu);
loop
fetch v_menu into v_menuid,v_menuname;
exit when v_menu%NOTFOUND;
show_alert_info(v_menuid||';'||v_menucount||'、'||v_menuname);
--show_alert_info,like Developer's Function "message",
--It can show some text
v_menucount:=v_menucount+1;
end loop;
Close v_menu;
end; -
Please help me..about JTable ..Please please
I have a JTable and tried to set the width for its columns..but I dont
know why it doesnt work..here's my codes:
Please help me..thanks..
import javax.swing.table.TableColumn;
import javax.swing.table.*;
JTable table = new JTable();
//a method{
DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
public boolean isCellEditable(int row, int col){ return false; }
table.setModel(model);
TableColumn column = tblEntryList.getColumnModel().getColumn(0);
column.setPreferredWidth(25);
column = tblEntryList.getColumnModel().getColumn(1);
column.setPreferredWidth(100);I did feed the data into the table..you can tell by looking at my codes..
please show me..dont know why it doesnt work.
I just have my tlbEntrylist declared as
String[][] rowData = new String[0][];
String[] columnNames = {"Cnt","Name","Text"};
JTable tblEntryList = new JTable(rowData, columnNames);
//then whenever I click a a button , will call loadTableEntries()
to remove all row data and refresh with new data..so I have to
set new new model for this table.
private void loadTableEntries()
tblEntryList.removeAll(); // Remove old entries
Object[][] rowData = new Object[entries.length][3];
//feed the table of new data
for(int i=0;i<rowData.length;i++)
rowData[0] =new Integer(entries[i].getTimesUsed());
rowData[i][1] = entries[i].getName();
rowData[i][2] = entries[i].getText();
String[] columnNames = {"Cnt","Name","Text"};
// Create a new model and load it with new values
DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
public boolean isCellEditable(int row, int col){ return false; }
tblEntryList.setModel(model);
TableColumn col = tblEntryList.getColumn(tblEntryList.getModel().getColumnName(0));
col.setPreferredWidth(10);
col = tblEntryList.getColumn(tblEntryList.getModel().getColumnName(1));
col.setPreferredWidth(25);
I dont know what i'm doing wrong here but it ddint work.. -
Jtable Update problem .. Please help !!!!!!!!
Hi ,
I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
Here is the code .... Please see it and tell me if it is possible :
package newpackage;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.text.*;
import newpackage.ExcelExporter;
import java.awt.Dimension;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.awt.print.*;
import java.awt.*;
import java.io.*;
import java.util.Random.*;
import javax.swing.*;
import java.text.*;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class tab7le extends javax.swing.JFrame {
Vector columnNames = new Vector();
Vector data = new Vector();
Connection con;
Statement stat;
ResultSet rs;
int li_cols = 0;
Vector allRows;
Vector row;
Vector newRow;
Vector colNames;
String dbColNames[];
String pkValues[];
String tableName;
ResultSetMetaData myM;
String pKeyCol;
Vector deletedKeys;
Vector newRows;
boolean ibRowNew = false;
boolean ibRowInserted = false;
private Map<String, Color> colormap = new HashMap<String, Color>();
/** Creates new form tab7le */
public tab7le() {
populate();
initComponents();
public void updateDB(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException e){
System.out.println("Cannot Load Driver!");
try{
String url = "jdbc:odbc:FAMS";
con = DriverManager.getConnection(url);
stat = con.createStatement();
rs = stat.executeQuery("Select * from SubAllot");
deletedKeys = new Vector();
newRows = new Vector();
myM = rs.getMetaData();
tableName = myM.getTableName(1);
li_cols = myM.getColumnCount();
dbColNames = new String[li_cols];
for(int col = 0; col < li_cols; col ++){
dbColNames[col] = myM.getColumnName(col + 1);
allRows = new Vector();
while(rs.next()){
newRow = new Vector();
for(int i = 1; i <= li_cols; i++){
newRow.addElement(rs.getObject(i));
} // for
allRows.addElement(newRow);
} // while
catch(SQLException e){
System.out.println(e.getMessage());
String updateLine[] = new String[dbColNames.length];
try{
DatabaseMetaData dbData = con.getMetaData();
String catalog;
// Get the name of all of the columns for this table
String curCol;
colNames = new Vector();
ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
while (rset1.next()) {
curCol = rset1.getString(4);
colNames.addElement(curCol);
rset1.close();
pKeyCol = colNames.firstElement().toString();
// Go through the rows and perform INSERTS/UPDATES/DELETES
int totalrows;
totalrows = allRows.size();
String dbValues[];
Vector currentRow = new Vector();
pkValues = new String[allRows.size()];
// Get column names and values
for(int i=0;i < totalrows;i++){
currentRow = (Vector) allRows.elementAt(i);
int numElements = currentRow.size();
dbValues = new String[numElements];
for(int x = 0; x < numElements; x++){
String classType = currentRow.elementAt(x).getClass().toString();
int pos = classType.indexOf("String");
if(pos > 0){ // we have a String
dbValues[x] = "'" + currentRow.elementAt(x) + "'";
updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
pos = classType.indexOf("Integer");
if(pos > 0){ // we have an Integer
dbValues[x] = currentRow.elementAt(x).toString();
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString();
else{
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
pos = classType.indexOf("Boolean");
if(pos > 0){ // we have a Boolean
dbValues[x] = currentRow.elementAt(x).toString();
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
} // For Loop
// If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
int numNewRows = newRows.size();
int insertRow = 0;
boolean newRowFound;
for (int z = 0;z < numNewRows;z++){
insertRow = ((Integer) newRows.get(z)).intValue();
if(insertRow == i+1){
StringBuffer InsertSQL = new StringBuffer();
InsertSQL.append("INSERT INTO " + tableName + " (");
for(int zz=0;zz<=dbColNames.length-1;zz++){
if (dbColNames[zz] != null){
InsertSQL.append(dbColNames[zz] + ",");
// Strip out last comma
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
InsertSQL.append(" VALUES(" + pkValues[i] + ",");
for(int c=1;c < dbValues.length;c++){
InsertSQL.append(dbValues[c] + ",");
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
System.out.println(InsertSQL.toString());
stat.executeUpdate(InsertSQL.toString());
ibRowInserted=true;
} // End of INSERT Logic
// If row has not been INSERTED perform an UPDATE
if(ibRowInserted == false){
StringBuffer updateSQL = new StringBuffer();
updateSQL.append("UPDATE " + tableName + " SET ");
for(int z=0;z<=updateLine.length-1;z++){
if (updateLine[z] != null){
updateSQL.append(updateLine[z]);
// Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
System.out.println(updateSQL.toString());
stat.executeUpdate(updateSQL.toString());
} //for
catch(Exception ex){
System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
// Delete records from the DB
try{
int numDeletes = deletedKeys.size();
String deleteSQL;
for(int i = 0; i < numDeletes;i++){
deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
((Integer) deletedKeys.get(i)).toString();
System.out.println(deleteSQL);
stat.executeUpdate(deleteSQL);
// Assume deletes where successful. Recreate Vector holding PK Keys
deletedKeys = new Vector();
catch(Exception ex){
System.out.println(ex.getMessage());
public void populate()
try
// Connect to the Database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
System.out.println("ok1");
// Read data from a table
String sql;
sql = "Select * from SubAllot";
System.out.println("ok1");
Statement stmt = con.createStatement();
System.out.println("ok1");
ResultSet rs = stmt.executeQuery( sql );
System.out.println("ok1");
ResultSetMetaData md = rs.getMetaData();
System.out.println("ok1");
int columns = md.getColumnCount();
for(int i = 0;i<columns;i++){
columnNames.addElement(md.getColumnName(i+1));
System.out.println("ok2");
while (rs.next())
Vector row = new Vector(columns);
for (int i = 1; i <columns+1; i++)
row.addElement( rs.getObject(i) );
data.addElement( row );
catch(Exception e){
e.printStackTrace();
public void dropmenu(JTable table,TableColumn subpref1) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
for (int i = 0;i<=20;i++)
comboBox.addItem(i);
subpref1.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
subpref1.setCellRenderer(renderer);
abstract class StringTransferHandler extends TransferHandler {
public int dropAction;
protected abstract String exportString(final JComponent c);
protected abstract void importString(final JComponent c, final String str);
@Override
protected Transferable createTransferable(final JComponent c) {
return new StringSelection(exportString(c));
@Override
public int getSourceActions(final JComponent c) {
return MOVE;
@Override
public boolean importData(final JComponent c, final Transferable t) {
if (canImport(c, t.getTransferDataFlavors())) {
try {
String str = (String) t.getTransferData(DataFlavor.stringFlavor);
importString(c, str);
return true;
} catch (UnsupportedFlavorException ufe) {
} catch (IOException ioe) {
return false;
@Override
public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
for (int ndx = 0; ndx < flavors.length; ndx++) {
if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
return true;
return false;
class TableTransferHandler extends StringTransferHandler {
private int dragRow;
private int[] dragColumns;
private BufferedImage[] image;
private int row;
private int[] columns;
public JTable target;
private Map<String, Color> colormap;
private TableTransferHandler(final Map<String, Color> colormap) {
this.colormap = colormap;
@Override
protected Transferable createTransferable(final JComponent c) {
JTable table = (JTable) c;
dragRow = table.getSelectedRow();
dragColumns = table.getSelectedColumns();
createDragImage(table);
return new StringSelection(exportString(c));
protected String exportString(final JComponent c) {
JTable table = (JTable) c;
row = table.getSelectedRow();
columns = table.getSelectedColumns();
StringBuffer buff = new StringBuffer();
colormap.clear();
for (int j = 0; j < columns.length; j++) {
Object val = table.getValueAt(row, columns[j]);
buff.append(val == null ? "" : val.toString());
if (j != columns.length - 1) {
buff.append(",");
colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
table.repaint();
return buff.toString();
protected void importString(final JComponent c, final String str) {
target = (JTable) c;
DefaultTableModel model = (DefaultTableModel) target.getModel();
String[] values = str.split("\n");
int colCount = target.getSelectedColumn();
int max = target.getColumnCount();
for (int ndx = 0; ndx < values.length; ndx++) {
String[] data = values[ndx].split(",");
for (int i = 0; i < data.length; i++) {
String string = data;
if(colCount < max){
Object val = model.getValueAt(target.getSelectedRow(), colCount);
model.setValueAt(string, target.getSelectedRow(), colCount);
model.setValueAt(val, dragRow, dragColumns[i]);
colCount++;
public BufferedImage[] getDragImage() {
return image;
private void createDragImage(final JTable table) {
if (dragColumns != null) {
try {
image = new BufferedImage[dragColumns.length];
for (int i = 0; i < dragColumns.length; i++) {
Rectangle cellBounds = table.getCellRect(dragRow, i, true);
TableCellRenderer r = table.getCellRenderer(dragRow, i);
DefaultTableModel m = (DefaultTableModel) table.getModel();
JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
lbl.setBounds(cellBounds);
BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D graphics = img.createGraphics();
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
lbl.paint(graphics);
graphics.dispose();
image[i] = img;
} catch (RuntimeException re) {
class TableDropTarget extends DropTarget {
private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
private Rectangle rect2D = new Rectangle();
private TableTransferHandler handler;
public TableDropTarget(final TableTransferHandler h) {
super();
this.handler = h;
@Override
public void dragOver(final DropTargetDragEvent dtde) {
handler.dropAction = dtde.getDropAction();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
Point location = dtde.getLocation();
int row = table.rowAtPoint(location);
int column = table.columnAtPoint(location);
table.changeSelection(row, column, false, false);
paintImage(table, location);
autoscroll(table, location);
super.dragOver(dtde);
public void dragExit(final DropTargetDragEvent dtde) {
clearImage((JTable) dtde.getDropTargetContext().getComponent());
super.dragExit(dtde);
@Override
public void drop(final DropTargetDropEvent dtde) {
Transferable data = dtde.getTransferable();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
clearImage(table);
handler.importData(table, data);
super.drop(dtde);
private final void paintImage(final JTable table, final Point location) {
Point pt = new Point(location);
BufferedImage[] image = handler.getDragImage();
if (image != null) {
table.paintImmediately(rect2D.getBounds());
rect2D.setLocation(pt.x - 15, pt.y - 15);
int wRect2D = 0;
int hRect2D = 0;
for (int i = 0; i < image.length; i++) {
table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
pt.x += image[i].getWidth();
if (hRect2D < image[i].getHeight()) {
hRect2D = image[i].getHeight();
wRect2D += image[i].getWidth();
rect2D.setSize(wRect2D, hRect2D);
private final void clearImage(final JTable table) {
table.paintImmediately(rect2D.getBounds());
private Insets getAutoscrollInsets() {
return autoscrollInsets;
private void autoscroll(final JTable table, final Point cursorLocation) {
Insets insets = getAutoscrollInsets();
Rectangle outer = table.getVisibleRect();
Rectangle inner = new Rectangle(outer.x + insets.left,
outer.y + insets.top,
outer.width - (insets.left + insets.right),
outer.height - (insets.top + insets.bottom));
if (!inner.contains(cursorLocation)) {
Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
cursorLocation.y - insets.top,
insets.left + insets.right,
insets.top + insets.bottom);
table.scrollRectToVisible(scrollRect);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
table.setModel(new javax.swing.table.DefaultTableModel(
data, columnNames
jScrollPane1.setViewportView(table);
//populate();
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true);
table.setDragEnabled(true);
TableTransferHandler th = new TableTransferHandler(colormap);
table.setTransferHandler(th);
table.setDropTarget(new TableDropTarget(th));
dropmenu(table, table.getColumnModel().getColumn(11));
jButton1.setText("Update");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButton2.setText("Ex");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(347, 347, 347)
.addComponent(jButton1)
.addGap(115, 115, 115)
.addComponent(jButton2)))
.addContainerGap(73, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jButton1)
.addContainerGap(83, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addGap(65, 65, 65))))
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
updateDB(); // TODO add your handling code here:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
pathToDesktop = pathToDesktop + "//Final Allotment.xls";
ExcelExporter exp = new ExcelExporter();
exp.exportTable(table, new File(pathToDesktop));
JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
} // TODO add your handling code here:
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new tab7le().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
// End of variables declaration
Please help !!!!!!!!
Thanks in advance.....Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
Why post code with access to a database? We can't access the database.
Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour. -
JTA Transaction--please help-----Xid not valid
HI,
I am writing a small application which i am posting at the end.This is decription of my application.I am writing a jsp.Later on i will be using in some other way.
I am using Oracle XA implementation to communicatewith my RM which oracle8.1.7 .
I am creating two XAConnection with two data instances 'test' and 'test3' .These two reside on my local machine in the same database server.
With the code which i am sending you i have tried two cases.
First Case
1)i use only one XAConnection object of say 'test'.
2)enlist its XADataSource with my transaction Object
3) get two connection objects and execute two sql's on themMy code works fine and maintains the transaction.
Second Case
1) I use create two XAConnection objects. one of 'test' and other of 'test3'.
2) enlist their XAResources with transaction object.
3) Now i take one connection from each of XAConnection and execute two sqls, oneon each of them.
It gives me exception while enlisting second XAResource with transaction objeectsaying that "The Xid is not valid".
below is the stackTrace.
javax.transaction.SystemException: start() failed on resource 'oracle.jdbc.xa.client.OracleXAResource':XAER_NOTA : The XID is not valid
oracle.jdbc.xa.OracleXAException at oracle.jdbc.xa.OracleXAResource.checkError(OracleXAResource.java:483)
at oracle.jdbc.xa.client.OracleXAResource.start(OracleXAResource.java:190)
at weblogic.transaction.internal.ServerResourceInfo.start(ServerResourceInfo.java:1165)
at weblogic.transaction.internal.ServerResourceInfo.xaStart(ServerResourceInfo.java:1108)
<----------------------CODE------------------------------------------------------>
<html>
<body bgcolor=tan>
<%@page session="true" %>
<%@page import="java.util.Hashtable,java.sql.*,javax.naming.*,javax.transaction.*,javax.sql.*,oracle.jdbc.xa.client.OracleXADataSource,javax.rmi.PortableRemoteObject,javax.transaction.xa.XAResource" %>
<%!
private static XAConnection getFirstXAConnection() throws java.sql.SQLException{
OracleXADataSource oxadsFirst = new OracleXADataSource();
String urlFirst = "jdbc:oracle:thin:@70.7.51.80:1521:test";
oxadsFirst.setURL(urlFirst);
XAConnection xaConnectionFirst = oxadsFirst.getXAConnection("scott","tiger");
return xaConnectionFirst;
private static XAConnection getSecondXAConnection() throws java.sql.SQLException{
OracleXADataSource oxadsSec= new OracleXADataSource();
String urlSec = "jdbc:oracle:thin:@70.7.51.80:1521:test3";
oxadsSec.setURL(urlSec);
XAConnection xaConnectionSec = oxadsSec.getXAConnection("scott","tiger");
return xaConnectionSec;
%>
<%
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
try{
ctx = new InitialContext(ht);
//javax.transaction.UserTransaction transaction = (javax.transaction.UserTransaction)ctx.lookup("java:comp/UserTransaction");
System.out.println("Before Lookup JNDI UserTransaction and TransactionManager......................");
//javax.transaction.UserTransaction userTx = (javax.transaction.UserTransaction)ctx.lookup("javax.transaction.UserTransaction");
javax.transaction.TransactionManager transactionManager = (javax.transaction.TransactionManager)ctx.lookup("javax.transaction.TransactionManager");
System.out.println("After Lookup TransactionManager......................");
try{
transactionManager.begin();
Transaction transaction = transactionManager.getTransaction();
System.out.println("Transaction Object ----------------------------->"+transaction);
XAConnection xaConFirst = getFirstXAConnection();
XAResource xaResourceFirst = xaConFirst.getXAResource();
System.out.println("xaResourceFirst Object ----------------------------->"+xaResourceFirst);
XAConnection xaConSecond = getSecondXAConnection();
XAResource xaResourceSecond = xaConSecond.getXAResource();
System.out.println("xaResourceSecond Object ----------------------------->"+xaResourceSecond);
if(!xaResourceFirst.isSameRM(xaResourceSecond) )
System.out.println("<-----------------BOTH THE RESOURCES ARE NOT SAME SMAE SAME----------------------------->");
boolean firstEnlistBool = transaction.enlistResource(xaResourceFirst);
System.out.println("firstEnlistBool ----------------------------->"+firstEnlistBool);
boolean secondEnlistBool = transaction.enlistResource(xaResourceSecond);
System.out.println("secondEnlistBool -------------------------> "+secondEnlistBool);
java.sql.Connection firstConn = xaConFirst.getConnection();
Statement stmt = firstConn.createStatement();
stmt.executeQuery("insert into dept values(60,'MARKETING','NEW DELHI')");
java.sql.Connection secondConn = xaConSecond.getConnection();//xaConFirst.getConnection();//
stmt = secondConn.createStatement();
//stmt.executeQuery("insert into account values(20,20)");
stmt.executeQuery("insert into salgrade values(10,10,10)");
if(Status.STATUS_ACTIVE == transactionManager.getStatus() )
System.out.println("Before committing status "+transactionManager.getStatus() );
transactionManager.commit();
System.out.println("After committing");
} catch(SQLException sqlE){
sqlE.printStackTrace();
catch(Exception e){
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
finally {
try {
ctx.close();
catch (Exception e) {
e.printStackTrace();
} // close finally
%>
<form method="post">
<input type="submit" name="submit" value="Call Transaction Bean">
</form>
</html>
<-------------------------------------------------------------------------------->
please help in this..I am stuck with this and dont kow how to move ahead to remove this problem..
Best Regards
Akhil NagpalHi,
Hi Vicky,
I think we are in different time zones. I am south
korea.I have tried your suggestion but it gives me
the same exception.Yes ,there is a difference of 3.5 hours , I am in India(Mumbai).
This is what i am trying to achieve.
My aim is to create some aplication to which i can
register my XADataSources and this application should
be able to handle the distributed transactions among
them.I will be using the TransactionManager of some
application server.SO i am using weblogic7.0.
For the testing purpose i have creaed a jsp as i
i posted the code. I am very new to this JTA and may
be i am doing wrong.Can you help me this but putting
insights into your experience may be that will
increase my enthusiasm :-) ....
please help me in this.
I am extracting the following from the docs
public interface TransactionManager
The TransactionManager interface defines the methods that allow an application server to manage transaction boundaries.
public interface UserTransaction
The UserTransaction interface defines the methods that allow an application to explicitly manage transaction boundaries
So as per your specs I can understands your application is trying to explicitily control the boundaries of the transaction, so you should use the UserTransction instance to begin the Transaction.My understanding says the TransactionManager will come in picture for declarative transaction and UserTransaction for the your case.I think you have tried that , I would have tried this out here but I dont work on weblogic.Do the things cooly and try to understand the concept.Let me know of the results.
Regards
Vicky -
Please Help Get a Color from Pixel !!!!
Is anybody know how to get a Color from pixel.
My program is not Full Screen .
So i think Robot.getPixelColor() don't suitable.
Please Help me!Robot.getPixelColor() will work fine, but the problem you will have is getting the mouse set to the correct location and getting your application to know where it is: you can do it with win32 calls and JNI. Here are a few that I have found helpful--they are in a VB format:
Public Const CLR_INVALID = &HFFFF 'not a valid pixel
Public Const MOUSE_MOVED = &H1
Public Const MOUSEEVENTF_ABSOLUTE = &H8000 ' absolute move
Public Const MOUSEEVENTF_LEFTDOWN = &H2 ' left button down
Public Const MOUSEEVENTF_LEFTUP = &H4 ' left button up
Public Const MOUSEEVENTF_RIGHTDOWN = &H8 ' right button down
Public Const MOUSEEVENTF_RIGHTUP = &H10 ' right button up
Public Const REQUEST_LEFT_CLICK = &H2D 'request left click "-"
Public Const REQUEST_RIGHT_CLICK = &H2B 'request right click "+"
Type POINTAPI
x As Long
y As Long
End Type
Type POINTSTRUCT
hwnd As Long
hdc As Long
ptAbsolute As POINTAPI
ptOrigin As POINTAPI
ptLocal As POINTAPI
ptColor As Long
sType As String
retMessage As Boolean
End Type
Declare Function GetCursorPos _
Lib "user32" (ByRef lpPoint As POINTAPI) _
As Long
Declare Function SetCursorPos _
Lib "user32" (ByVal x As Long, ByVal y As Long) _
As Long
Declare Sub mouse_event _
Lib "user32" (ByVal dwFlags As Long, _
ByVal dx As Long, _
ByVal dy As Long, _
ByVal cButtons As Long, _
ByVal dwExtraInfo As Long)
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Declare Function GetMessageExtraInfo Lib "user32" () As Long
Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, _
ByVal x As Long, _
ByVal y As Long) As Long
Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, _
ByVal yPoint As Long) As Long
Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
Declare Function GetWindowOrgEx Lib "gdi32" (ByVal hdc As Long, _
ByRef lpPoint As POINTAPI) As Long -
Please please help. I need to get this code working ASAp
hi! right, I am a java dunce. I am doing a web design degree at uni and annoyingly have to take a programming module. I just don't get it one bit and the lecturer is a sadist and won't help. I have tried countless books and what not but it all goes over my head.... to the problem
We were given some code for a "guess the number" game. it generates a random number between 1 and 1000. You then have to guess the number. If you guess higher it should output "you ned to guess higher" and visa versa. Also if you enter 0 it should exit the program (which it does)
The code had logical and syntax erros in it most of which I think I have managed to find but it still does not work and I have been at this for hours now (even my headache has a headache)
It compiles now but when you enter a number the program just spits out the line "Enter your guess, from 1 to 1000 inclusive (0 to quit):" again but doesn't tell you if you should go higher or lower.
I can only get it to spit out the "you need to guess lower" line if you enter a number above 1000 which is wrong.
please please help me. Just point me in the right direction or something but please use novice language or I think I might have to go jump of the nearest peir.
The code I have so far is:
import java.util.*;
public class guessgame2
public static void main(String[] args)
// Declare variables, setup keyboard input and the
// random number generator
int game_number, user_number;
String continue_pref;
Scanner data_input = new Scanner(System.in);
Random generate = new Random();
do
// Generate game number
game_number = generate.nextInt(999) + 1;
// The following line is a debug line, comment out
// for real game.
// System.out.printf("Game number:%d%n", game_number);
// Get users first guess
System.out.print("The computer has generated a number.");
do
System.out.printf("%nEnter your guess, from 1 to 1000 inclusive (0 to quit):");
user_number = data_input.nextInt();
} while ((user_number >= 1) && (user_number <= 1000));
// While user has not guessed right and does not want to quit
while ((user_number == game_number) || (user_number != 0))
if (user_number > game_number)
System.out.printf("You need to guess lower%n");
else
System.out.printf("You need to guess higher%n");
// Get users next guess
do
System.out.printf("%nEnter your guess, from 1 to 1000 inclusive (0 to quit):");
user_number = data_input.nextInt();
} while ((user_number >= 1) && (user_number <= 1000));
if (user_number == game_number);
// User has guessed right
System.out.printf("%nYou guessed correctly, well done.%nDo you want to play again (y/Y)=Yes: ");
continue_pref = new String(data_input.next());
if (user_number == 0)
// User wants to quit
continue_pref = new String("No");
} while (continue_pref.equalsIgnoreCase("N"));
} (thankyou)Is this posted in two different sections of the forum? Oh well... here you
are, would be a good idea to do as WIlfred_Death suggested and write
out what you need your program to do, then put them in the order for
them to work, and then convert your notes to code, and then you get
like so....
import java.util.*;
import java.io.*;
public class guessgame2{
public static void main(String[] args) throws IOException{
BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
Scanner data_input = new Scanner(System.in);
Random generate = new Random();
int game_number, user_number;
String continue_pref = "Y";
Boolean done = false;
int max = 1000;
int min = 1;
System.out.println("Would you like to play my guessing game?(y/n) ");
continue_pref = userIn.readLine();
continue_pref = continue_pref.trim();
game_number = generate.nextInt(999) + 1;
//System.out.println(game_number);//--->UNCOMMENT THIS IF YOU WANT TO DISPLAY game_number<---
/*-----Run program while user agrees to-----*/
while(continue_pref.equalsIgnoreCase("Y")){
/*-----Let user guess until they win or choose to quit-----*/
while(!done){
System.out.println("Enter your guess, from 1 to 1000 inclusive(0 to quit):");
user_number = data_input.nextInt();
/*-----check if user wants to quit-----*/
if(user_number==0){
continue_pref = "n";
done=true;
else{
/*-----Check if user won-----*/
if(user_number==game_number){
System.out.println("Congradulations you've won! Would you like to continue(y/n)?");
continue_pref = userIn.readLine();
continue_pref = continue_pref.trim();
/*-----If user wants to play again,
regenerate game_number-----*/
if(continue_pref.equalsIgnoreCase("n")){
done=true;
else{
game_number = generate.nextInt(999)+1;
//System.out.println(game_number);//--->UNCOMMENT THIS IF YOU WANT TO DISPLAY game_number<---
}/*-----Check if user number is lower-----*/
else if(user_number<game_number){
System.out.println("You need to guess higher!\n");
else{/*-----Number must be higher-----*/
System.out.println("You need to guess lower!\n");
} -
Problem with simple piece of code - please help
For some reason the following code will not compile - im being told i need a return - however i cant see where or why?
Please help
Thanks
* Author: hc01pl
* Created: 16 April 2002 14:45:48
* Modified: 16 April 2002 14:45:48
//package csci1003testprograms.Gui;
public class Task2
// students id number
private int id;
// students name
private String name;
// students mark 1
private int mark1;
// students mark 2
private int mark2;
// constucts a student with given id, name and two module marks
public void StudentMarks(int aID, String aName, int aMark1, int aMark2)
id = aID;
name = aName;
mark1 = aMark1;
mark2 = aMark2;
// returns student id
public int getID()
return id;
//returns student name
public String getName()
return name;
//returns student's first mark
public int getMark1()
return mark1;
//returns student's first mark
public int getMark2()
return mark2;
//sets the first mark of a student
public void setMark1(int aMark1)
mark1 = aMark1;
//sets the second mark of a student
public void setMark2(int aMark2)
mark2 = aMark2;
//returns the grade of a student
public String getGrade()
int mark = mark1 + mark2;
if (mark<30)
System.out.println("F");
else
if (mark>=30&& mark<40)
System.out.println("U");
else
if (mark>=40&& mark<50)
System.out.println("D");
else
if (mark>=50&& mark<60)
System.out.println("C");
else
if (mark>=60&& mark<70)
System.out.println("B");
else
if (mark>=70&& mark<80)
System.out.println("A");
else
if (mark>=80)
System.out.println("A*");The answer is given by asantoas. You need a return statement. Because your method
public String getGrade(), has a return type String , so the method expects to return a String datatype.
If you don't want to return any thing. Then declare the method as public void getGrade()
Regards
Deepa Datar -
hi! right, I am a java dunce. I am doing a web design degree at uni and annoyingly have to take a programming module. I just don't get it one bit and the lecturer is a sadist and won't help. I have tried countless books and what not but it all goes over my head.... to the problem
We were given some code for a "guess the number" game. it generates a random number between 1 and 1000. You then have to guess the number. If you guess higher it should output "you ned to guess higher" and visa versa. Also if you enter 0 it should exit the program (which it does)
The code had logical and syntax erros in it most of which I think I have managed to find but it still does not work and I have been at this for hours now (even my headache has a headache)
It compiles now but when you enter a number the program just spits out the line "Enter your guess, from 1 to 1000 inclusive (0 to quit):" again but doesn't tell you if you should go higher or lower.
I can only get it to spit out the "you need to guess lower" line if you enter a number above 1000 which is wrong.
please please help me. Just point me in the right direction or something but please use novice language or I think I might have to go jump of the nearest peir.
The code I have so far is:
import java.util.*;
public class guessgame2
public static void main(String[] args)
// Declare variables, setup keyboard input and the
// random number generator
int game_number, user_number;
String continue_pref;
Scanner data_input = new Scanner(System.in);
Random generate = new Random();
do
// Generate game number
game_number = generate.nextInt(999) + 1;
// The following line is a debug line, comment out
// for real game.
// System.out.printf("Game number:%d%n", game_number);
// Get users first guess
System.out.print("The computer has generated a number.");
do
System.out.printf("%nEnter your guess, from 1 to 1000 inclusive (0 to quit):");
user_number = data_input.nextInt();
} while ((user_number >= 1) && (user_number <= 1000));
// While user has not guessed right and does not want to quit
while ((user_number == game_number) || (user_number != 0))
if (user_number > game_number)
System.out.printf("You need to guess lower%n");
else
System.out.printf("You need to guess higher%n");
// Get users next guess
do
System.out.printf("%nEnter your guess, from 1 to 1000 inclusive (0 to quit):");
user_number = data_input.nextInt();
} while ((user_number >= 1) && (user_number <= 1000));
if (user_number == game_number);
// User has guessed right
System.out.printf("%nYou guessed correctly, well done.%nDo you want to play again (y/Y)=Yes: ");
continue_pref = new String(data_input.next());
if (user_number == 0)
// User wants to quit
continue_pref = new String("No");
} while (continue_pref.equalsIgnoreCase("N"));
} (thankyou and sorry about the lack of indenting)You may want to try and write out what you want your program to do on paper and then sort the steps in which order you need them done. And then convert your notes to code.... here's a working version for you
import java.util.*;
import java.io.*;
public class guessgame2{
public static void main(String[] args) throws IOException{
BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
Scanner data_input = new Scanner(System.in);
Random generate = new Random();
int game_number, user_number;
String continue_pref = "Y";
Boolean done = false;
int max = 1000;
int min = 1;
System.out.println("Would you like to play my guessing game?(y/n) ");
continue_pref = userIn.readLine();
continue_pref = continue_pref.trim();
game_number = generate.nextInt(999) + 1;
//System.out.println(game_number);//--->UNCOMMENT THIS IF YOU WANT TO DISPLAY game_number<---
/*-----Run program while user agrees to-----*/
while(continue_pref.equalsIgnoreCase("Y")){
/*-----Let user guess until they win or choose to quit-----*/
while(!done){
System.out.println("Enter your guess, from 1 to 1000 inclusive(0 to quit):");
user_number = data_input.nextInt();
/*-----check if user wants to quit-----*/
if(user_number==0){
continue_pref = "n";
done=true;
else{
/*-----Check if user won-----*/
if(user_number==game_number){
System.out.println("Congradulations you've won! Would you like to continue(y/n)?");
continue_pref = userIn.readLine();
continue_pref = continue_pref.trim();
/*-----If user wants to play again,
regenerate game_number-----*/
if(continue_pref.equalsIgnoreCase("n")){
done=true;
else{
game_number = generate.nextInt(999)+1;
System.out.println(game_number);
}/*-----Check if user number is lower-----*/
else if(user_number<game_number){
System.out.println("You need to guess higher!\n");
else{/*-----Number must be higher-----*/
System.out.println("You need to guess lower!\n");
}
Maybe you are looking for
-
Cellular Connection not working in iPhone 5
My Cellular Data is not working in iPhone 5. I tried to reset the 3G Toggle but still its not working.
-
Ringtone problems...
I am running iTunes 7.4.1.2 But I see no ringtone icon in my music. I looked under view -> view options, but there is no Ringtone item to check. I went to the iTunes store and saw that "Hotel California" is a song that can be made into a ring tone. I
-
How to insert a button on the column header of a table in webdynpro java
Hi Can anyone tell me how to insert a button on the column header of a table in webdynpro java? regards sunit
-
Some videos not in sync with audio..
some of the dvd's i put on my ipod have a problem..the audio is sometimes 6 seconds behind whats going on..how can i fix this when converting?
-
2004s BI & SEM-BCS 6.0 in one System?
Hi, Rumors say you should keep SEM out of your central BI and give it its own BI, to avoid painful patch/release dependencies. Should the SEM-BCS be installed on a separate system, because of patch interdependencies with the central BI? If yes, does