How to trim white space in StringBuffer in JAVA [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was trying to reverse the String using pre-defined method reverse() which is available in StringBuffer
I took input from the user and while printing the reverse string I used toString() method to avoid an extra space
import java.util.*;
public class Small {
public static void main(String a[])
{
int num;
Scanner sc=new Scanner(System.in);
num = sc.nextInt();
while(num>0)
{
String t;
t=sc.nextLine();
StringBuffer sb=new StringBuffer(t);
sb.reverse();
System.out.println(sb.toString());
num--;
}
}
}
Input:
2
hello
welcome
Output:
<Empty line>
olleh
Can anyone please advise why this blank space is coming and also not getting second output?

sc.nextInt() doesn't consume the newline at the end of the line containing the number.
Add sc.nextLine(); after it:
num = sc.nextInt();
sc.nextLine();

Related

scanner doesn't wait for input when i used nextLine after using nextInt().Is it a bug [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
In this program, string variable fd doesn't wait taking input.
Can someone help me with this program.
i can get the input if i use the new scanner object though.
import java.util.Scanner;
public class Strmethod {
public static void main(String[] args)
{
String ch,fd;
int s,e;
Scanner sc=new Scanner(System.in);
System.out.print("Enter A String:");
ch=sc.nextLine();
System.out.println("String is "+ch);
System.out.println("Enter Two Numbers For Substring:");
s=sc.nextInt();
e=sc.nextInt();
System.out.println("Substring:"+ch.substring(s,e));
System.out.println("Enter a Word to search:");
fd=sc.nextLine();
System.out.println(ch.contains(f));
String jn=String.join("/","hello","g","u","y","s");
System.out.println(jn);
System.out.println(ch.startsWith("H"));
System.out.println(ch.startsWith("e"));
System.out.println("Length:"+ch.length());
String newstr=ch.replace("Hello","Hey");
System.out.println("String is "+ch);
}
}
The above picture shows the input in the form of a buffer your program is using.
Explanation:
When you first use the nextLine() function it reads the whole buffer up to \n character. Now the next buffer line starts and you have used nextInt() to read an integer 3 again nextInt() to read 6 now you have pressed enter i.e. \n character that is appended to the last of the buffer.
The current position of the buffer is that already contains the \n character so when you use the nextLine() method it consumes the \n character from the buffer and takes no input from the console.
Solution:
The solution is to use the nextLine() whenever using the last nextInt() or similar functions that don't read the full line.
The final program would be
...
System.out.println("Enter Two Numbers For Substring:");
s=sc.nextInt();
e=sc.nextInt();
sc.nextLine(); // <--- to read the last \n character from the buffer
System.out.println("Substring:" + ch.substring(s,e));
System.out.println("Enter a Word to search:");
fd=sc.nextLine();
...

How to get a pair of Strings in a for loop? [duplicate]

This question already has answers here:
Scanner and nextInt discard integer
(3 answers)
Closed 4 years ago.
Why usage of nextLine() is not efficiently takes the input?
If i use next() instead of nextLine() the code is super good but why? whats the reason behind it.Where and all i should use next and nextLine();
import java.util.Scanner;
public class Sample{
public static void main(String args[]) {
String a,b;
Scanner scan = new Scanner(System.in);
q = scan.nextInt();
for(int m=0;m<q;m++) {
a = scan.nextLine();
b = scan.nextLine();
System.out.println(a + "" + b);
}
}
}
Expected:
2
mnopm
nop
mnop nop
abcdee
bee
abcdee bee
Actual:
2
mnop
mnop(output appears before taking the 2nd input)
abcee
bee
abcee bee
Replace q = scan.nextInt(); with q = Integer.valueOf(scan.nextLine()); This will do the trick
The Scanner.nextInt() method does not read the newline character in your input created by hitting enter. Please refer this link for more info

Length method in java , when used on input string does not produce the expected result [duplicate]

This question already has answers here:
Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class
(24 answers)
Closed 5 years ago.
My initial code that does not produce the desired result:
import java.util.Scanner;
class Strings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your word: ");
String word1 = sc.next();
System.out.println(word1.length());
sc.close();
}
}
Output:
tk#localhost:~$ java Strings
Enter your word:
avada kedavra
5
Which is not the length of my string.
But when I try this(without the user input) :
class Strings {
public static void main(String[] args) {
String str = new String("avada kedavra");
System.out.println(str.length());
}
}
Output :
tk#localhost:~$ java Strings
13
It works!
So , why doesn't it work when I take input from the user? What am I missing?
By default, sc.next() finds and returns the next complete token. By default, a token is a word, something separated with spaces or newline (\p{javaWhitespace}+).
So in your first example, word1 = "avada", with length 5.
Use sc.nextLine() to get the complete line.
In short: RTFM
A bit longer for the click-lazy: Scanner returns the "next token" when calling next Tokens are calculated by taking a pattern, which is "all whitespaces" by default. So your call of next returns the next word and not the complete line as you intended.
Set a fitting pattern when instantiating Scanner or call nextLine instead.

How does the method Scanner.nextInt() works compare to Scanner.nextLine() [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I've just started Java recently. There's an exercise that ask me to split and display the number separated by spacebar.
The standard input is basically like this:
2
2 2
The first line is the number of integers in the array.
The second line is the array
This is the first block of code that I use
import java.util.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args)
{
Scanner reader= new Scanner(System.in);
int t=reader.nextInt();
String []s=reader.nextLine().split(" ");
for(int i=0;i<=t-1;i++)
{
System.out.println("The "+(i+1) +" number is "+s[i]);
}
}
}
When compile and run it gives me this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:15)
However when I change the the reader.nextInt() to reader.nextLine() and parse it into integer it works perfectly fine
import java.util.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args)
{
Scanner reader= new Scanner(System.in);
int t=Integer.parseInt(reader.nextLine());
String []s=reader.nextLine().split(" ");
for(int i=0;i<=t-1;i++)
{
System.out.println("The "+(i+1) +" number is "+s[i]);
}
}
}
This is what the output looks like
The 1 number is 2
The 2 number is 2
So why doesn't it work with reader.nextInt() ?
Edit about the reading the Line character, I still don't get it. It reads the string normally
int t=reader.nextInt();
Reads a 2.
reader.nextLine()
Reads to the next newline character.
Calling it again will read 2 2, as expected.
Check the content of s. It's likely empty, or doesn't have 2 elements, thus the error
When you read the line twice, you consume the newline
For more info, see Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

System.out.println not working for string [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I'm trying to learn Java through Hackerrank and the challenge that I'm working on currently takes an int, double, and string and prints them on separate lines in reverse order, but I haven't been able to get the string to print.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
double y=sc.nextDouble();
String s=sc.nextLine();
System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
}
}
The input is:
42
3.1415
Welcome to Hackerrank Java tutorials!
And output is:
String:
Double: 3.1415
Int: 42
I don't know Java at all, but from the code I've seen online, I can't tell why this is wrong.
Change the first part of the code to this:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
double y = sc.nextDouble();
sc.nextLine(); // Discard rest of current line
String s = sc.nextLine();
The way java.util.Scanner splits the input into numbers or lines is a bit weird.
The sc.nextLine(); should instead be sc.next();

Categories