how to refer to strings from input dialog? - java

I need to prompt the user to enter their full name and once they do I need two separate messages to show them your first name is and your last name is. I have everything but what I need to code for the firstName and lastName string. I feel like it has something to do with indexOf? but I can't get it to work correctly.
public class project2b {
public static void main (String [] args) {
String firstName;
String lastName;
String fullName;
firstName =
lastName =
fullName = JOptionPane.showInputDialog(null, "What is your full name?");
JOptionPane.showMessageDialog(null, " Your first name is " +
firstName);
JOptionPane.showMessageDialog(null, " Your last name is " +
lastName);
}
}

String[] names = fullName.split ("\\s");
firstName = names[0];
lastName = names[1];

InputDialog will only return a single String. You need to parse it. String has a handy split() method that will do the parsing for you.
Assuming the user enters their first and last name separated by a space, this will work.
String fullName = JOptionPane.showInputDialog(null, "What is your full name?");
String[] names = fullName.split(" ");
String firstname = names[0];
String lastName = names[1];
My answer does not cover validation. You would normally validate the user's input before using it, but I believe it to be out of the scope of the question.

Related

how to input username by getting the half of the first name and half of the last name and the day of the given birthday

example of output should be
please help thank you in advance!!
the output of the code in username should be the 2 letter in firt name and 3 in last name and date number
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter Fullname:");
String fullname = sc.nextLine();
System.out.println("Enter Birthday : ");
String bday = sc.nextLine();
System.out.println("Your Login Details");
System.out.println("Enter Fullname:" + fullname);
System.out.println("Enter Birthday : " + bday);
System.out.println("Enter Username: " + );
}
}
Assuming the input will always be in the format you provided, you can use String.split() and String.substring() to extract the required information from the input as shown below.
String[] splitName = fullName.split(" ");
String firstName = splitName[0];
String lastName = splitName[1];
String day = bday.split("-")[1];
String username = firstName.substring(0, 2) + lastName.substring(0, 3) + day;
You can use this code to achieve the expected result. The name should always be in this format FirstName LastName, otherwise, you may encounter NullPointerException more frequently. There are split and substring methods in the string class. Follow these steps to get started
Full name should be split into two strings, the first is for the first name and another is for the last name, for this we will use the split method which returns String[].
After splitting the full name, the substring method comes into the picture, substring method takes two parameters first and the last index. We can use this method with both strings received by the split method.
String[] firstLastName = fullname.split(" ");
System.out.println("Enter Username: " + firstLastName[0].substring(0, 2) + firstLastName[1].substring(0, 3) + bday.split("-")[1]);
Syntax
Public String [] split ( String regex, int limit)
public String substring(int begIndex, int endIndex)

ReportPayment() method in main is giving errors

I'm asked to do the following tasks:
Five private variables to store the Name, Surname, Gender, age,
AmountPayout
Include an Object Instantiation that has two methods called. The one methods is called Info(), this will use a GUI to retrieve Name,
Surname, Gender, age, AmountPayout
Create another method called ReportPayment(), this will use a GUI to display the information of the user. Within this methods create
another method called PaymentCalculator that parse a parameter of the
amount to be paid.
Use the amount to deduct 15% tax, and return the final amount to be displayed.
My code returns:
required string string int double
public static void main(String[] args) {
Details det = new Details();
det.info();
det. ReportPayment();
}
class Details
{
private String name;
private String surname;
private String gender;
private int age , age1;
private double AmountPayout , SubPayout;
void info()
{
String name = JOptionPane.showInputDialog(null,"Enter the Patient Name :");
String surname = JOptionPane.showInputDialog(null,"Enter the Patient Surname :");
String age = JOptionPane.showInputDialog(null,"Enter the age of the patient :");
int age1 = Integer.parseInt(age);
String gender = JOptionPane.showInputDialog(null,"Enter the Patient gender :");
String AmountPayout = JOptionPane.showInputDialog(null,"Enter the Patient payout :");
double SubPayout = Double.parseDouble(AmountPayout);
}
void ReportPayment(String name, String surname, int age, double AmountPayout)
{
JOptionPane.showMessageDialog(null,"Victim of Listeriosis" + "\n"
+ "Patient Name:" + name + "" + surname + "\n"
+ "Age:" + age + "\n"
+ "Payout:" + AmountPayout);
}
}
First of all you should remove c# from tags, this has nothing to do with it.
Then take look at your ReportPayment method, as you can see in method signature you have 4 parameters that you must past once you call method.
So instead of writing det.ReportPayment();
You should write det.ReportPayment("name","surname", 10, 30); to make it work
But that isn't what you really want, because you are supposed to use class attributes you don't need to pass them to method, so you should change method to something like this:
// Note that we don't have parameters anymore
void reportPayment() {
JOptionPane.showMessageDialog(null,"Victim of Listeriosis" + "\n"
+ "Patient Name:" + name + "" + surname + "\n"
+ "Age:" + age + "\n"
+ "Payout:" + AmountPayout);
}
Last issue with your code is that you are not following conventions, this doesn't affect how your code works but it affects other people reading your code, whenever using some language make sure to get familiar with standard conventions in other to make code more understandable for other developers that will look at it.
In Java standard for naming is Camel case notation, with difference between class names and variable/method names being that classes always start with UPPERCASE letter while variable and method names start with lowercase.
Class name - StringBuilder
Method name - reportPayment
Variabl name - amountPayout
Another convention in Java is that { bracket comes just after method signature not on next line.
Finally in other to learn more about above mentioned things and many others I suggest you to buy/borrow some good Java introduction book, there are many out there.
2 issues with your code:
First issue: you forget the parameters in the call to det.reportPayment(); (note the lowercase r).
I assume you want to use the attributes stored in Details.
You have two options:
Pass the attributes as parameters:
det. ReportPayment(det.name, det.surname, det.age, det.AmountPayout);
Note this will not works without more modification as those attributes are privates. You have to either make them public or add getters (and then replace det.name with det.getName(), etc.)
Remove the parameters and use the Detail attribute directly in the method as the method is in the same class (best solution).
void reportPayment() {
JOptionPane.showMessageDialog(null, "Victim of Listeriosis" + "\n" + "Patient Name:" + this.name + "" + this.surname
+ "\n" + "Age:" + this.age + "\n" + "Payout:" + this.AmountPayout);
}
Second issue: you never set your class attribute.
In info()method, you ask the user to give values. Those values are stored in temporary variables but not in the class attributes.
For example, push the values in this.name instead of creating a new String name.
this.name = JOptionPane.showInputDialog(null, "Enter the Patient Name :");
this.surname = JOptionPane.showInputDialog(null, "Enter the Patient Surname :");
and so on.
Unrelated: have a look at java naming convention
Adding "this" in the info() method made the name , surname and gender work but the age and AmountPayout still returns a null
public static void main(String[] args) {
Details det = new Details();
det.info();
det.reportPayment();
}
}
class Details {
private String name;
private String surname;
private String gender;
private int age , age1;
private double AmountPayout , SubPayout;
void info()
{
this.name = JOptionPane.showInputDialog(null,"Enter the Patient Name :");
this.surname = JOptionPane.showInputDialog(null,"Enter the Patient Surname :");
String age = JOptionPane.showInputDialog(null,"Enter the age of the patient :");
int age1 = Integer.parseInt(age);
this.gender = JOptionPane.showInputDialog(null,"Enter the Patient gender :");
String AmountPayout = JOptionPane.showInputDialog(null,"Enter the Patient payout :");
double SubPayout = Double.parseDouble(AmountPayout);
}
Reworked the answer:
I tried to run the code myself and with a little tweaking it works perfectly fine. We are getting there. I think thi is the whole thing you should need!
This should now fix your error aswell as fit the requirements you have.
I changed:
renamed ReportPayment() to reportPayment()
removed te space inbetween
"det." and "ReportPayment() in the main class
Rewrote your attributes
rewrote the info() method
added the calculation for taxes as required
Main.java
public class Main {
private static boolean running = true;
public static void main(String[] args) {
Details det = new Details();
det.info();
det.reportPayment();
}
}
Details.java
import javax.swing.JOptionPane;
class Details {
private String name;
private String surname;
private int age;
private String gender;
private double AmountPayout;
void info() {
this.name = JOptionPane.showInputDialog(null, "Enter the Patient Name :");
this.surname = JOptionPane.showInputDialog(null, "Enter the Patient Surname :");
String rawAge = JOptionPane.showInputDialog(null, "Enter the age of the patient :");
this.age = Integer.parseInt(rawAge);
this.gender = JOptionPane.showInputDialog(null, "Enter the Patient gender :");
String rawPayout = JOptionPane.showInputDialog(null, "Enter the Patient payout :");
this.AmountPayout = Double.parseDouble(rawPayout);
}
void reportPayment() {
paymentCalculator();
JOptionPane.showMessageDialog(null, "Victim of Listeriosis" + "\n" + "Patient Name:" + name + " " + surname
+ "\n" + "Age:" + age + "\n" + "Payout:" + AmountPayout);
}
private void paymentCalculator() {
this.AmountPayout = this.AmountPayout * 0.85;
}
}

Trying to split up a string with blank space

I'm writing out a piece of a code that where I am trying to split up the user's input into 3 different arrays, by using the spaces in-between the values the user has entered. However, everytime i run the code i get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
I have tried to use a different delimiter when entering the text and it has worked fine, e.g. using a / split the exact same input normally, and did what i wanted it to do thus far.
Any help would be appreciated!
Here's my code if needed
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Split is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").
String[] array = s.split(" +");
Or you can use Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You have made mistakes at following places:
fullname = user_input.next();
It should be nextLine() instead of just next() since you want to read the complete line from the Scanner.
String[] NameSplit = new String[2];
There is no need for this step as you are doing NameSplit = user_input.split(...) later but it should be new String[3] instead of new String[2] since you are storing three entries i.e. First Name, Middle Name and the Last Name.
Here is the correct program:
class Substring {
public static void main (String[] args) throws java.lang.Exception {
Scanner user_input = new Scanner(System.in);
String[] NameSplit = new String[3];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
String fullname = user_input.nextLine();
NameSplit = fullname.split(" ");
FirstName = NameSplit[0];
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname);
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Output:
Enter your full name (First Middle Last): John Mayer Smith
Smith, John Mayer
John
java.util.Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
hence even though you entered 'Elvis John Presley' only 'Elvis' is stored in the fullName variable.
You can use BufferedReader to read full line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
fullname = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
or you can change the default behavior of scanner by using:
user_input.useDelimiter("\n"); method.
The exception clearly tells that you are exceeding the array's length. The index 2 in LastName = NameSplit[2] is out of array's bounds. To get rid of the error you must:
1- Change String[] NameSplit = new String[2] to String[] NameSplit = new String[3] because the array length should be 3.
Read more here: [ How do I declare and initialize an array in Java? ]
Up to here the error is gone but the solution is not correct yet since NameSplit[1] and NameSplit[2] are null, because user_input.next(); reads only the first word (*basically until a whitespace (or '\n' if only one word) is detected). So:
2- Change user_input.next(); to user_input.nextLine(); because the nextLine() reads the entire line (*basically until a '\n' is detected)
Read more here: [ http://www.cs.utexas.edu/users/ndale/Scanner.html ]

2nd JOptionPane won't come up

I'm just starting out with Java and programming in general. Could someone please explain to me why the second dialog box won't show up after I've entered the information for the first one?
Thanks!
// Java Practice
import javax.swing.JOptionPane;
import java.util.Scanner;
public class DialogTest
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String firstname;
String lastname;
int age;
JOptionPane.showInputDialog("What is " +
"your first name?");
firstname = keyboard.nextLine();
JOptionPane.showInputDialog("What is " +
"your last name?");
lastname = keyboard.nextLine();
JOptionPane.showInputDialog("How old are you?");
age = keyboard.nextInt();
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
System.exit(0);
}
}
JOptionPane.showInputDialog() returns a String that contains the value entered by the user. Instead of using the Scanner class, store the return value of the method call into your variables:
String firstname, lastname, age;
firstname = JOptionPane.showInputDialog("What is " +
"your first name?");
lastname = JOptionPane.showInputDialog("What is " +
"your last name?");
age = JOptionPane.showInputDialog("How old are you?");
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
You don't need both JOptionPane and Scanner. You only need one (I highly recommend Scanner over the other).
What's happening is this: The call to JOptionPane is opening a dialog for your user to enter a value. That value is returned by this method call, which you do nothing with. Then after the dialog is finished, you call keyboard.nextLine() which blocks the program until the user enters another value into the command line window (or your IDE if you're running it through that).
If you want to see both options available to you, try commenting out the keyboard lines and setting firstname = JOptionPane... and so on. Once you've tried out that program, do the opposite: comment out the JOptionPane calls and replace them with System.out.println calls.
As someone who began learning input handling via JOptionPane, I believe Scanner is a much better utility.

Java string split with multiple delimeters

What would be the best way to split this string directly after the CN= to store both the first and last name in separate fields as shown below?
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String firstName"Paul"
String lastName="Sebula"
Don't re-invent the wheel. Assuming these are well-formed DN's, see the accepted answer on this question for how to parse without directly writing your own regex: Parsing the CN out of a certificate DN
Once you've extracted the CN, then you can apply some of the other parsing techniques suggested (use the Java StringTokenizer or the String.split() method as others here have suggested if it's known to be separated only by spaces). That assumes that you can make assumptions (eg. the first element in the resulting array is the firstName,the last element is the lastName and everything in between is middle names / initials) about the CN format.
You can use split:
String distinguisedName = "CN=Paul Sebula,OU=BAE,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=baesystems,DC=com";
String[] names = distinguisedName.split(",")[0].split("=")[1].split(" ");
String firstName = names[0];
String lastName= names.length > 2 ? names[names.length-1] : names[1];
System.out.println(firstName + " " + lastName);
See IDEONE demo, output: Paul Sebula.
This also accounts for just 2 names (first and last only). Note how last name is accessed it being the last item in the array.
public static void main(String[] args) {
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String splitResult[]=distinguisedName.split(",")[0].split("=");
String resultTwo[]=splitResult[1].split("\\.");
String firstName=resultTwo[0].split(" ")[0].trim();
String lastName=resultTwo[1].trim();
System.out.println(firstName);
System.out.println(lastName);
}
output
Paul
Sebula
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String[] commaSplit = distinguisedName.split(',');
String[] whitespaceSplit = commaSplit[0].split(' ');
String firstName = whitespaceSplit[0].substring(3);
String lastName = whiteSpaceSplit[2];
In steps:
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String fullName = distinguisedName.substring(3, distinguisedName.indexOf(','));
String[] nameParts = fullName.split(" ");
String firstName = nameParts[0];
String lastName = nameParts[nameParts.length-1];
This will work for cases where the middle name/initial are not present as well.

Categories

Resources