for the below input im expecting all the strings delimited with "|" to be available in an array. but only first string is available and the next string is partially available.the rest is not at all available. please help me in understanding it. i explored all the help docs and previous stackoverflow stuff but not able to solve it. i tried with split(String regex,int limit)as well but no use. I dont want to replace the whitespace as i need to retain that.
input "1|New York|1345|134|45634"
Expected output is: 1,New York,1345,134,45634
Actual output is:1,New
public class test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String strinp=scanner.next();
//System.out.println(strinp.replaceAll(" ", ""));
String[] strArr=strinp.split("\\|");
//System.out.println(Arrays.deepToString(strArr));
for (String s:strArr) {
System.out.println(s);
}
}
}
scanner.next() splits on spaces itself. So your first scanner.next() call reads 1|New which you then split.
Use scanner.nextLine() to read the whole line, it will be split successfully.
Change:
String strinp = scanner.next();
To:
String strinp = scanner.nextLine();
Or you can declare scanner as:
Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
Related
I have a textfile that i am reading out of that looks like this:
pizza, fries, eggs.
1, 2, 4.
I am scannning this .txt using the Scanner class and i want to insert the input into an ArrayList. I know that there is a method to split Strings and use the "," as a Delimiter but i cannot seem to find how and where to apply this. Note: The . is used as its own Delimiter so the scanner know it needs to check the next Line and add that to a different ArrayList.
Here is my corresponding code from the class with the ArrayList Setup:
public class GrocerieList {
static ArrayList<String> foodList = new ArrayList<>();
static ArrayList<String> foodAmount = new ArrayList<>();
}
And here is the code from the class scanning the .txt input:
public static void readFile() throws FileNotFoundException {
Scanner scan = new Scanner(file);
scan.useDelimiter("/|\\.");
scan.nextLine(); // required because there is one empty line at .txt start
if(scan.hasNext()) {
GrocerieList.foodList.add(scan.next());
scan.nextLine();
}
if(scan.hasNext()) {
GrocerieList.foodAmount.add(scan.next());
scan.nextLine();
}
}
Where can i split the strings? And how? Perhaps my approach is flawed and i need to alter it? Any help is greatly appreciated, thank you!
Use nextLine() to read a line from the file, then eliminate the ending period, and split on comma.
And use try-with-resources to close the file correctly.
public static void readFile() throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.nextLine(); // required because there is one empty line at .txt start
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
GrocerieList.foodAmount.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
}
}
Usually you would save the read out from the nextLine method, and use the split method to decompose the list into an array, then store it to your target. If conversion is needed, such as from string to integer, do it separately.
String lineContent = scan.nextLine();
String[] components = lineContent.split(","); //now your array has "pizza", "fries", "eggs" etc.
The easiest way to do this would be to use String#split.
Also you don't want 'next', but nextLine
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(", ")));
(Should work but didn't test it).
For more informations about the scanner class refer to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
I have to write a program which prints the String which are inputed from a user and every letter like the first is replaced with "#":
mum -> #u#
dad -> #a#
Swiss -> #wi## //also if it is UpperCase
Albert -> Albert //no letter is like the first
The user can input how many strings he wants. I thought to split the strings with the Split method but it doesn't work with the ArrayList.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
ArrayList <String> Parolecens= new ArrayList <String>();
while (s.hasNextLine()) {
tdc=s.nextLine();
Parolecens.add(tdc);
}
System.out.println(Parolecens);
}
}
If you want to read in single words you can use Scanner.next() instead. It basically gives you every word, so every string without space and without newline. Also works if you put in two words at the same time.
I guess you want to do something like this. Feel free to use and change to your needs.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
while (s.hasNext()) {
tdc=s.next();
char c = tdc.charAt(0);
System.out.print(tdc.replaceAll(Character.toLowerCase(c) +"|"+ Character.toUpperCase(c), "#"));
}
}
}
Edit:
Basically it boils down to this. If you want to read single words with the scanner use .next() instead of .nextLine() it does consider every word seperated by space and newline, even if you put in an entire Line at once.
Tasks calling for replacing characters in a string are often solved with the help of regular expressions in Java. In addition to using regex explicitly through the Pattern class, Java provides a convenience API for using regex capabilities directly on the String class through replaceAll method.
One approach to replacing all occurrences of a specific character with # in a case-insensitive manner is using replaceAll with a regex (?i)x, where x is the initial character of the string s that you are processing:
String result = s.replaceAll("(?i)"+s.charAt(0), "#");
You need to ensure that the string is non-empty before calling s.charAt(0).
Demo.
Assuming that you've successfully created the ArrayList, I'd prefer using the Iterator interface to access each elements in the ArrayList. Then you can use any String variable and assign it the values in ArrayList . Thereafter you can use the split() in the String variable you just created. Something like this:
//after your while loop
Iterator<String> it = Parolecens.iterator();
String myVariable = "";
String mySplitString[];
while(it.hasNext()) {
myVariable = it.next();
mySplitString = myVariable.split(//delimiter of your choice);
//rest of the code
}
I hope this helps :)
Suggestions are always appreciated.
I'm trying to do some homework for my computer science class and I can't seem to figure this one out. The question is:
Write a program that reads a line of text and then displays the line, but with the first occurrence of hate changed to love.
This sounded like a basic problem, so I went ahead and wrote this up:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.next();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
I expect a string input of "I hate you" to read "I love you", but all it outputs is "I". When it detects the first occurrence of the word I'm trying to replace, it removes the rest of the string, unless it's the first word of the string. For instance, if I just input "hate", it will change it to "love". I've looked at many sites and documentations, and I believe I'm following the correct steps. If anyone could explain what I'm doing wrong here so that it does display the full string with the replaced word, that would be fantastic.
Thank you!
Your mistake was on the keyboard.next() call. This reads the first (space-separated) word. You want to use keyboard.nextLine() instead, as that reads a whole line (which is what your input is in this case).
Revised, your code looks like this:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.nextLine();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
Try getting the whole line like this, instead of just the first token:
String text = keyboard.nextLine();
keyboard.next() only reads the next token.
Use keyboard.nextLine() to read the entire line.
In your current code, if you print the contents of text before the replace you will see that only I has been taken as input.
As an alternate answer, build a while loop and look for the word in question:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
// Start with the word we want to replace
String findStr = "hate";
// and the word we will replace it with
String replaceStr = "love";
// Need a place to put the response
StringBuilder response = new StringBuilder();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
System.out.println("<Remember to end the stream with Ctrl-Z>");
String text = null;
while(keyboard.hasNext())
{
// Make sure we have a space between characters
if(text != null)
{
response.append(' ');
}
text = keyboard.next();
if(findStr.compareToIgnoreCase(text)==0)
{
// Found the word so replace it
response.append(replaceStr);
}
else
{
// Otherwise just return what was entered.
response.append(text);
}
}
System.out.println("I have rephrased that line to read:");
System.out.println(response.toString());
}
}
Takes advantage of the Scanner returning one word at a time. The matching will fail if the word is followed by a punctuation mark though. Anyway, this is the answer that popped into my head when I read the question.
I'm trying to print a string in reverse. i.e.
hello world
should come out as:
dlrow olleh
But the outcome only shows the reverse of the first word. i.e.
olleh
Any thoughts?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Input a string:");
String s;
s = input.next();
String original, reverse = "";
original = s;
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
input.close();
}
}
Using input.next() only stores the next word in the variable (only "hello"). Try this:
System.out.println("Input a string:");
String s;
s = input.nextLine();
System.out.println("entered: " + s);
The line
s=input.next()
will only take one word.
So to get the whole line 'hello world', you've to use the nextLine() function.
s = input.nextLine();
Your scanner object returns only the next complete token through the input.next() method. A token is considered complete when there is a whitespace character. Use the nextLine() method of the scanner to get the complete input if you are using multiple words.
new StringBuilder("hello world").reverse().toString();
Maybe much more simpler.
use s.nextline() instead of s.next() as s.next() read only first token string
Scanner sc= new Scanner(System.in);
String s = sc.nextLine();
System.out.println(new StringBuilder(s).reverse().toString());
From Scanner javadoc:
public String next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
What happens is that the token delimiter may not be what you're expecting (newline, for instance).
If you wish your program to read the entire line input by the user, you might want to use Scanner.nextLine(), which will read the entire line input by the user, or maybe Scanner.next(String delimiter), which will allow you to enter the desired token delimiter.
Change s = input.next() to s = input.nextLine()
I can't really write some source code but maybe try using two different inputs. After that add each string to it's own variable. After that, reverse them both and add them together as an output.
I have a text file as follows:
Title
XYZ
Id name
1 abc
2 pqr
3 xyz
I need to read the content starting with the integer value and I used the regular expression as in the following code.
public static void main(String[] args) throws FileNotFoundException {
FileInputStream file= new FileInputStream("C:\\Users\\ap\\Downloads\\sample1.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.startsWith("[0-9]")) {
System.out.println("Line: "+line);
}
}
}
The above code can't detect the lines starting with integers. However, it works fine if single integer values are passed to startsWith() function.
Please suggest, where I went wrong.
String#startsWith(String) method doesn't take regex. It takes a string literal.
To check the first character is digit or not, you can get the character at index 0 using String#charAt(int index) method. And then test that character is digit or not using Character#isDigit(char) method:
if (Character.isDigit(line.charAt(0)) {
System.out.println(line);
}
For regex you can use the "matches" method, like this:
line.matches("^[0-9].*")