1. Write a java code for reverse a number.
public class ReverseNum {
public static void main(String args[]){
int num=323,sum=0,r;;
while(num>0){
r=num%10;
sum=r+sum*10;
num=num/10;
}
System.out.println(sum);
}
}
2. Write a code for finding duplicate word in a sentence.
public class DupliWord {
public static void main(String[] args) {
System.out.print("Enter string to analyse:");
Scanner sn = new Scanner(System.in);
String input = sn.nextLine();
// first let us split string into words
String[] words = input.split(" ");
// adds all words into a map
// we also check whether the word is already in map!
Map<String,String> wordMap = new HashMap<String,String>();
for(int i=0;i<words.length;i++) {
String word = words[i].toUpperCase(); // for case insensitive comparison
if(wordMap.get(word)!=null) {
// we found a duplicated word!
System.out.println("Duplicated/Repeated word:"+word);
}else {
wordMap.put(word, word);
}
}
}
}
public class ReverseNum {
public static void main(String args[]){
int num=323,sum=0,r;;
while(num>0){
r=num%10;
sum=r+sum*10;
num=num/10;
}
System.out.println(sum);
}
}
2. Write a code for finding duplicate word in a sentence.
public class DupliWord {
public static void main(String[] args) {
System.out.print("Enter string to analyse:");
Scanner sn = new Scanner(System.in);
String input = sn.nextLine();
// first let us split string into words
String[] words = input.split(" ");
// adds all words into a map
// we also check whether the word is already in map!
Map<String,String> wordMap = new HashMap<String,String>();
for(int i=0;i<words.length;i++) {
String word = words[i].toUpperCase(); // for case insensitive comparison
if(wordMap.get(word)!=null) {
// we found a duplicated word!
System.out.println("Duplicated/Repeated word:"+word);
}else {
wordMap.put(word, word);
}
}
}
}
3. Write a program for sorting a String.
import java.util.Arrays;
public class StringSort {
public static void main(String[] args) {
String s1="deabc";
char[] c=s1.toCharArray();// covert string into sequence of character
Arrays.sort(c);// sorting char
String sorted = new String(c);
System.out.println(sorted);
}
}
4. Write a java code for count word in string.
Method 1:
public class Words_Count {
public static void main(String[] args) {
System.out.println("Enter a string");
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
String[] words=s.trim().split(" ");
System.out.println(words.length);
}
}
Method 2 :
public class Words_Count_2 {
public static void main(String[] args) {
String s="This is a boy";
int count=1;
for(int i=0; i<=s.length()-1; i++){
if((s.charAt(i)== ' ' ) && (s.charAt(i+1) != ' ') ){
count++;
}
}
System.out.println("Number of words = " + count);
}
}
No comments:
Post a Comment