So I am trying to take multiple inputs. here is the question:- Given two strings of equal length, you have to tell whether they both strings are identical.
Two strings S1 and S2 are said to be identical, if any of the permutation of string S1 is equal to the string S2. See Sample explanation for more details.
Input : First line, contains an intger 'T' denoting no. of test cases. Each test consists of a single line, containing two space separated strings S1 and S2 of equal length.
Output:
For each test case, if any of the permutation of string S1 is equal to the string S2 print YES else print NO.
Constraints:
1<= T <=100
1<= |S1| = |S2| <= 10^5
String is made up of lower case letters only.
import java.io.*;
import java.util.*;
public class test
{
public static void main(String args[])throws IOException
{
String parts[]=new String[10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter no of inputs");
int n=sc.nextInt();
int j=n;
for(int i=0;i<j;i++)
{
System.out.println("Enter string");
String s=sc.next();
int in=s.indexOf(" ");
String s1=s.substring(0,in);
String s2=s.substring(in+1);
boolean status = true;
if (s1.length() != s2.length())
{
status = false;
}
else
{
char[] ArrayS1 = s1.toCharArray();
char[] ArrayS2 = s2.toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status==true)
{
System.out.println(s1 + " and " + s2 + " are anagrams");
}
else
{
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
}
}
the error
issue
The issue is the statement
String s = sc.next();
That will never consume a token with a space (because white space is the delimiter). Change it to
String s = sc.nextLine();
And then
int in = s.indexOf(" ");
will work (but only if the input contains a space); so you should still test it is not -1
yourself.
if (in >= 0) {
String s1 /* ... */
}
Also,
int n=sc.nextInt();
will leave trailing newlines (and skip your next input) using nextLine()
so consume that too.
int n=sc.nextInt();
sc.nextLine(); // <-- skip trailing new line.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments