nextInt() in java - java

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

Related

How do I process different delimiters in a RegEx expression with Java?

I am working on creating a program for my course, in which I am required to divide the string: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;.
In the requirements, I need to read a single semicolon as a space, and a double semicolon as a new line. How do I create a regular expression in the useDelimiter() method that allows me to parse through and differentiate between both ; and ;;? Thank you!
Assignment Excerpt:
Instead of hard-coding the string, this time you will read it from the console. Study the useDelimiter() method and use it to set the delimiter for the scanner input. This time allow either colons or semicolons as the delimiters. One might prefer to use the String Tokenizer here, but don’t -- use the Scanner’s useDelimiter() method to set the delimiter in the Scanner and process each token as it comes.
import java.util.Scanner;
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in);
// Prompts user for input.
System.out.println("Enter the string you wish to filter & parse: ");
// Reads user input.
String filterString = input.nextLine();
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString);
a.useDelimiter(";|;;");
System.out.printf("\n");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next());
}
}
}
The Expected output is to be:
You may use this code:
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in).useDelimiter(";;");
// Prompts user for input.
System.out.print("Enter the string you wish to filter & parse: ");
// Reads user input.
while(input.hasNext()) {
String filterString = input.next();
//System.err.println("filterString: " + filterString);
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString).useDelimiter(";");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next() + " ");
}
System.out.println();
a.close();
}
input.close();
}
}
Output:
Enter the string you wish to filter & parse: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;
This is the first line
This is the second line!
Done!
Note use of outer scanner with delimiter ;; and an inner one with ;.

Reverse a string with spaces.going through for loop

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");

Why won't Java print last word here?

Why does this print the entire string "1fish2fish"...
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String input = "1,fish,2,fish";
Scanner sc = new Scanner(input);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
}
}
But this only prints "1fish2" even though I enter "1,fish,2,fish"?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter your string: ");
Scanner sc = new Scanner(System.in);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
}
}
In the first case, the scanner doesn't need the last delimiter, as it knows that there are no more characters. So, it knows that the last token is 'fish' and there are no more characters to process.
In the case of a System.in scan, the fourth token is considered as completed only when the fourth ',' is entered in the system input.
Note that white spaces are considered as delimiters by default. But, once you specify an alternate delimiter using useDelimiter, then white space characters don't demarcate tokens any more.
In fact, your first trial can be modified to prove that white space characters are not delimiters any more...
public static void main(String[] args) {
String input = "1,fish,2,fish\n\n\n";
Scanner sc = new Scanner(input);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.println("Done");
sc.close();
}
The new line characters will be treated as part of the fourth token.
I checked the first snippet; it is correctly printing -
1fish
2fish
Link - http://code.geeksforgeeks.org/jK1Mlu
Please let us know if your expectation is different.
Scanner waits for you to enter another ',' so when you will enter ',' then after that it will immediately prints fish after 1fish2.
so Pass 1,fish,2,fish, instead of 1,fish,2,fish

Trying to break up a string into list

I'm trying to convert a String into a List. I'm getting the string by user input, but whenever I run my code, and it gives me this:
Enter a number: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
This is my code
public class ch3_15 {
public static void main(String[] args) {
int compNum, user_hund, user_ten, user_one, comp_hund, comp_ten, comp_one;
String s;
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.toString();
//generating random number
compNum = (int) Math.random() * 1000;
System.out.println(s);
//finding the hundreds, tens, and ones place of the user number
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
}
}
This is not error. It is expected behavior since you used
Scanner input1 = new Scanner(System.in);
s = input1.toString();
...
System.out.println(s);
and toString() returns String representing of object on which this method was invoked (in this case instance of Scanner).
If you want to use that Scanner to read line from user you should write
s = input1.nextLine();
// ^^^^^^^^
Your problem is that you don't read the next String from the console, but rather convert the Scanner to a String, which you then print.
What you want to use is Scanner.nextLine(), instead of toString().
Also, this is not a runtime error, but simply a wrong output.
you should use scanner.nextLine() to read next line that use enters.
Your current code is printing the toString() method of the scanner object and that is not a runtime error and is an expected behaviour.
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
You are not advancing from your current line; the method to use in this case is nextLine() from the class Scanner; So the code would be something like:
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
String aux = s.toString(); // To return the string representation from the sc
nextLine() method from Java API 7 => This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.**/

How do I make Java register a string input with spaces?

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.");
}
}

Categories

Resources