Why won't Java print last word here? - java

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

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 ;.

Why does my Java StringTokenizer read emptyspace?

I wrote this program that should only break down the string when there is greater than sign or a colon. When I enter for example "cars:ford> chevy" , the output gives me the space between the > and "chevy" and then the word "chevy. How do I prevent it from giving me that white space? All I want is the word , here is my code.
import java.util.Scanner;
import java.util.StringTokenizer;
public class wp{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter words");
String ingredients = keyboard.nextLine();
StringTokenizer str = new StringTokenizer(ingredients,">:");
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
As the space is part of the input, it is valid that the tokenizer returns it (think of situations where you want to react to the space).
So all you need to do is postprocess your split results e.g.:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter words");
String ingredients = keyboard.nextLine();
StringTokenizer str = new StringTokenizer(ingredients, ">:");
while (str.hasMoreTokens()) {
String nextToken = str.nextToken();
String trimmed = nextToken.trim();
System.out.println(trimmed);
}
}
}
Answer to trim is ok also, but on line
StringTokenizer str = new StringTokenizer(ingredients, ">:");
you specified delimiters as characters '>' and ':', you can simply add space there too. It depends what your requirements are. If you want for string "cars:ford> chevy 123" to have 4 tokens, this is what you have to do...
So change it to
StringTokenizer str = new StringTokenizer(ingredients, ">: ");
You can use trim() method of String class to remove all preceding and succeeding white spaces:
str.nextToken().trim().

Java scanner: line separator is not recognized as an input

I have a Test class that creates a Scanner and reads a user's input. I want to recognize when a user pressed Enter, so I check if the next symbol of the input equals to lineSeparator. However, even though I do press Enter it doesn't get recognized as such.
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
if (reader.next().equals(System.lineSeparator())) {
System.out.println("finished");
}
/but at the same time, this one works as expected:
String temp = "dog" + System.lineSeparator() + "cat";
System.out.println(temp);
}
}
At the same time when I construct a string using lineSeparator, it works fine, adding a new line as expected.
What is wrong here and how to recognize if a user pressed Enter?
change your code to use hasNextLine() to check if nextline exists and then nextLine() to read the nextLine. Something like this
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
System.out.println("finished");
}

nextInt() in 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

How to take a scanner object and make it a String

I need help doing the following:
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
The below code is what I have so far but it is only returning user input and not removing numbers:
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1.replaceAll("[^0-9]","");
System.out.println(firstname1);
Updated Code. Thank you Hovercraft. I am now investigating how to retrieve all alpha characters as with the code below, I am only getting back the letters prior to the numeric values entered by the user:
import java.util.Scanner;
public class Assignment2_A {
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1 = firstname1.replaceAll("[^A-Z]","");
System.out.println(firstname1);
String input = yourScannerObject.nextLine ();
where "yourScannerObject" is the name you give your scanner.
What method did you use to scan? is it {scanner object name}.next() ?
if so you have got a string and all that you have to do is create some string, and save the input to it, e.g.:
String str="";
str = {scanner object name}.next();
before using anything in java, I would advise you to read the API :
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next()
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
Here's an example:
String in;
Scanner scan = new Scanner("4r1e235153a6d 6321414t435hi4s 4524str43i5n5g");
System.out.println(in = (scan.nextLine().replaceAll("[0-9]", ""))); // use .next() for space or tab
Output:
read this string
The problem in your code is the regex "[^A-Z]" is set to remove all non-alphabet capital characters. This means you remove all lower case as well. You could say "[^a-zA-Z]", but then you're also removing special characters.

Categories

Resources