The code below asks for your name, takes the input, and then displays your name.
Code:
public static void main(String args[]) {
System.out.println("What is your name?");
Scanner name = new Scanner(System.in); //Passed in "Vincent"
System.out.println("Hello, " + name.nextLine() + "!");
}
Output:
What is your name?
Vincent
Hello, Vincent!
Question:
How would I combine the first two lines, so that I can have something similar to:
"What is your name: namehere"
You are using println which adds the new line character at the end of your string.
Use this instead:
System.out.print("What is your name? ");
Read more here.
Just change println to print so the newline is not printed.
System.out.print("What is your name: ");
Related
Why nextLine() method doesn't work? I mean, I can not enter any sentence after the second scan call because the program runs to the end and exits.
Input: era era food food correct correct sss sss exit
Should I use another Scanner object?
import java.util.*;
public class Today{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str="";
String exit="exit";
System.out.println("Please enter some words : ");
while(true){
str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);
}
System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine();
System.out.println("the word you entered is : " + sentence1);
}
}
What Scanner#nextLine does is to
Advance this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end.
Since your input is era era food food correct correct sss sss exit you read inside the while every word with Scanner#next, so when Scanner#nextLine is called it returns "" (empty string) because there is nothing left of that line. That's why you see the word you entered is : (at the begging of the text is the empty string).
If you would have used this input: era era food food correct correct sss sss exit lastWord you would have seen the word you entered is : lastWord
The only thing you need to do in order to fix this is to call scan.nextLine(); first to move to the next line for the new input the user is going to provide and then get the new word with Scanner#nextLine() like this:
Scanner scan = new Scanner(System.in);
String str="";
String exit="exit";
System.out.println("Please enter some words : ");
while(true){
str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);
}
scan.nextLine(); // consume rest of the string after exit word
System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine(); // get sentence
System.out.println("the word you entered is : " + sentence1);
Demo: https://ideone.com/GbwBds
Project: What’s My Name?
From the keyboard enter your first and then your last name, each with its own
prompt. Store each in a separate String and then concatenate them together to
show your full name. Call both the project and the class FullName. When your
program is finished running, the output should appear similar to that below:
What is your first name? Cosmo
What is your last name? Kramer
Your full name is Cosmo Kramer
Here is what i got:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbReader=new Scanner(System.in);
String a="Cosmo";
String b="Kramer";
a=kbReader.nextLine();
System.out.println("What is your first name?"+a);
b=kbReader.nextLine();
System.out.println("What is your last name?"+b);
System.out.println("Your full name is"+a+" "+b);
}}
What is wrong with my code? Both Eclipse and the web compiler doesn't work both do state a different error saying that I have no lines.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at Tester.main(Tester.java:10)
You appear to be reading before you display your message,
String a="Cosmo";
String b="Kramer";
a=kbReader.nextLine();
System.out.println("What is your first name?"+a);
b=kbReader.nextLine();
System.out.println("What is your last name?"+b);
System.out.println("Your full name is"+a+" "+b);
and I would recommend you use descriptive variable names. So, I think you wanted something like -
System.out.println("What is your first name?");
String firstName = kbReader.nextLine();
System.out.println("What is your last name?");
String lastName = kbReader.nextLine();
System.out.println("Your full name is " + firstName + " " + lastName);
Which seems to do what you asked when I run it (and provide your input) -
What is your first name?
Cosmo
What is your last name?
Kramer
Your full name is Cosmo Kramer
Finally, I note that FullName is not Tester.
An exercise in the introduction to java programming book I am currently working through requires me to retrieve input from the command line using the scanner class. Each example in the book (and the code I have seen here) creates and uses a scanner object in the same method it is needed in, such as:
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter your first name: ");
String firstName = inputDevice.nextLine();
System.out.println("Enter your middle name: ");
String middleName = inputDevice.nextLine();
System.out.println("Enter your last name: ");
String lastName = inputDevice.nextLine();
inputDevice.close();
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
}
I was wondering why this method is preferred over something like the following (especially since the execise requires me to retrieve input for nine strings)
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
String firstName = prompt("Enter your first name: ");
String middleName = prompt("Enter your middle name: ");
String lastName = prompt("Enter your last name: ");
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
private static String prompt(String message) {
Scanner inputDevice = new Scanner(System.in);
System.out.println(message);
return inputDevice.nextLine();
}
}
Please keep in mind I am new to both Java and programming in general.
There's nothing wrong with doing it that way, and it very well may save you a few lines in the long run, but it's not common because you can create a Scanner once and reuse it, as you've done above.
It's all style-based, but using one Scanner multiple times is fairly straightforward and avoids unnecessary complexity in your code, which is important (especially in larger-scale projects).
When you're going through the code line-by-line, your first example is much more readable to me, but that's just my opinion, as this is a fairly subjective question. The only real downside is that you're creating a new Scanner every time you call the prompt() method, which is unnecessary.
Also note that you forgot to close the Scanner in the method.
In your case you are creating the Scanner object for every call of the prompt method which is not great practice.
Also you are not closing the Scanner.
IMHO the book's code is reads easier...
For this program it asks for the user to input their full name. It then sorts out the first name and last name by separating them at the space the put between the first and last name. However, indexOf() is not recognizing the space and only returns -1. Why is that? Thanks.
Here is the prompt off of PracticeIt:
Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:
Please enter your full name: Sammy Jankis
Your name in reverse order is Jankis, Sammy
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String fullName = inputScanner.next();
int space = fullName.indexOf(" "); // always return -1 for spaces
int length = fullName.length();
String lastName = fullName.substring(space+1,length+1);
String firstname = fullName.substring(0, space);
System.out.print("Your name in reverse order is " + lastName + ", " + firstname);
}
}
As next will return the next token use nextLine not next to get the whole line
see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
When you do String fullName = inputScanner.next() you only read till the next whitespace so obviously there is no whitespace in fullName since it is only the first name.
If you want to read the whole line use String fullName = inputScanner.nextLine();
Does anybody know how i could make scanner ignore space? I wanna type a first and second name, but scanner wont let me, i want to save the full name
String name;
System.out.print("Enter name: ");
name = scan.next(); //Ex: John Smith
System.out.println(name);
Edit:
New problem.. While using nextLine in my extended program, nextLine just ignores the whole question and moves on without a chance to scan the name.
Scanner#next() splits lines around whitespace. Scanner.nextLine() does not, therefore leaving spaces in.
name = scan.nextLine(); //Ex: John Smith
Well, first your System.out.print(); call is flawed. Everything inside must be inside quotations
System.out.print("Enter name: ");
scan.next() gets the next character in the stream, whereas scan.nextLine() gets the next line (terminated by an EOL character), which may be more helpful to you.
After that, you can create an array of words, like
String[] broken = name.split(" ");
which will place into broken all of the words that you've typed in delimited by spaces.
Then you can go something like
for(int i = 0; i < broken.size; i++)
{
System.out.print(broken[i] + " ");
}
System.out.println();
Scanner.next delimits using whitespaces, to read a full line you can use:
name = scan.nextLine();
use scanner.nextLine() which reads full line, instead of scan.next();
Example:
name = scan.nextLine();
Read oracle documentation for Scanner class for available methods.
sounds like you want to read the entire line (minus the line ending). if someone enters, "helen r. smith", you can read the line in with:
name = scan.nextLine();
YOU CAN DO LIKE THIS
import java.util.*;
class scanner2
{
public static void main(String args[])
{
Scanner in= new Scanner(System.in);
System.out.println("enter the name");
String name= in.nextLine();//for name with spaces with more than one word or for one word.
System.out.println("enter single word");
String rl= in.next();//single word name
System.out.println("name is "+name+" rl is "+rl);
}
}
Execute it you will get your answer.