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.
Related
This question says ask for the 'First Name' and the 'Last Name' from the user and then show the message Welcome with the full name of the user . also make sure that the user does not enter his/her full name in the first Text Field which asks for First Name only
I thought that if the user enters his/her full name in the first text field , we can know that from the fact that he/she entered a space or (' ') or not . If not we can simply show the message Welcome + full name . However it didn't work the way I thought it would ... Can somebody help me with itenter image description here
If I understand you the below will work accomplish what you need by ignoring the data after the space and asking the user for their last name.
code:
public static void main(String[] args) {
// Properties
Scanner keyboard = new Scanner(System.in);
String firstName, lastName
// Ask the user for their first name
System.out.println("What is your first name? ");
System.out.print("--> "); // this is for style and not needed
firstName = keyboard.next();
// Ask the user for their last name
System.out.println("What is your last name? ");
System.out.print("--> "); // this is for style and not needed
lastName = keyboard.next();
// Display the data
System.out.println("Your first name is : " + firstName);
System.out.println("Your last name is : " + lastName);
}
There is actually a few ways you can do this, but if I understand your question correctly a simple way would be below, which is from http://math.hws.edu/javanotes/c2/ex6-ans.html and helped me understand Java more when I was learning it, you just would alter it to your needs.
code:
public class FirstNameLastName {
public static void main(String[] args) {
String input; // The input line entered by the user.
int space; // The location of the space in the input.
String firstName; // The first name, extracted from the input.
String lastName; // The last name, extracted from the input.
System.out.println();
System.out.println("Please enter your first name and last name, separated by a space.");
System.out.print("? ");
input = TextIO.getln();
space = input.indexOf(' ');
firstName = input.substring(0, space);
lastName = input.substring(space+1);
System.out.println("Your first name is " + firstName + ", which has "
+ firstName.length() + " characters.");
System.out.println("Your last name is " + lastName + ", which has "
+ lastName.length() + " characters.");
System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
}
}
edit:
If this doesn't make sense I can give a better explanation with a better example with more detail.
More notes on similar problems.
https://www.homeandlearn.co.uk/java/substring.html
The problem with your code is, that you check every single charackter and then do the if/else for every single charackter. which means if the last charackter is not a whitespace it will at the end process the else tree.
The solution is to just check once:
if(fn.contains(' '){
//Do what you want to do, if both names were entered in the first field
}else{
//Everything is fine
}
I want the user to only enter his age. So I did this program :
Scanner keyb = new Scanner(System.in);
int age;
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("How old are you ?");
}
age = keyb.nextInt();
System.out.println("you are" + age + "years old");
I found how to prevent user from using string by using the while loop with keyb.hasNextInt(), but how to prevent him from using the whitespace or from entering more input than his age ?
For example I want to prevent this kind of typing "12 m" or "12 12"
Also, how can I clear all existing data in the buffer ? I'm facing an infinite loop when I try to use this :
while(keyb.hasNext())
keyb.next();
You want to get the whole line. Use nextLine and check that for digits e.g.
String possibleAge = "";
do {
System.out.println("How old are you ?");
possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))
Your problem is that the default behaviour of Scanner is to use any whitespace as the delimiter. This includes spaces. This means that a 3 a is in fact three tokens, not one. You can change the delimiter to a new line so that a 3 a becomes a single token, which will then return false for hasNextInt.
I've also added an initial question, because in your example the first input was taken before asking any questions.
Scanner keyb = new Scanner(System.in);
keyb.useDelimiter("\n"); // You can try System.lineSeparator() but it didn't work in IDEA
int age;
System.out.println("How old are you?");
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("No really. How old are you?");
}
age = keyb.nextInt();
System.out.println("You are " + age + " years old");
String age = "11";
if (age.matches(".*[^0-9].*")) {
System.out.println("Invalid age");
} else {
System.out.println("valid age");
}
If age contains other then digits then it will print invalid age.
I'm trying to read separate names and instruments up until the total number of bandmembers(asked earlier in the program) is reached. The program reads the amount, and reads the first name. However after that it fails in that it only reads the first name, it does not print any name or instrument after.
The while loop below is the most likely source of the problem:
i = counter
while(i <= bandMembers)
{
System.out.println("What is band member " + i + "'s name?");
kb.nextLine();
String bName = kb.nextLine();
System.out.println("What instrument does " + bName + " play?");
kb.nextLine();
String bNamePlay = kb1.nextLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
This is what it prints if I entered the first name as bName1:
Band Members
--------------
1: bName1 -
2: -
3: -
Any help appreciated, thanks.
Use BufferedReader instead.This will fix your problem.:-
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=counter;
while(i<=bandMembers){
System.out.println("Enter band member "+i+" name:-");
String bName=br.readLine();
System.out.println("What instrument does "+bName+" play?");
String bNamePlay=br.readLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
You should be using
String bName = kb.next();
Under the assumption that you are using a Scanner.
When you call nextLine() it reads the remainder of the same line and does not wait for input.
I don't have enough rep to comment on the issue you're having:
I was using kb.next at first but it read each word separated by a space as the next name. For example I would input "Jimmy loose hands" and it would prompt for Jimmy's instrument correctly, but it would then ask for band member 2's name and "what instrument does loose play?" simultaneously. So it took the second word as the next name.
What you may want to do is remove the "kb.nextLine();" before "String bName = kb.nextLine();"
I don't have an IDE open to confirm it, but that may be the reason that it is taking the second word/string entered as the name.
I am in beginning Java. I have been trying for several days to figure how to code the following:
Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane.
In the loop, check if the user selects OK of Cancel without entering data, if so prompt the user until valid data is entered.
Separate the name, phone, and email into separate String variables.
In the loop, check if the name is 10 characters or less, if not, prompt the user until valid data is entered.
If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user.
Display the contents in a JOptionPane using the get methods.
Even if someone can help me with just the "Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane."
and/or
"If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user." code.
I can figure out the rest I'm sure. And yes, I know how to spell Sunflower...the A was on purpose. Thank you to anyone who helps. I really appreciate it!
This is what I have: (the Contact class info is posted below) I am learning how to clean this code up to be more efficient. I was going to delete from about Line 19 on after I figured our how to do the while loop. For now, I get all excited when I actually get a code to work.
import javax.swing.*;
public class TestContact
{
public static void main(String[] args)
{
Contact mycontact = new Contact();
mycontact.setName("Tanya Smith");
mycontact.setPhone("440-226-2866");
mycontact.setEmail("tanya#gmail.com");
JOptionPane.showMessageDialog(null,
"The Contact's information is:\n Name: " + mycontact.getName() +
"\n Phone Number: " + mycontact.getPhone () +
"\n Email: " + mycontact.getEmail());
JOptionPane.showInputDialog(null, "Please enter your Name: " );
while Name.equals()
String Info = JOptionPane.showInputDialog(null, "Please enter you Name, Phone Number and Email");
String[] word = Info.split(" ");
String AllInfo =
Character.toString(word[0].charAt(0)) +
Character.toString(word[1].charAt(0)) +
Character.toString(word[2].charAt(0)) +
Character.toString(word[3].charAt(0));
JOptionPane.showMessageDialog(null, "Your Name: " + word[0] + " " + word[1] +
"\nYour Phone: " + word[2] +
"\nYour Email: " + word[3]);
}
}
I figured out how to do it one way with the Character.toString, but not with using the while loop.
While I don't approve of simply asking for code, you do sound legitimately stuck, and confused. I'm also waiting on a 4 gig transfer over a very slow network connection, so here's a bit to get you started. This should get you most of the way. Next time try to post whatever you came up with, regardless of how off base you think it might be. A least we know you're not just asking for code.
public static void main(String [] args) {
promptForData();
}
public static void promptForData() {
boolean cont = true;
while (cont) {
String input = JOptionPane.showInputDialog("Enter name phone and email space delimited.");
cont = !validData(input);
}
}
public static boolean validData(String input) {
String[] parts = input.split(" ");
if (parts.length != 3) return false;
if (parts[0].length() < 11) return false;
return true;
}
"Even if someone can help me with just the "Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane."
Pseudo code
String name;
String phone;
String email;
String input;
String[] array;
while name.length() > 10 or name is null
input = JOptionPane...
array = input.split(....)
name = first array index
// end loop
phone = second array index
email = third array index
""If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user." code."
Pseudo code
class Contact
String name;
String phone;
String email
Contact (constructor taking the three field type arg)
this field = an argument
.... // two more
After the loop from the first part after get the valid input
Contact contact = new Contact( fill in the args)
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.