Only the import java.util.Scanner
package is allowed.
How to Sort a Single String (it's characters) in Alphabetic order in Java?
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
int i,j,k,l;
char temp;
// Complete the function
a = a.toLowerCase();
b = b.toLowerCase();
char [] ca =a.toCharArray();
char [] cb = b.toCharArray();
for(i=0;i<=a.length()-1;i++){
for(j=i+1;j<=a.length()-1;j++){
if(ca[i]>ca[j]){
temp = ca[i];
ca[i]=ca[j];
ca[j]=temp;
}
}
}
for(k=0;k<=b.length()-1;k++){
for(l=k+1;l<=b.length()-1;l++){
if(cb[k]>cb[l]){
temp = cb[k];
cb[k]=cb[l];
cb[l]=temp;
}
}
}
a = String.valueOf(ca);
b = String.valueOf(cb);
if(a.equals(b)){
return true;
}
else{
return false;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}
This is my code. I tried this. but this sorting does'nt work. it's actually program for Anagram.
Seems you wanted to exchange elements i and j here:
if(ca[i]>ca[j]){
temp = ca[0];
ca[0]=ca[1];
ca[1]=temp;
}
but instead you exchange elements 0 and 1.
Install java 1.8 and use its outstanding feature as shown in the below code.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:" );
String data = scanner.next();
data.chars().sorted().forEach( character -> { System.out.print((char)character); }
( This uses only Scanner import and nothing else )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.