how to modify string with scanner? [duplicate] - java

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I already have a string let's say
String abc = "Stack";
Now, I want to modify this string using scanner class only ! So, user should to able to see existing string on console and then he can edit that string.
I tried this, but then it just replaces the existing string.
System.out.println("Edit the below string");
System.out.println(abc);
abc = scanner.nextLine();
How would I achieve it ?

Well the issue is you shouldn't with just a String. Your problem is the reason StringBuffer was created. Ideal solution:
StringBuffer buffer = new StringBuffer("Stack");
while (scanner.hasNextLine()){
buffer.append(scanner.nextLine());
System.out.println(buffer.toString());
}
String abc = buffer.toString(); //if you really need to save it to variable 'abc' for some reason.
Here is a terrible example if you hate your computer and can only user a String.
String abc = "Stack";
while (scanner.hasNextLine()){
abc += scanner.nextLine();
System.out.println(abc);
}
The above is a terrible solution for memory reason.
I hope this helps

Related

Java program to take string as user input and store it in array, then print it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm sorry if I'm not able to explain the question. When I take user input it prints only the first word of the string.
Help me understand what I'm missing, or why is it not working when I take user input.
When I pass the input, "This is Mango", it prints only
This.
Instead I want to print it as This
is
Mango
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the String: ");
String str= in.next();
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.println(words[i]+" ");
If I give a hard-coded string, it is able to save it in array.
String str = "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.println(words[i]+" ");
When I run the above code, it prints as
This
is
a
sample
sentence
Change this line:
String str = in.next();
to this:
String str = in.nextLine();
This way, your Scanner object will read the whole line of input.
If you only use next() it only reads the input until it encounters a space. Meanwhile, nextLine() reads the whole line (so until you escape to the next line when providing input). Also note that if you would like to read other data types you would need to use the corresponding function. For example, to read an integer you should use nextInt().
Hope this helps!

Search String in file [duplicate]

This question already has answers here:
Creating a Java Program to Search a File for a Specific Word
(3 answers)
Closed 5 years ago.
I am trying to count the number of times a specific string appears into a file.
This is the code I am using:
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(wordidnamee1))
count++;
}
This code only counts the number of time the string appears 'clean', but if it is attached to another word or followed by a colon it is not counted.
How can I solve this problem ?
Use contains()
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.contains(wordidnamee1))
count++;
}
For Non Case Sensitive match:
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.toLowerCase().contains(wordidnamee1.toLowerCase()))
count++;
}

How can I pick a string apart and outprint it? [duplicate]

This question already has answers here:
How to split a String by space
(17 answers)
Closed 5 years ago.
public void display()
{
super.display();
String str = super.getChoices();
System.out.println(str);
while(!str.equals(""))
{
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
}
}
I have a String str containing "Apple Banana Orange". I want to system out print these fruits separately because they are each a choice to a question stored in a single variable. How can I do this? The code above is my failed attempt because the substring doesn't update the str variable rather creates a new string. I can't use a loop and I can't make it dynamic and thus not use it.
You need to change str as well:-
while(!str.equals("") ) {
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
str = str.substring(a); // Remove the bit of str that we've processed.
}
(Untested, but you get the idea). You obviously also need to check if str actually contains a space and drop out.
If i understand you correctly, you should try to use StringTokenizer
StringTokenizer st=new StringTokenizer("Apple Banana Orange");
while (st.hasMoreTokens()){
System.out.println(st.nextToken());
}

How to reversing user input String? [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 6 years ago.
I am trying to reverse user input string my code below is working so that it just output as same as input value..
For example "Hello" will come out "Hello" while result should be "olleH"
This is my code that is in the main as a method call:
System.out.println("Enter a word or phrase you want to be reversed: ");
String s1 = sc.next();
System.out.println("The reversed message is: " + printReverse(s1));
And this is the code that is in my method for the reversal:
public static String printReverse(String str1){
return str1;
}
I know my method is just returning the same message, I did that intentionally as a place holder so that the code would run.
I need to know the most simplest way of doing the reversal, as all examples
I have seen use super complex ways of doing this.
Any help is appreciated.
You can use a StringBuilder, and call reverse on it.
public static String printReverse(String str1) {
return new StringBuilder(str1).reverse().toString();
}

scanner i java doesn't work for all inputs [duplicate]

This question already has answers here:
Scanner doesn't work properly after reading double [duplicate]
(3 answers)
Closed 7 years ago.
I want to read several things ( long, string ) from console but I don't know why for, for example just several first input it works and then it doesn't work for others:
below is the code what I'm talking about, it doesn't ask for adress
public void getInfo(PhoneBook PB)
{
Scanner keyboard = new Scanner(System.in).useDelimiter("\n");
String c1 = "yes";
do {
System.out.print("Name:");
PB.setName(keyboard.nextLine());
System.out.print("Family:");
PB.setFamily(keyboard.nextLine());
System.out.print("Address:");
PB.setAddress(keyboard.nextLine());
System.out.print("Number:");
PB.setNumber(keyboard.nextLong());
System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();
phoneBooks.add(PB);
}while (c1.equals("yes"));
}
Thanks in advance
When you call nextLong() (or nextInt(), nextDouble(), next()...), you are reading in a token with the Scanner, but are not reading in the end-of-line (EOL) token, thus leaving it dangling. This dangling EOL token will then be scooped up immediately with your next call to nextLine(), and so that call will not get the user's input, messing your program up. To fix this, add an additional call to nextLine()after getting your nextLong(), ignoring any result returned since it will just be the EOL token.
So change this:
System.out.print("Number:");
PB.setNumber(keyboard.nextLong());
System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();
to this:
System.out.print("Number:");
PB.setNumber(keyboard.nextLong());
keyboard.nextLine(): // **** add this ****
System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();

Categories