My goal is to have the user be prompted for multiple separate inputs that would store the data in a manner that I could then manipulate.
For example:
Question:
What is your username?
What is your name?
Input:
Sparkeyy
Nelson
I then want to be able to take these and add them / multiply if they're numbers. This is what I have so far. (Also first question so sorry for poor formatting)
import java.util.*;
public class Program{
public static void main(String args[]){
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
}
public static void (name){
System.out.println("Enter your name: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Your name is " + name);
}
}
Take a look here, they answered you're question thoroughly:
https://stackoverflow.com/questions/5287538/how-to-get-basic-user-input-for-java
You basically need a Scanner, like you're doing, and then for numbers:
scanner.nextInt();
There are also ways of converting properly formatted Strings to Ints/Doubles.
Related
I am trying to figure out how to accumulate user inputs in for loop and then to print them out with one system.out.print. This is my test code for the problem.
So for example if a user type : Mike for his name and Joe,Jack,Dave for other names, how to print them all just having one variable because amount of variables are not known since a user has that decision. Also is it possible to do that without stringbuilder and without arrays?
import java.util.Scanner;
public class Accumulate {
public static void main(String[] args) {
String othernames = " ",name;
int count,n;
Scanner kybrd = new Scanner(System.in);
System.out.println("Enter your name ");
name = kybrd.nextLine();
System.out.println("How many other names would you like to add ? ");
count = kybrd.nextInt();
kybrd.nextLine();
for(n=0;n<count;++n){
System.out.println("Enter other names ");
othernames = kybrd.nextLine();
}
System.out.println("Other names are "+othernames + " And your name is "+ name);
}
}
You can call it recursively, for instance:
Scanner sc = new Scanner(System.in);
String s;
while(condition) {
s = s + sc.nextLine();
}
this will always concat the lines you enter, you can also add commas, or spaces, or whatever you want to add.
as for your question about using Objects other than StringBuilder you can use List<String> and build a string for it at the final step.
you can use Map<String, String> if you need more complex data structure.
I've only been learning java for a few weeks so I'm still a noob. I want the next line to print "mr/miss." + firstname + lastname;
however, i don't want to type the gender of the person in. I want there to be a list of male names (long list over 1000 names) and the program to detect if the firstname input is one of those male names. The program can then assign the correct title (mr/ms.)
How do I do this without making a normal arraylist and typing out each name individually (which'll take agessss).
Thanks in advance!
public static void main (String [] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Hello, will you be checking out today? (Y/N)");
String CheckOutYesOrNo = scanner.nextLine();
if (CheckOutYesOrNo.equalsIgnoreCase("y")) { x();}
else if (CheckOutYesOrNo.equalsIgnoreCase("n")) {System.out.println("Okay then. Enjoy the rest of your stay at the Rizty Hotel!");}
}
public static void x(){
System.out.println("Sure, would you mind telling me your last name?");
Scanner scanner = new Scanner(System.in); //how can I avoid making a new scanner?
String lastname = scanner.nextLine();
System.out.println("And your first name?");
String firstname= scanner.nextLine();
}
}
Sounds like a typical mapping. You could read all your names into a Map where the key is the name and the gender is the value. To resolve the gender just do something like genderMap.get(name).
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :" );
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
String name= input.nextLine();
System.out.println("Your Next is : " + name);
}
}
nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.
If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.
Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.
If you call input.nextInt(); the scanner reads the number from the input, but leaves the line separator there. That means, if you call input.nextLine(); next, it reads everything till the next line separator. And this is in this case only the line separator itself.
You can fix that in two ways.
Way 1:
int ip = Integer.parseInt(input.nextLine());
// output
String name= input.nextLine();
Ways 2:
int ip = input.nextInt();
// output
input.nextLine();
String name= input.nextLine();
This one working, Anyway if you want to save IP address it must be String.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :");
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
input.nextLine();
String name = input.nextLine();
System.out.println("Your Next is : " + name);
}
}
I have to use a loop in my code so that when someone enters yes, they can re-enter their names as many times as they want, but I have no idea how to do this. Any help is appreciated, here is my code:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if (reply == "yes")
{
}
}
}
This reply == "yes" is not how you compare Strings in Java. This compares there memory locations, not there contents (and it's unlikely there memory locations are going to be equal).
Instead you need to use reply.equals("yes") or if you don't care about doing a case comparison, you can use reply.equalsIgnoreCase("yes") instead
do {
// The remainder of your code...
} while (reply.equalsIgnoreCase("yes"));
Updated
You may also wish to have a read through The while and do-while statements and The for Statement, which covers the basics of looping in Java
Use a do-while loop:
public static void main(String[] args) {
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
} while (keyboard.nextLine().equalsIgnoreCase("yes"));
System.out.println("Bye!");
keyboard.close();
}
}
use this
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
while(true){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if(reply.equals("no"))
break;
}
}
}
The reason for this is to loop through as long as the answer is not no.
or you could use this if you want the answer to always be yes
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply="yes";
//Get the user's name.
while(reply.equals("yes")){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
}
}
}
I think this will work (untested):
public static Scanner keyboard = new Scanner(System.in); // global
public static void main(String [] args)
{
getName();
}
public static void getName()
{
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
rerun();
}
public static void rerun()
{
System.out.println("Would you like to enter another name? Please enter \"yes\" or \"no\".");
String reply = keyboard.nextLine();
if (reply.equals("yes")) getName();
else System.exit();
}
}
First we call the getName() method and run through that once. Then we make a call to the rerun() method. This method will test if we want to re-run the program. If the user types in "yes", then we repeat the whole process. If we type in anything besides "yes", the program quits.
Besides the fact that your code is unfinished, the only real problem with your code is that you try to compare strings with the == operator. See MadProgrammer's answer as to why that is wrong.
The simplest (and probably clearest) way is to wrap what you want to repeat in a do-while statement:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply;
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
} while ("yes".equals(reply));
}
}
The reply variable must be declared before the block, because it is accessed in the loop condition (a variable is only visible in the block it is declared in, so if reply were declared in the loop, it would not be available to the loop condition).
I changed the loop condition because the == operator compares Strings by reference, i.e. it will check whether both sides point to the same String object. The equals method, in contrast, checks that the content of the Strings is equal (i.e. they contain the same characters in the same order).
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}