I have a JList and a string that is the JList's selection. If you click a JButton, It displays your JList selection. If you don't click a JList selection, It returns an error, So i used try catch, but it still returned an error.
here is my code, there are no errors in editor.:
#Override
public void actionPerformed(ActionEvent e) {
String choice = chooser.getSelectedValue().toString();
String companyname = name.getText();
try{
JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: " + companyname + "" +"</html>" );
}catch (Exception e1){
JOptionPane.showMessageDialog(frame, "Please fill in both inputs");
}
}
And also the try works fine if there's no error, but the catch just doesn't work. I also tried to catch NullPointerException and if ,else if choose = null, but it still didn't work. Not even the option pane pops up with null in its place.
Just where would expect an exception to occur?
try{
String choice = chooser.getSelectedValue().toString();
String companyname = name.getText();
JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: " + companyname + "" +"</html>" );
}catch (Exception e1){
JOptionPane.showMessageDialog(frame, "Please fill in both inputs");
}
MIGHT be a better solution, given the fact that JList#getSelectedValue will return null if nothing is selected...but then you would need to catch a NullPointerException or Throwable instead of Exception
Updated with example
Branching by exception is not a good way to design applications. Exceptions should be used to trap unexpected states. You would seem that you are expecting invalid results.
A better approach would be to actually inspect each of the values in turn and determine if they are valid.
Object value = chooser.getSelectedValue();
if (value != null && value instanceof String) {
String choice = chooser.getSelectedValue().toString();
String companyname = name.getText();
if (companyname != null && companyname.trim().length() > 0) {
JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: " + companyname + "" +"</html>" );
} else {
JOptionPane.showMessageDialog(frame, "The company name is invalid, please provide one");
}
} else {
JOptionPane.showMessageDialog(frame, "Your company type choice is invalid, please select one");
}
Im fairly sure showMessageDialog() doesn't throw any exceptions, if any probably just a null pointer. Maybe try an if-else.
EDIT Here is some code, this should work as a full replacement.
Code:
if(! choice == null){
if(!companyname.equals("");){
JOptionPane.showMessageDialog(frame, "<html> Welcome to your new Company!<br><br>Company type: "+ choice + " " + "<br>" + "Company Name:" + companyname + "" +"</html>");
}else{
JOptionPane.showMessageDialog(frame, "Please fill in the company name!");
}
}else{
JOptionPane.showMessageDialog(frame, "Plaease fill in choice!");
}
You are actually not guaranteed that the showing of the dialog will be done on the calling thread - if showMessageDialog() is invoked from a background thread, the UI will still be displayed on the event thread - the calling thread will just be blocked until it is closed.
If the UI does throw an exception, it will happen on a different thread and not propagate to your code (have a look at the source code to the AWT event queue to get an idea of the mechanics of this).
Related
I am pretty new to Java and I am doing this project. I keep getting the following error message while I click a jButton (submitButton) in the runtime, and I am not sure why as it is not telling which line the problem is at.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Below is my code, I was wondering if anybody could help? Maybe help me find the error, or tell me what the error message means. Thank you!
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fullName = nameText.getText();
String email = emailText.getText();
String address = addressText.getText();
String phoneNumber = phoneText.getText();
// sets either true or false to membershipSelected if a plan is selected
boolean membershipSelected = standardMembership.isSelected() || silverMembership.isSelected() || goldMembership.isSelected();
double total = 0;
// checks if the text entered in phone number text field can be parsed to an integer
// this is only possible if it is a number, if it is a string, then error pop-up appears
try {
int phone = Integer.parseInt(phoneText.getText());
}
catch(Exception e) {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid phone number, please try again!");
}
// checks if email text field does not contain "#" or a domain
if(!email.contains("#") || !email.contains(".com") && !email.contains(".de") && !email.contains(".co.uk")){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid email address, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if length of phone number is 11, if not shows error pop-up
int phoneLength = Integer.parseInt(phoneText.getText());
if(phoneLength != 11){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This phone number is not long enough, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if a plan is selected, if not shows error pop-up
if(membershipSelected){
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
else {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "Please select a membership!");
}
// sets the final overview to an empty string that can be added to with selections later
String overview = "";
if (standardMembership.isSelected()){
overview = overview + " " + standardMembership.getText() + '\n';
total = 200;
}
if (silverMembership.isSelected()){
overview = overview + " " + silverMembership.getText() + '\n';
total = 450;
}
if (goldMembership.isSelected()){
overview = overview + " " + goldMembership.getText() + '\n';
total = 600;
}
}
You have two places where you perform Integer.parseInt(phoneText.getText());
At the first time, the parsing is surrounded by a try-catch block and that handles the NumberFormatException that would be thrown in case phoneText.getText() is empty or not a number.
The second time, the parsing is not surrounded by any try-catch. This time the NumberFormatException thrown is unhandled and hence you are seeing the Exception.
You should ideally parse the phoneText.getText() once and have your conditions modified accordingly.
I have never done anything in java before so I really am a newb but while building the program I have ran into a snag that i just can't figure out. I will try to explain and show to the best of my abilities.
Here is what I am building
The UI
Here is the code I have so far to make it work.
private void jButtonGenerateActionPerformed(java.awt.event.ActionEvent evt) {
String ObjectName = jtObjectName.getText();
String ObjectBase = jcbBaseNPC.getSelectedItem().toString();
String NPCName = jtNPCName.getText();
String MinLevel = jtMinLevel.getText();
if (MinLevel != null && MinLevel.isEmpty())
MinLevel = MinLevel.replace(MinLevel, "minLevel" + MinLevel);{
}
//Alignment Combo Box Start
String Alignment = jcbAlignment.getSelectedItem().toString();
if (Alignment.contains("Good")) {
Alignment = Alignment.replace("Good", "255");
}
if (Alignment.contains("Neutral")) {
Alignment = Alignment.replace("Neutral", "127");
}
if (Alignment.contains("Evil")) {
Alignment = Alignment.replace("Evil", "0");
}
//Alignment Combo Box End
// Print to Output Box
jaOutput.append("object" + " " + ObjectName + " " + "of" + " " + ObjectBase +
"\n\tproperties" + "\n\tname" +" " + "\"" + NPCName + "\"" + MinLevel
);
What I can not understand it how to check to see if there is something entered in a String and if there is I need to add to it so the output looks like this.
minLevel 1100
maxLevel 1500
only thing I will be adding is the numbers so i need to add something like
minLevel + MinLevel
and if it is empty just skip it all together. If I add it to the append and its empty I will just get minLevel and i can't have it like that.
Any tips would be great.
Thank you all
Donald
My user inputs work fine, my problem is I want an if statement that will say are both inputs equal?, but I get the attached error.
I need the code to be: if cork is entered in batman and robin?. This is what I tried:
System.out.println("From " + batman);
System.out.println("To " + Robin);
if(batman.equals("Cork") + Robin.equals("Cork") {
} else {
System.err.println("");
}
that here:
if(batman.equals("Cork") + Robin.equals("Cork") {
makes no sense because you are doing something like concatenating true with true or similar...
you have to do instead:
if(batman.equals("Cork") && Robin.equals("Cork") {
Your code should look like this :
System.out.println("From " + batman);
System.out.println("To " + Robin);
if(batman.equals("Cork") && Robin.equals("Cork")) {
// Statements
} else {
System.err.println("");
}
You should simply use && when requiring more then one test in an if statement.
+ doesn't work in such cases it simply concatenates values. Hope it helps :)
I need some help writing a program
Using this code I am able to enter in a track name, artist, etc.
I have a problem that I cannot now show this information in JOptionPane to display all of my info
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TestTrack
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
System.out.println("Track name");
String name = myScan.nextLine();
System.out.println("Artist");
String Artist = myScan.nextLine();
System.out.println("Track length seconds");
String seconds = myScan.nextLine();
System.out.println("Album");
String Album = myScan.nextLine();
JOptionPane.showMessageDialog(null,"Trackinfo:")
}
}
So I guess I would want the pop out window to say
Track Name: "blank"
Artist: blank
Another question I have is how to ask this question multiple times by using "while" and asking if I would like to add another track
Sorry if I am using any terminology incorrectly I just started to learn Java
This line: JOptionPane.showMessageDialog(null,"Trackinfo:")
Contains what the pop-up window will contain. You pass in what you want its contents to be as the 2nd parameter, which is currently "Trackinfo".
To incorporate a while loop, you'll have to have a loop control variable, or a condition that will break the loop. In my example I used a string. My example uses a while loop that will continue as long as the string is not equal to "quit".
String test = "";
while( ! test.equals("quit") ) {
//use Scanner to get the next value the user enters
//ask for track info
//display that info in a message box
}
To obtain this:
Note: the texts of the OK and Cancel buttons are localized, if your computer is set to US locale you doesn't see 'Annuler"... ;-)
code this:
int answer = 0;
do {
/*----------------------------------------------------------------------------
Here you put the code which set the variables name, artist, seconds... (1)
----------------------------------------------------------------------------*/
final String title = "Track info";
final String message =
"<html><table>" +
"<tr><td>Track name" + "</td><td>" + name + "</td></tr>" +
"<tr><td>Artist" + "</td><td>" + artist + "</td></tr>" +
"<tr><td>Track length seconds</td><td>" + seconds + "</td></tr>" +
"<tr><td>Album" + "</td><td>" + album + "</td></tr>" +
"</table>";
answer =
JOptionPane.showConfirmDialog(
null, message, title, JOptionPane.OK_CANCEL_OPTION );
} while( answer == JOptionPane.OK_OPTION );
(1) You may choose Scanner or GUI whith JOptionPane.showInputDialog()
JOptionPane.showMessageDialog(null,"Trackinfo:" + "\nArtist: " + Artist + "\nseconds: " + seconds + "\nAlbum: " + Album)
Each '\n' means a new line. for doing this multiple times, you should place your code in a while loop, something like this:
while(!(Artist == "end")) {
//your code
}
Use myScan.next() instead of myScan.nextLine()
To output the information into the Message Dialog, use
String trackInfo = "Track Name: " + name + " | Artist : " +artist+ " | Track Length: " + seconds + " | Album: " + album;
JOptionPane.showMessageDialog(null, trackInfo, "Trackinfo", JOptionPane.INFORMATION_MESSAGE);
Problem solved.
I have two methods in my class.
private void retrieveDetails(){
List<String> details = File.getCredentials();
username = details.get(0);
pw = details.get(1);
}
private void checkCredentials() throws IOException {
retrieveDetails();
System.out.println("\nPlease enter USERNAME: ");
String usersName = scan.next();
System.out.println("\nPlease enter PASSWORD: ");
String usersPW = scan.next();
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw);
if (usersName.equals(username) && usersPW.equals(pw)) {
doWork();
} else {
System.out.println("Incorrect credentials");
}
}
I thought I came up with a solution by moving the following up to where my strings are initialized.
List<String> creds = File.getCredentials();
I created a System.out statement to check if the details coming from retrieveDetails() match those entered by the users. They do match - but when the system goes to the else clause instead of executing doWork();
If what is printed is the same then try trimming before comparing. E.g.:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
When i have similar problem i do this simple trick:
Print the size of the strings you are comparing because sometimes you have characters like \n or \r which are not visible when you print the string.
First of all, it seems like you have a typo in sysout statement below.
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw); //Should be username
Secondly, you might wanna trim the strings for better string comparison.
Sometimes strings read from file or console can contain unwanted and hard-to-catch empty strings like spaces and tabs. These can be removed by calling .trim() method on strings.
Thus, try using the following code instead:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
}
usersName.equals(username) && usersPW.equals(pw).
I have faced these problem also, These kind of equality always tricky, Try to trim the strings that you are going to compare, as well as if you can compare these strings based on their length.
if (usersName.trim().equalsIgnoreCase(username.trim()) && usersPW.trim().equalsIgnoreCase(pw.trim()))
or
if (usersName.trim().length()==username.trim().length && usersPW.trim().length()==pw.trim().length))