How do I make it so JOptionPane.showMessageDialog can sense multiple strings? - java

/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String grade = JOptionPane.showInputDialog(null, "Please Specify Your Grade");
String First_name = JOptionPane.showInputDialog(null, "What is your First Name?");
String Last_name = JOptionPane.showInputDialog(null, "What is your Last Name?");
]JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
}
How do I get the part where it says "Your Last Name is " + Last_Name to print the correct string? in my code it says that the string cannot be converted to an integer but the rest of that line works fine (using Netbeans IDE)

You are trying to pass multiple messages as separate parameters to the method JOptionPane.showMessageDialog, however the method only accepts a single message parameter. However, this parameter is not limited to just Strings; you can actually pass any Object as the message. See the JOptionPane javadocs for details on how JOptionPane handles various types of message parameters.
I think there are a couple approaches that could be used. One approach is to create a String that concatenates all of the results together. My suggestion would be to use a newline character (\n) to concatenate the results, so they appear one per line. Here is an example:
String message = "You are a " + grade + "\n"
+ "Your Name is " + First_name + "\n"
+ "Your Last Name is " + Last_name;
JOptionPane.showMessageDialog (null, message);
Another approach is to create an array out of the results, and pass the array as the message parameter:
String[] message = {
"You are a " + grade,
"Your Name is " + First_name,
"Your Last Name is " + Last_name
};
JOptionPane.showMessageDialog (null, message);

works also in the constructor :
JOptionPane.showMessageDialog(null, "You are a " + grade+ "\nYour Name is " + First_name+
"\nYour Last Name is " + Last_name);
and probably delete ] in your last line of code

JOptionPane has 3 showMessageDialog() methods, each with different arguments, let's look at each of them, but first we're going to use the following String:
String message = "You are a " + grade + " Your Name is " + First_name " Your Last Name is " + Last_name;
showMessageDialog(Component parentComponent, Object message) this method recieves the parentComponent (it shouldn't be null, instead pass the reference to your JFrame because otherwise you won't be blocking the parent component, so it won't be a modal Dialog) and the message, in your case it would be the String containing the name, last name, etc, you could use it this way:
JOptionPane.showMessageDialog(frame, message);
showMessageDialog(Component parentComponent, Object message, String title, int messageType) this method allows you to modify the icon (or the message type (A list of the full message types can be found on the docs) and the title of the dialog and you can use it as:
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) this allows you to use a custom icon and you can use it this way:
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
For more information you can check How to use Dialogs
Now, if you want to improve the format you can either use html tags as:
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
Or create your own custom JPanel where you add your components to it and then add that JPanel to the showMessageDialog on the Object message argument, but I'm leaving that part to you
This code will create the above output images, however you need to change the image path to your own path, the custom icon has been taken from here
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class DialogExamples {
private JFrame frame;
private ImageIcon icon = new ImageIcon("/home/jesus/Pictures/L5DGx.png");
public static void main (String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DialogExamples().createAndShowGui();
}
});
}
public DialogExamples() {
System.out.println(icon);
}
public void createAndShowGui() {
frame = new JFrame("Example");
String name = "Your name is Frakcool";
String grade = "Your grade is 5";
String lastname = "Your lastname is YajiSuzu";
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
// String message = name + " " + lastname + " " + grade;
JOptionPane.showMessageDialog(frame, message);
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
In your case you're getting the exception:
String cannot be converted to an int
because you're sending 4 parameters here:
JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
In this case, you're using the 2nd method I showed you above, so it's expecting to receive an int messageType on the 4th parameter, not a String.
This isn't something as a console.log() in JS, here you concatenate Strings with + operator, not with a , (comma).
NOTE:
As an aside note, your variable and method names should start with lowerCamelCase while your classes should start with UpperDromedaryCase as stated on the Java naming conventions
NOTE2:
You're not placing your program on the EDT which could cause you problems in the future, so be careful, my above code already solved that problem

Related

How do I save the input data received by JOptionPane?

I'm busy studying Javascript as my first language, so I am very new. I am busy with a project for generating company e-mails and passwords, and I want to use JOptionPane to show a pop-up for the user to enter their details e.g. first name, last name etc.
I want to use the information, that was entered, to generate an e-mail for that specific employee. How would I do this?
This is how I wrote it to see that I can generate e-mail addresses correctly. How would I utilise JOptionPane in this?
public Email(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.department = setDepartment();
System.out.println("Department: " + this.department);
this.password = randomPassword(defaultPasswordLength);
System.out.println("Your password is: " + this.password);
email = firstName.toLowerCase() + "." + lastName.toLowerCase() + "#" + department + companySuffix;
System.out.println(email);
}
I am also new to Java, so there are probably better answers than mine, but I know that to use JOptionPane you first import javax.swing.JOptionPane; then you create the variable name and set it equal to an input dialog box.
The input will be stored under the variable name as a string that you can call later in the program.
Remember that if you ever want the user to input a number, the input will still be stored as a string and you will have to use a parse method to convert it to a number.
import javax.swing.JOptionPane;
public class JavaApplication1 {
public static void main(String[] args) {
String firstName = JOptionPane.showInputDialog("Type your first name");
String lastName = JOptionPane.showInputDialog("Type your last name");
JOptionPane.showMessageDialog(null, "Your email is: "
+ firstName.toLowerCase() + "." + lastName.toLowerCase()
+ "#email.com");
}
}

Java - Extracting Substrings Programmatically

I am trying to create a code that accepts a user's full name and returns first and last names and initials. Since a user's name length varies, I did not want to use hard coding, so I extract names and initials programmatically.
However when I run it and enter a name, I get the following error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
I looked into my code carefully and cannot see where exactly I miscalculated on the index range. I tried to find similar questions here, but though I did see similar problems, they have to do with C++ or Perl, not Java.
package nameSubstring;
import java.util.Scanner;
public class NameSubstring {
public static void main(String[] args) {
/*
* This is a program that accepts a user’s full name as a string (e.g. Margaret Thatcher) and displays to the user his/her first name, last name and initials in the following format:
Your first name is Margaret and your last name is Thatcher and your initials are MT.
*/
System.out.println("This program will take your full name and display your first name, last name, and initials.");
Scanner scanner = new Scanner(System.in);
String firstName, lastName, firstNameInitial, lastNameInitial;
System.out.println("Please enter your full name, e.g. Jane Smith:");
String fullName = scanner.next();
int nameSpace = fullName.indexOf(' ');
firstName = fullName.substring(0, nameSpace);
lastName = fullName.substring(nameSpace)+1;
firstNameInitial = firstName.substring(0, 1);
lastNameInitial = lastName.substring(0, 1);
System.out.println("Your first name is " + firstName + ", " + "your last name is " + lastName + ", " + "and your initials are " + firstNameInitial + lastNameInitial + ".");
}
}
Instead of next() use nextLine():
String fullName = scanner.nextLine();
and correct the error with the +1 which must be inside the parenthesis:
lastName = fullName.substring(nameSpace+1);

Voting System Error

So, currently my voting system works well but now I'm getting a divide by zero code :/. This shouldn't be happening because the "Total integer always has a numerical value greater than zero (unless I'm missing Something?). Anyways I want the program to take votes and organize them as female and male voters and whether they voted for Trump or Clinton.
package vote;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class vote {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Declare Strings and Initialize
String PCandidate1=null;
String Gender1=null;
String Economy1= null;
//Declare Integer
int Age;
int Trump=0;
int Clinton=0;
int Male=0;
int Female=0;
int MaleT=0;
int FemaleT=0;
int MaleC=0;
int FemaleC=0;
int Young=0;
//all data read from a dialog box comes into a string
String svalue,output ="";
//Need to Implement While loop to keep collecting data
int counter=0;
while(counter<4) {
counter++;
//Vote for Presidential Candidate and Tally the Votes!
svalue =JOptionPane.showInputDialog(null,"Will you Vote for Clinton or Trump?","Input Data", JOptionPane.QUESTION_MESSAGE);
svalue=JOptionPane.showInputDialog(null,"Are you Male or Female (M/F)?","Input Data", JOptionPane.QUESTION_MESSAGE);
if (svalue.equals("trump")||(svalue.equals("Trump")))
{
if (svalue.equals("F")||(svalue.equals("f")))
Trump++;
Female++;
FemaleT++;}
if (svalue.equals("Trump")||(svalue.equals("trump")))
{
if (svalue.equals("M")||(svalue.equals("m")))
MaleT++;
Trump++;
Male++;}
if (svalue.equals("clinton")||(svalue.equals("Clinton"))){
if (svalue.equals("M")||(svalue.equals("m")))
Clinton++;
MaleC++;
Male++;}
if (svalue.equals("Clinton")||(svalue.equals("clinton"))){
if(svalue.equals("F")||(svalue.equals("f")))
FemaleC++;
Clinton++;
Female++;}
PCandidate1= (svalue);
//Inpute Users Age
svalue=JOptionPane.showInputDialog(null,"What is Your Age?","Input Data", JOptionPane.QUESTION_MESSAGE);
Age=Integer.parseInt(svalue);
if (Age<=25)
Young++;
// Get Users Input about State of the Economoy
svalue=JOptionPane.showInputDialog(null,"Do you feel the economy is getting better?","Input Data", JOptionPane.QUESTION_MESSAGE);
Economy1= (svalue);
}
int Total=Male+Female;
//Output The Data to Form
output=output+"Users Voted For Trump: " + Trump +"\n"
+ "Users Voted For Clinton: " + Clinton+ "\n"
+"Total Users Polled: " +(Total)+"\n"
+ "Male Voters: " + Male+ "\n"
+ "Female Voters: " + Female+ "\n"
+ "% Female Voters for Clinton: " + (FemaleC/Clinton)*100+ "\n"
+ "% Male Voters for Clinton: " + (MaleC/Clinton)*100+ "\n"
+ "% Female Voters for Trump: " + (FemaleT/Total)*100+ "\n"
+ "% Male Voters for Trump: " + (MaleT/Total)*100+ "\n"
+ "Number of Young People Polled: " + Young+ "\n"
;
//write all in a dialog box
JOptionPane.showMessageDialog(null,
output,"Output:",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
You have a lot of problems with your if-statements:
if (svalue.equals("clinton")||(svalue.equals("Clinton"))){
if (svalue.equals("M")||(svalue.equals("m")))
Clinton++;
MaleC++;
Male++;}
You don't have brackets in your second if statement.
Your if's check whether a value is equal to both "Clinton", and "m". This means that your second if-statement will never be entered. So Clinton will never be updated and will always be zero. (And we thought it was the Russians..)
You need to have a second variable for whether the voter is male or female and check this in your second if-statement instead of overriding svalue
Side note: proper indenting will help you spot these errors
So something more like this:
gender =JOptionPane.showInputDialog(null,"Are you Male or Female (M/F)?","Input Data", JOptionPane.QUESTION_MESSAGE);
//…
if (svalue.equals("clinton")||(svalue.equals("Clinton"))){
if (gender.equals("M")||(gender.equals("m"))) {
Clinton++;
MaleC++;
Male++;
}
//Etc

Multidimensional array condition in Java

I want to pun a condition in an multidimesional array and I'm stuck. My method should return a name in a specific format. If find a title like (Mr.,Mrs) return Title , first letter from name , and the full surname. If title is not found return full name + full surname. Eg. Ms. S. T. Mark or Smith T. Rose or Tony Mark.
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. ","Miss"},
{"Smith ", "Jones "},
{"Tony ", "Jhon "},
{"Mark ","Rose "}
};
if (names[0].equals(names)&& names[1].equals(names)&&names[2].equals(names)&& names[3].equals(names)){
return names[0][0] + names[1][0].substring(0,1)+". " + names[2][0].substring(0,1)+". "+names[3][0];}
return"";
As I wrote in the comment this doesn't make sense:
names[0].equals(names)
names[0] is string array (String[]) containing: {"Mr. ", "Mrs. ", "Ms. ","Miss"}
While names is array of string arrays (String[][]) containing everything, so you can't compare them in such way, it will always be false.
Moreover you actually shouldn't ever use equals for arrays. Please check this post for more information:
https://stackoverflow.com/a/8777266/7624937
Now, as suggested by #Tschallacka you should probably create Person class, e.g:
class Person {
String title;
String name;
String surname;
}
and then implement functions which are of your interest. So according to your description such function would look like this:
public String introduceYourself() {
if (title != null) {
return title + " " + name.charAt(0) + " " + surname;
} else {
return name + " " + surname;
}
}

Java Error, Incompatible types: Object cannot be converted to string

I almost finished creating this simple code, but I keep getting an error when making my input dialog box from JOptionPane and giving it a variable.
For instance:
name = JOptionPane.showInputDialog(null, "What is your name?",
"Question",
JOptionPane.QUESTION_MESSAGE,
iconhello,
null,
"");
When the name is in front, I get the error, when it is not there are no errors and my code runs smoothly, but I need to return the input into a message dialog which I create later in my code.
This is the full code:
public static void main(String[] args) {
String name, choice, choice2, choice3, order;
ImageIcon iconhello;//identifying the new icon created
iconhello = new ImageIcon("hello.gif");
ImageIcon iconcat1;
iconcat1 = new ImageIcon("cat1.gif");
ImageIcon iconcat7;
iconcat7 = new ImageIcon("cat7.gif");
ImageIcon icondrink;
icondrink = new ImageIcon("drink.gif");
ImageIcon iconpizza;
iconpizza = new ImageIcon("pizza.gif");
name = JOptionPane.showInputDialog(null, "What is your name?",
"Question",
JOptionPane.QUESTION_MESSAGE,
iconhello,
null,
"");
Object[] possibilities= {"Chicken Sub", "Chicken Teriyaki Sub", "Tuna "
+ "Sub", "Vegetable Sub"};//creating options for user to choose from
choice= (String)JOptionPane.showInputDialog(null, "What type of"
+ " subsandwich do you like? \n \"I like...\"",
"Subsandwich",
JOptionPane.QUESTION_MESSAGE,
iconpizza,
possibilities,
"Chicken Sub");
Object[] possibilities1= {"Sprite", "Coke", "7Up", "Pepsi"};
choice2= (String)JOptionPane.showInputDialog(null, "What type of"
+ " drink do you prefer to have? \n \"I prefer..\"",
"Drink",
JOptionPane.QUESTION_MESSAGE,
icondrink,
possibilities1,
"Sprite");
JOptionPane.showInputDialog(null, "Please state what you would like"
+ " to have additionally",
"Additional Request",
JOptionPane.INFORMATION_MESSAGE,
iconcat1,
null,
"");
order= String.format("Your order: \n " + choice + " \n" + choice2 +
" \n Please enjoy!",
"Order for: " + name + " " ,
JOptionPane.PLAIN_MESSAGE,
iconcat7,
null);
JOptionPane.showMessageDialog(null, order);
}
Please, help me if you can.
The showInputDialog method that you're calling returns an Object, but you're assigning the returned value to a String variable. The error message is telling you that Java won't implicitly make this conversion for you, you have to do it explicitly. You've got it right a few lines later in your code.
choice = (String)JOptionPane.showInputDialog(null, "What type of"
+ " subsandwich do you like? \n \"I like...\"",
"Subsandwich",
JOptionPane.QUESTION_MESSAGE,
iconpizza,
possibilities,
"Chicken Sub");

Categories