I have a form that give Fname and Lname and Date and a method to write this information to a file.
If Fname or Lname contain digit, the program should display an error message and not run all below statements ,(like write to file and generate random number and...), and not exit.
since i dont know how to do like this, in my code i write if Fname or Lname have digit, exit !
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
please help!
That's why you need checked exceptions. Just throw SomeException instead of System.exit(1) and process it properly in block:
catch (SomeException e){
jLabel6.setText("Error!");
}
Don't think that catching all exceptions is a good idea.
Here's one way you could do it:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
setLName(jTextField2.getText());
boolean firstNameHasDigit = havedigit(getFName());
boolean lastNameHasDigit = havedigit(getLName());
if (firstNameHasDigit || lastNameHasDigit) {
jLabel6.setText("Names cannot contain digits");
}
else {
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
As a general rule, try to stay away from using System.exit() in GUI-driven applications. It'll just make the whole program quit, leaving the user wondering what happened. System.exit() is usually better suited for command line applications that want to provide an exit code to the shell and it's a parallel to the system exit calls available in most operating systems.
Try this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())) {
jLabel6.setText("First name error!");
return;
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
jLabel6.setText("Last name error!");
return;
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
should be
if(havedigit(getFName())) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
Search on Google about how to use JOptionPane.showMessageDialog.
In your if statements, instead of
System.exit(1);
You should have something
throw new MyException("Error Text");
and then your catch should look like this:
catch(MyException e){
jLabel6.setText(e.getMessage());
}
where MyException extends Exception.
Related
I have to read a file in try block and later print it out. While the print method is working, the program is not running the method. How do I solve this? I can't keep it in the while loop.
Lexer.java
private boolean atEOF = false;
private SourceReader source;
public static void main(String args[]) {
Token token;
try {
Lexer lex = new Lexer(args[0]);
while(!(lex.atEOF)) {
token = lex.nextToken();
}
lex.source.printVec(); // WANT TO EXECUTE THIS METHOD
} catch (Exception e) {
System.out.println("usage: java lexer.Lexer filename.x");
System.exit(-1);
}
}
SourceReader.java
public void printVec() {
System.out.println("in the program");
for (String l : progVec) {
System.out.println(l);
}
}
How do I run printVec() after the while loop in Lexer.java?
I would simply declare the Lexer outside of the try-catch block then put the required Function at the first line of the catch part too.
Lexer lex;
try {
lex = new Lexer(args[0]);
while(!(lex.atEOF)) {
token = lex.nextToken();
}
lex.source.printVec();
} catch (Exception e) {
lex.source.printVec();
//... rest of code
}
I am working on a turtle graphics project and I'm attempting to retrieve a user input from a jtextfield (commField) which should be like: ' forward 100 ' I've attempted to do a string split and intparse however when the program is run, even when a correct command is entered it will go to the message error dialogue. After a few hours of turning the cogs in my brain I'm struggling to figure out why and so am asking for any help. If more of my code is needed for an answer that is fine, perhaps I'm focusing on the wrong thing.
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
}
});
Below is the full code block for those who want it:
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(commField.getText().contains("penup")) {
graphicsPanel.penUp();
}
else if(commField.getText().contains("pendown")) {
graphicsPanel.penDown();
}
else if(commField.getText().contains("turnright")) {
graphicsPanel.turnRight();
}
else if(commField.getText().contains("turnleft")) {
graphicsPanel.turnLeft();
}
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
System.out.println(commField);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("black")) {
graphicsPanel.black(Color.black);
}
else if(commField.getText().contains("green")) {
graphicsPanel.green(Color.green);
}
else if(commField.getText().contains("red")) {
graphicsPanel.red(Color.red);
}
else if(commField.getText().contains("reset")) {
graphicsPanel.clear();
}
else {
JOptionPane.showMessageDialog(textArea, "Invalid command, try again");
}
commField.setText("");
graphicsPanel.repaint();
}
});
Line of interest:
String cForward = commField.toString();
JTextField.toString() does not return the content of the JTextField.
I checked my java 8 sources and found the following:
public String toString() {
return getClass().getName() + '[' + paramString() + ']';
}
However, the toString() method is intended to be a debugging utility. Unless its behavior is explicitly documented it is not recommended to rely on it programmatically.
For retrieving its text content, JTextField provides a separate method: JTextComponent#getText(). The line should therefore be changed to:
String cForward = commField.getText();
I am writing an if-else condition in my test case. But function not going in else condition , it just look for if (condition).I am not able to figure out the problem.
Using java with selenium webdriver
public static void afterMenthod() throws InterruptedException {
try {
if (remoteDriver.findElementByName("Confirmation").isDisplayed())
{
if (remoteDriver.findElementByName("Stop").isDisplayed())
{
remoteDriver.findElementByName("Stop").click();
}
else
{
remoteDriver.findElementByName("Resume").click();
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
}
}
else if (remoteDriver.findElementByName("TRY AGAIN").isDisplayed())
{
System.out
.println("There is some problem in deposit transaction");
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
remoteDriver.findElementByName("Stop").click();
}
else if (remoteDriver.findElementByName("NEXT").isDisplayed() || remoteDriver.findElementByName("SUBMIT").isDisplayed() )
{
System.out.println("There is some problem in deposit transaction");
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
}
else {
// if(remoteDriver.findElementByName("namaskaar").isDisplayed())
System.out
.println("There is some problem in deposit transaction");
}
} finally{
GeneralMethods.signout();
System.out.println("Script Over");
}}
It just look for "confirmation" element, if it does not find that test get fails.
Try checking whether the element is displayed AND enabled
WebElement confirmation = remoteDriver.findElementByName("Confirmation");
if ( confirmation.isDisplayed() && confirmation.isEnabled()) {
...
}
else {
...
}
Write Your Else Part In catch block.
This way if an exception occurs, your else block will get executed.
It worked for me.
My Code to find a element in scroll-able screen and click it.
public static void scrollToBeFound(String Value) throws InterruptedException{
try{
driver.findElementByName(Value).click();
Thread.sleep(5000);
}
catch(Exception e){
try{
driver.swipe(120,420,120,750,1500);
Thread.sleep(3000);
driver.findElementByName(Value).click();
}
catch(Exception ex){
driver.swipe(120,750,120,420,1500);
Thread.sleep(3000);
driver.findElementByName(Value).click();
}
}
}
"It just look for "confirmation" element, if it does not find that test get fails." - that's because findElementByName throws an exception if element is not found. Which is why the else is not getting processed. You need to use try-catch-finally in your code. Search any forum on how to use it.
I am making a gui for POP3 commands I am having a problem editing my JTextPane in the GUI outside of the initialize() method
Part of the Action Listener:
public void actionPerformed(ActionEvent e)
{
String Input = Commands.getText();
verifyUserAndPass();
if(Input.substring(0).equals("QUIT")) {
System.exit(0);
}
if(Input.substring(0,4).equals("LIST")) {
ListCommand(Input);
}
if(Input.substring(0,4).equals("STAT")) {
ListCommand(Input);
}
if(Input.substring(0,4).equals("RETR")) {
try {
RETRCommand(Input);
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(Input.substring(0,4).equals("DELE")) {
Delete(Input);
}
if(Input.substring(0,4).equals("NOOP")) {
Display.setText("+OK");
}
if(Input.substring(0,4).equals("UIDL")) {
if(userEntered == true && passEntered == true) {
Display.setText("the UIDL is"+String.valueOf(ui));
ui++;
}else {
Display.setText("Please sign in first");
}
}
if(Input.substring(0,3).equals("TOP")) {
try {
TOP(Input);
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(Input.substring(0,4).equals("RSET")) {
Delete(Input);
}
the verifyUserAndPass method:
public void verifyUserAndPass() {
String Input = Commands.getText();
System.out.println(Input+"randomstring");
if(Input.substring(0, 4).equals("USER")) {
try {
if(verifyUser(Input.substring(5))) {
Display.setText("+OK");
Commands.setText("");
userEntered = true;
} else {
Display.setText("-ERR");
}
} catch (IOException e1) {
e1.printStackTrace();
Display.setText("-ERR");
}
}
if(Input.substring(0, 4).equals("PASS")) {
try {
if(userEntered == true) {
if(verifyPass(Input.substring(5))) {
Display.setText("+OK");
Display.setText("Welcome, you are now logged in");
Commands.setText("");
passEntered = true;
} else {
Display.setText("-ERR");
}
} else {
Display.setText("Please enter USER first");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Commands is a JTextField,
Display is a JTextPane.
for some reason, I can edit Commands outside the ActionListener but not Display
e.g. The Display.setText under the NOOP if works but not the one in verifyUserAndPass() method
but the Commands.setText works
What am I doing wrong?
It is quite hard to answer this question without you providing more details, but I can name a common issue:
Display may not be initialized, check your program's flow and then you can see why it is not being initialized.
Moreover, please abide the Java conventions for everyone's sake. Variables and methods are typed in camelcasing. So these ones would need to be changed:
String Input to String input.
ListCommand() to listCommand().
etc. I hope you get the idea.
I was doing a project in JAVA Swing Netbeans IDE 7.1. I created one jFrame with some button and Dropdowns on it. On selecting a choice from the dropdown,another frame object is created and setVisible is set to true. But instead of showing one window, it is showing up 2 windows. There are other similar calls, but none have this issue, someone please help me. Thanks.
Code:
private void itemListItemStateChanged(java.awt.event.ItemEvent evt) {
String item = null;
String filename = null;
item = (String) itemList.getSelectedItem();
if(item=="P"){
filename="p";
description.setText("Description: P");
}
else if(item=="A"){
filename="a";
description.setText("Description: A");
}
else if(item=="R"){
filename="r";
description.setText("Description: R");
}
else if(item=="S"){
filename="s";
description.setText("Description: S");
}
else if(item=="X"){
displayText.setText("");
x xl = new x();
xl.setVisible(true);
}
else if(item=="Xx"){
filename="xx";
description.setText("Description: xx");
}
else {
System.out.println("invalid selection.");
}
if (item=="X"){
return;
}
else {
displayText.setText("");
BufferedReader b = null;
try {
b= new BufferedReader(new FileReader ("/home/sfred/"+filename+".mile"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
line = b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
while (line != null){
displayText.append(line + "\n");
try {
line=b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
See The Use of Multiple JFrames, Good/Bad Practice? rather use :
1) JDialog
2) CardLayout which will allow you to flip between multiple components on a single JFrame.
You cannot compare String using ==operator must use equals(String s) or else it wont evaluate correctly
if(item.equals("X")) {
}
Rather use switch statement (Java 7+) when comparing String:
switch(item) {
case "P":
//do something
break;
case "X":
//do something
break;
default:
//if no match with above was found..
break;
}