In this exercise I am to reverse a string. I was able to make it work, though it will not work with spaces. For example Hello there will output olleH only. I tried doing something like what is commented out but couldn't get it to work.
import java.util.Scanner;
class reverseString{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next();
int length = input.length();
String reverse = "";
for(int i = length - 1; i >= 0; i--){
/*if(input.charAt(i) == ' '){
reverse += " ";
}
*/
reverse += input.charAt(i);
}
System.out.print(reverse);
}
}
Can someone please help with this, thank you.
Your reverse method is correct, you are calling Scanner.next() which reads one word (next time, print the input). For the behavior you've described, change
String input = scan.next();
to
String input = scan.nextLine();
You can also initialize the Scanner this way:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
So that it delimits input using a new line character.
With this approach you can use sc.next() to get the whole line in a String.
Update
As the documentation says:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
An example taking from the same page:
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
All this is made using the useDelimiter method.
In this case as you want/need to read the whole line, then your useDelimiter must have a pattern that allows read the whole line, that's why you can use \n, so you can do:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
Related
I am having trouble with a user-entered number. I am trying to add the user-entered number a few spaces after the colon in the sentence instead of the line underneath.
Scanner inputHere = new Scanner(system.in);
System.out.println("I am trying to add the number a few spaces after the colon:");
String inputHereOne = inputHere.nextLine();
Change
System.out.println("I am trying to add the number a few spaces after the colon:");
to not print a newline - you should also flush() when you do so. Like,
System.out.print("I am trying to add the number a few spaces after the colon: ");
System.out.flush();
Also, you had a typo here
new Scanner(system.in);
should be
new Scanner(System.in);
Change the lowercase 's' in 'system.in' to 'System.in'
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
I'm trying to write a program that is practically a stack. Given a text file with certain keywords, I want my program to evaluate the text line by line and perform the requested action to the stack.
For example, if the input file is:
push 10
push 20
push 30
The resulting stack should look like:
30
20
10
However, I don't know how to push these values into the stack without hardcoding an int value after the word push. I made a String variable and assigned it to scanner.nextLine()
From there, I compare the line with strLine: if strLine is equal to push followed by some Number, then that number would be pushed on the stack.
However, it seems that the method nextInt() isn't taking this number from the input stream.
Scanner input = new Scanner(file)
int number;
String strLine;
while (input.hasNextLine()){
strLine = input.nextLine();
number = input.nextInt();
if(strLine.equals("push " + number)){
stack.push(number);
}
How can I fix this?
Thank you.
Get the input and split it with space " "!
That will give ["push","1"]
convert the first index to int and then push the value to stack!
while (input.hasNextLine()){
String[] strLine = input.nextLine().split(" ");
if(strLine[0].equals("push")){
stack.push(Integer.parseInt(strLine[1]));
}
else if(strLine[0].equals("pop")){
stack.pop();
}
else{
system.out.println("Please enter a valid input!");
}
}
Hope it helps!
input.nextLine reads the whole line, including the number. What you can do instead is to use input.next() to get the "push" and input.nextInt() to get the number. This example is using Scanner with System.in (so it needs "quit" to exit the while loop), but it should also work with a file (in which case you don't need to type "quit" to exit the program, as it will do so automatically when the input file has no more input). The advantage of using parseInt (as some of the other answers have suggested) is that you can catch any errors in integer input using a try/catch block.
import java.util.Scanner;
import java.util.Stack;
import java.util.InputMismatchException;
public class StackScanner {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
Scanner input = new Scanner(System.in);
int number;
String strLine;
while (input.hasNext()){
strLine = input.next();
if(strLine.equals("push")){
try {
number = input.nextInt();
stack.push(number);
} catch ( InputMismatchException e) {
System.out.println("Invalid input. Try again.");
input.nextLine();
continue;
}
} else {
break;
}
}
System.out.println(stack);
}
}
Sample output:
push 5
push 6
push 3
quit
[5, 6, 3]
change this:
number = input.nextInt();
to this:
number = Integer.parseInt(input.nextLine());
nextLine method parses the whole line including any numbers in the line. So, you need to take care of splitting the line and parsing the number in your code.
Something like below will work where I split the line with spaces. Although, there are many such ways possible.
Scanner input = new Scanner(file);
String strLine;
Stack<Integer> stack = new Stack<>();
int number;
while (input.hasNextLine()){
strLine = input.nextLine();
if(strLine.startsWith("push")){
String[] sArr = strLine.split("\\s+");
System.out.println(strLine);
if(sArr.length==2){
number=Integer.parseInt(sArr[1]);
stack.push(number);
System.out.println(number);
}
}
}
If I understand your problem, I would simply tokenize the line by splitting on whitespace.
It looks like your input is relatively structured: you have a keyword of some kind then whitespace then a number. If your data is indeed of this structure, split the line into two tokens. Read the value from the second one. For example:
String tokens[] = strLine.split(" ");
// tokens[0] is the keyword, tokens[1] is the value
if(tokens[0].equals("push")){
// TODO: check here that tokens[1] is an int
stack.push(Integer.parseInt(tokens[1]));
} else if (tokens[0].equals("pop")) { // maybe you also have pop
int p = stack.pop();
} else if ... // maybe you have other operations
What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be "connected" to any source (file for example).
Which one should I choose and why?
I always prefer to read input using nextLine() and then parse the string.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine() would be str.split("\\s+").
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
For reading the entire line you can use nextLine().
From JavaDoc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns the input that was skipped.
So in case of "small example<eol>text" next() should return "small" and nextLine() should return "small example"
The key point is to find where the method will stop and where the cursor will be after calling the methods.
All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.
For example, consider the following illustration:
|23_24_25_26_27\n
| -> the current cursor position
_ -> whitespace
stream -> Bold (the information got by the calling method)
See what happens when you call these methods:
nextInt()
read 23|_24_25_26_27\n
nextDouble()
read 23_24|_25_26_27\n
next()
read 23_24_25|_26_27\n
nextLine()
read 23_24_25_26_27\n|
After this, the method should be called depending on your requirement.
What I have noticed apart from next() scans only upto space where as nextLine() scans the entire line is that next waits till it gets a complete token where as nextLine() does not wait for complete token, when ever '\n' is obtained(i.e when you press enter key) the scanner cursor moves to the next line and returns the previous line skipped. It does not check for the whether you have given complete input or not, even it will take an empty string where as next() does not take empty string
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cases = sc.nextInt();
String []str = new String[cases];
for(int i=0;i<cases;i++){
str[i]=sc.next();
}
}
}
Try this program by changing the next() and nextLine() in for loop, go on pressing '\n' that is enter key without any input, you can find that using nextLine() method it terminates after pressing given number of cases where as next() doesnot terminate untill you provide and input to it for the given number of cases.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
import java.util.Scanner;
public class temp
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);
}
}
Output:
enter string for c
abc def
c is abc
enter string for d
d is def
If you use nextLine() instead of next() then
Output:
enter string for c
ABC DEF
c is ABC DEF
enter string for d
GHI
d is GHI
In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.
Lets have a look at following snippet of code
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.next();
}
when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as
Input as :- abcd abcd or
Input as :-
abcd
abcd
Output will be like
abcd
abcd
But if in same code we replace next() method by nextLine()
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.nextLine();
}
Then if you enter input on prompt as -
abcd abcd
Output is :-
abcd abcd
and if you enter the input on prompt as
abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)
Output is:-
abcd
From javadocs
next() Returns the next token if it matches the pattern constructed from the specified string.
nextLine() Advances this scanner past the current line and returns the input that was skipped.
Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.
From the documentation for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
From the documentation for next():
A complete token is preceded and followed by input that matches the delimiter pattern.
Just for another example of Scanner.next() and nextLine() is that like below :
nextLine() does not let user type while next() makes Scanner wait and read the input.
Scanner sc = new Scanner(System.in);
do {
System.out.println("The values on dice are :");
for(int i = 0; i < n; i++) {
System.out.println(ran.nextInt(6) + 1);
}
System.out.println("Continue : yes or no");
} while(sc.next().equals("yes"));
// while(sc.nextLine().equals("yes"));
Both functions are used to move to the next Scanner token.
The difference lies in how the scanner token is generated
next() generates scanner tokens using delimiter as White Space
nextLine() generates scanner tokens using delimiter as '\n' (i.e Enter
key presses)
A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.
Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position.
NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line.
so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().
public static void main(String[] args) {
// TODO code application logic here
String str;
Scanner input = new Scanner( System.in );
str=input.nextLine();
System.out.println(str);
}
I also got a problem concerning a delimiter.
the question was all about inputs of
enter your name.
enter your age.
enter your email.
enter your address.
The problem
I finished successfully with name, age, and email.
When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".
The solution
I used the delimiter for my scanner and went out successful.
Example
public static void main (String args[]){
//Initialize the Scanner this way so that it delimits input using a new line character.
Scanner s = new Scanner(System.in).useDelimiter("\n");
System.out.println("Enter Your Name: ");
String name = s.next();
System.out.println("Enter Your Age: ");
int age = s.nextInt();
System.out.println("Enter Your E-mail: ");
String email = s.next();
System.out.println("Enter Your Address: ");
String address = s.next();
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("E-mail: "+email);
System.out.println("Address: "+address);
}
The basic difference is next() is used for gettting the input till the delimiter is encountered(By default it is whitespace,but you can also change it) and return the token which you have entered.The cursor then remains on the Same line.Whereas in nextLine() it scans the input till we hit enter button and return the whole thing and places the cursor in the next line.
**
Scanner sc=new Scanner(System.in);
String s[]=new String[2];
for(int i=0;i<2;i++){
s[i]=sc.next();
}
for(int j=0;j<2;j++)
{
System.out.println("The string at position "+j+ " is "+s[j]);
}
**
Try running this code by giving Input as "Hello World".The scanner reads the input till 'o' and then a delimiter occurs.so s[0] will be "Hello" and cursor will be pointing to the next position after delimiter(that is 'W' in our case),and when s[1] is read it scans the "World" and return it to s[1] as the next complete token(by definition of Scanner).If we use nextLine() instead,it will read the "Hello World" fully and also more till we hit the enter button and store it in s[0].
We may give another string also by using nextLine(). I recommend you to try using this example and more and ask for any clarification.
The difference can be very clear with the code below and its output.
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
List<String> arrayList2 = new ArrayList<>();
Scanner input = new Scanner(System.in);
String product = input.next();
while(!product.equalsIgnoreCase("q")) {
arrayList.add(product);
product = input.next();
}
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
product = input.nextLine();
System.out.println("Enter a product");
while (!product.equalsIgnoreCase("q")) {
arrayList2.add(product);
System.out.println("Enter a product");
product = input.nextLine();
}
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("You wrote the following products \n");
for (String naam : arrayList2) {
System.out.println(naam);
}
}
Output:
Enter a product
aaa aaa
Enter a product
Enter a product
bb
Enter a product
ccc cccc ccccc
Enter a product
Enter a product
Enter a product
q
You wrote the following products
aaa
aaa
bb
ccc
cccc
ccccc
Enter a product
Enter a product
aaaa aaaa aaaa
Enter a product
bb
Enter a product
q
You wrote the following products
aaaa aaaa aaaa
bb
Quite clear that the default delimiter space is adding the products separated by space to the list when next is used, so each time space separated strings are entered on a line, they are different strings.
With nextLine, space has no significance and the whole line is one string.
I have heard that nextInt() reads only the integers and ignores the \n at the end.
So why does the following code runs successfully?
Why there is no error after we enter value of a since \n must remain in the buffer ,
so use of nextInt() at b should give an error but it doesn't . Why?
import java.util.Scanner;
public class useofScanner {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int a = scanner.nextInt();
int b=scanner.nextInt();
System.out.println(a+b);
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
As another example, this code allows long types to be assigned from entries in a file myNumbers:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
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.");
}
}