Please in detail explain the rules in this program: import java.util.Scanner; pu
ID: 3547903 • Letter: P
Question
Please in detail explain the rules in this program:
import java.util.Scanner;
public class Test4
{
// Main method
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String s;
System.out.print("Enter the string: ");
s = input.nextLine();
System.out.print("Duplicate characters: ");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int j;
for (j = 0; j < i; j++) {
if (s.charAt(j) == c) {
break;
}
}
if (j == i) {
for (j = i + 1; j < s.length(); j++) {
if (s.charAt(j) == c) {
System.out.print(c);
break;
}
}
}
}
System.out.println();
} // end of main method
} // end of class
Explanation / Answer
import java.util.Scanner; //for intake of new items
public class Test4
{
// Main method
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //input = newly entered string
String s;
System.out.print("Enter the string: "); //prompt to enter a string
s = input.nextLine(); //s is assigned to the string
System.out.print("Duplicate characters: "); //prompt to duplicate characters after
for (int i = 0; i < s.length(); i++) { // iterating i upto lenght of string
char c = s.charAt(i); // c= present char
int j;
for (j = 0; j < i; j++) { /iterate j upto i checking whether any letter matches
if (s.charAt(j) == c) {
break; //if matches the stop and exit
}
}
if (j == i) { //for j==i
for (j = i + 1; j < s.length(); j++) { // check from j=i+1
if (s.charAt(j) == c) { //if any match found
System.out.print(c); //print the matched char
break;
}
}
}
}
System.out.println(); //nextline
} // end of main method