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");
}
}
Related
I'm a complete beginner to Java and I have been given an exercise where I have to read data from a CSV file and then create an object for each line of the file as the program reads the data from the file.
Here is part of the CSV file:
1,Jay, Walker,91 Boland Drive,BAGOTVILLE,NSW,2477
2,Mel, Lowe,45 Ocean Drive,MILLERS POINT,NSW,2000
3,Hugh, Manatee,32 Edgecliff Road,REDFERN,NSW,2016
4,Elizabeth, Turner,93 Webb Road,MOUNT HUTTON,NSW,2290
and so on ...
Here is my code that reads data from the CSV file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Client_19918424 {
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("clients.txt");
Scanner inputFile = new Scanner(inFile);
String str;
String[] tokens;
while (inputFile.hasNext()) {
str = inputFile.nextLine(); // read a line of text from the file
tokens = str.split(","); // split the line using commas as delimiter
System.out.println("Client ID: " + tokens[0]);
System.out.println("Client First Name: " + tokens[1]);
System.out.println("Client Sur Name: " + tokens[2]);
System.out.println("Street Address: " + tokens[3]);
System.out.println("Suburb: " + tokens[4]);
System.out.println("State: " + tokens[5]);
System.out.println("Postcode:" + tokens[6]);
System.out.println( );
} // end while
}
}
this is my Client class (have constructor):
public class Client {
private int clientID;
private String firstName;
private String surName;
private String street;
private String suburb;
private String state;
private int postcode;
// constructor
public Client (int ID, String fName, String sName, String str, String sb, String sta, int pCode) {
clientID = ID;
firstName = fName;
surName = sName;
street = str;
suburb = sb;
state = sta;
postcode = pCode;
}
However I don't know how to create a Client object for each line of text file as the program reads data from file.
like for the first line make something like this:
Client client1 = new Client(1, "Jay", "Walker", "91 Boland Drive", "BAGOTVILLE", "NSW", 2477);
And then add it to array:
Client[0] = client1;
can someone help me to solve this question, im really appreciate.
You are almost there.
All that's left to do is to map each token that is already printed to the corresponding fields in the Client class. Since token[0] doesn't really tell what value it holds you could do it in three ways:
while (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
// Because tokens[0] is of type String but clientID is of type int,
// we need to parse it and get the integer representation.
int clientID = Integer.parseInt(tokens[0]);
// Both of type String, no parsing required.
String firstName = tokens[1];
String surName = tokens[2];
String street = tokens[3];
String suburb = tokens[4];
String state = tokens[5];
int postcode = Integer.parseInt(tokens[6]);
// Then all that's left to do is to create a new object of `Client` type
// and pass all the gathered information.
Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);
System.out.println(client + "\n");
}
At this moment if we try to print the client (last line) we will get something like this: com.example.demo.Client#30a3107a. That's because we didn't tell how we want our object to be displayed. For that toString() method in Client class has to be overriden like so:
#Override
public String toString() {
return "Client ID: " + clientID + "\n" + "Client First Name: " + firstName + "\n"
+ "Client Sur Name: " + surName + "\n" + "Street Address: " + street + "\n"
+ "Suburb: " + suburb + "\n" + "State: " + state + "\n" + "Postcode: " + postcode;
}
It will give the exact output that is in your example.
It is achievable to create the class by passing those tokens directly as well, without the creation of temporary variables:
Client client = new Client(Integer.parseInt(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], Integer.parseInt(tokens[6]));
This case brings us to the third solution with setters and getters.
The variables that describe the Client are already defined, it is possible to pass them to assemble the perfect object, but it is not possible to retrieve them. Instead of setting the variables directly in the constructor, we can create a special method that will do the job, for instance:
// Other fields omitted
private int clientID;
// The empty constructor required for later usage,
// since right now, we can't create the object without specifying every property.
public Client() {
}
// This method does exactly the same thing that was done before but
// in the constructor directly
public void setClientID(int clientID) {
this.clientID = clientID;
}
// This method will assist in retrieving the set data from above.
public int getClientID() {
return clientID;
}
And then the while loop would look like this instead:
Client client = new Client();
client.setClientID(Integer.parseInt(tokens[0]));
client.setFirstName(tokens[1]);
client.setSurName(tokens[2]);
client.setStreet(tokens[3]);
client.setSuburb(tokens[4]);
client.setState(tokens[5]);
client.setPostcode(Integer.parseInt(tokens[6]));
And to get those values:
System.out.println("Client ID: " + client.getClientID());
Or you could use the constructor with the fields to create the client, add getters in the class, omit both setters, and the empty constructor if the creation of the client should only be possible with all the fields present.
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);
I'm just getting started with Java (via an edX class), and one of the assignments is to create a vacation planner program that gathers information from the user. When I run the code in terminal, it works, but the strings "name" and "place" are not displayed correctly. Instead, the lines after the string declarations are displayed as "Nice to meet you + name + where are you traveling to?". Am I missing something that would have the input assigned to "name" displayed in the sentence?
The code below is for 1 of 4 methods that will be in the program. Image of my output:
import java.util.Scanner;
public class projectplanner{
public static void main(String[] args) {
partOne();
partTwo();
partThree();
partFour();
}
public static void partOne() {
[enter image description here][1] Scanner input = new Scanner(System.in);
System.out.print("Welcome to Vacation Planner!");
System.out.print("What is your name?" + "");
String name = input.nextLine();
System.out.println("Nice to meet you " + name + "where are you travelling to?");
String place = input.nextLine();
System.out.println("Great! " + place + " sounds like a great trip.");
}
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StarWars {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String firstName = "";
String lastName = "";
String maidenName = "";
String town = "";
System.out.print("What is your first name? ");
firstName = reader.nextLine();
System.out.print("What is your last name? ");
lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
maidenName = reader.nextLine();
System.out.print("What town were you born? ");
town = reader.nextLine();
String Sfirstname = firstName.substring(0,2);
String Slastname = lastName.substring(0,3);
String SmaidenName = maidenName.substring(0,2);
String Stown = town.substring(0,3);
String Star = Sfirstname + Slastname;
String War = SmaidenName + Stown;
String StarWar = Star + War;
System.out.print("Your Star Wars name is: " + StarWar);
}
public static String StarWar (String Star, String War) {
String name;
name = Star + " " + War;
return War;
}
}
So this is my code about my project. While I'm doing my project I have some problem about the returning method and passing method.
I set up the main method perfectly to print out thing that what I want to see.
The problem is I also have to use passing method and returning method. My teacher want me to do two things with passing/returning method.
Pass all this data to your method, and the method should generate and return the users Star Wars name.
Get the return value of the method, and display it to the screen.
I have no idea what should I do with this problems (took 5 hrs to do everything I learn but wrong..).
Can someone give a hint or teach me what actually my teacher want me to do and How I can do this?
I really need help from you guys.
Additional, if I run a program it should be like this.
first name? user input: Alice last name? user input:Smith mothers maiden name? user input: Mata town were you born? user input: Sacramento
Your Star Wars name is: SmiAl MaSac
There are a few things we can improve here, lets start with the method - the method name looks like a constructor and doesn't perform the logic itself, lets describe what it does and move the logic into the method - we don't need all of those temporary variables (we can use a StringBuilder) like
public static String buildStarWarsName(String firstName, String lastName,
String maidenName, String town)
{
return new StringBuilder(lastName.substring(0, 3)) //
.append(firstName.substring(0, 2)) //
.append(" ") // <-- for the space between first and last
.append(maidenName.substring(0, 2)) //
.append(town.substring(0, 3)) //
.toString();
}
Then you can initialize your variables when you read them and finally call the method
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("What is your first name? ");
String firstName = reader.nextLine();
System.out.print("What is your last name? ");
String lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
String maidenName = reader.nextLine();
System.out.print("What town were you born? ");
String town = reader.nextLine();
System.out.print("Your Star Wars name is: " + //
buildStarWarsName(firstName, lastName, maidenName, town));
}
You should return what you evaluated instead :
return name;
and then call this defined method while you want to read the value.
The changes highlighted in the comments as well:
String StarWar = Star + War; // this would not be required, as handled by your method 'starWarName'
System.out.print("Your Star Wars name is: " + starWarName()); // calling the method defined
}
public static String starWarName (String Star, String War) { //renamed method to break the similarity with other variables
String name;
name = Star + " " + War;
return name; //returning the complete star war name
}
Your method is returning the 'war' parameter. Based on what your trying to do it looks like it should be returning 'name'. That's what the method built.
/**
* #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