What's new
  • Welcome to PHCorner Forums. Take a moment to Sign up and gain unlimited access and extra privileges that guests are not entitled to, such as: All that and more! Registration is quick, simple and absolutely free. Join our community today!

Help Patulong po sa mga magaling mag program

mrHazan

Eternal Poster
, Last edited:
search mo yung toCharArray() sa java.
saka ASCII para hinidi marami parameters mo sa if-else o maraming cases sa switch.
 

Arcturus

Forum Guru
sana makatulong paps
Java:
import java.util.ArrayList;
import java.util.Scanner;
public class test2 {
    static boolean isVowel(char c) {
        switch(Character.toLowerCase(c)) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            return true;
        }
        return false;
    }
    
    static void duplicateFinder(String input) {
        ArrayList<Character> Duplicates = new ArrayList<Character>();
        
        //Determine which one is a duplicate
         for (int i = 0; i < input.length(); i++) {
                for (int j = 1; j < input.length(); j++) {
                    char ci = input.charAt(i);
                    char cj = input.charAt(j);
                    if (ci == cj && i != j && !Duplicates.contains(ci)) {
                        // duplicate element found
                        Duplicates.add(ci);
                        break;
                    }
                }
            }
        //Iterate the duplicates
        for(int i = 0; i < Duplicates.size(); i++) {
            char c = Duplicates.get(i);
             int count = 0;
            System.out.print("Character with Duplicate: "+c);
            //count the number of duplicate happens
            for(int k  = 0; k < input.length(); k++) {
                if(c == input.charAt(k))
                    count++;
            }
            System.out.println(" : Count: "+count);
        }
    }
    static Scanner sc = new Scanner (System.in);
    public static void main(String []args){
        int numVowel = 0, numConsonant = 0, numDigits = 0, numSpace = 0, numSpecialCharacters = 0;
        System.out.println("Input String: ");
        String input = sc.nextLine();
        
        for(int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if(Character.isAlphabetic((int)c)) { //if character is a alphabetic
                if(isVowel(c))
                    numVowel++;
                else
                    numConsonant++;
            }
            else if(Character.isDigit(c)) //if character is a digit
                numDigits++;
            
            else if((int)c == 32)  //if character is a space
                numSpace++;
            
            else            //otherwise its a special character
                numSpecialCharacters++;
            
        }
        //Finally output everything
        duplicateFinder(input);
        System.out.println("Vowels: "+numVowel);
        System.out.println("Consonants: "+numConsonant);
        System.out.println("Digits: "+numDigits);
        System.out.println("White Spaces: "+numSpace);
        System.out.println("Special Characters: "+numSpecialCharacters);
    }
}
 

pixkit

Addict
Check this REPL: You must register or login to view this.

I prefer a more modular, SRP approach where the user input handler is SEPARATE from string analyzer. In this way if you wanna extend the input to be a loop input (or whatever you want), you don't need to modify the string analyzer. And if you want to modify the string analyzer, you don't need to mess up with the user input handler.

If you need to add a new string analyzer function, you just have to add a new static method in the StringAnalyzer class. Each analyzer is separate static method and the need for multiple if-else statements are drastically reduced.

Some notes:
- You can probably split the StringAnalyzer into classes: one that's purely an analyzer and another that just prints the output. - You can replace the InputReader to read from a file or IOT device and still keep the StringAnalyzer as is.
- Ideally you will have a unit test to verify the behavior of these classes.
- If the time comes, you found a better way to optimize how to detect consonants faster, then you just have to change the static method for the consonant analyzer. No need to touch the other methods.
- ALSO, I DO NOT KNOW all of the syntax and exact methods here by rote memorization. I had to Google first and see how people have done these kind of problems and also check the Java documentation. Here's what I know though: I HAVE AN IDEA how to approach the problem and organize my thoughts. My point is the latter is way more important than rote memorization. If you ask me in an actual job interview how to do this, I guarantee you that I will NOT be able to write this exact solution, but I can write the pseudocode though.

Java:
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.HashMap;

// Reads user input
class InputReader {
  public static String prompt() {
    Scanner scanner = new Scanner(System.in);
    System.out.printf("Input String: ");
    String input = scanner.nextLine();
    scanner.close();
    return input;
  }
}

// Analyzes a string's characteristics
class StringAnalyzer {
  public static void parse(String word) {
    printDuplicates(word);
    System.out.printf("Vowels: %d \n", vowels(word));
    System.out.printf("Consonants: %d \n", consonants(word));
    System.out.printf("Digits: %d \n", digits(word));
    System.out.printf("Spaces: %d \n", spaces(word));
    System.out.printf("Special Characters: %d \n", special(word));
    System.out.println("Process completed.");
  }

  private static void printDuplicates(String word) {
    Map<Character, Integer> dupes = countAndMapCharacters(word).entrySet()
         .stream()
         .filter(entry -> entry.getValue() > 1)
             .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    System.out.printf("Characters with duplicates: %d \n", dupes.size());

    dupes.entrySet()
         .stream()
         .forEach(entry ->
            System.out.printf(
              "Character: %s : Count %d \n",
              entry.getKey(),
              entry.getValue()));
  }

  private static int vowels(String word) {
    return word.replaceAll("[^aeiouAEIOU]", "").length();
  }

  private static int consonants(String word) {
    return word.replaceAll("[^b-df-hj-np-tv-z]", "").length();
  }

  private static int digits(String word) {
    return word.replaceAll("[^0-9]", "").length();
  }

  private static int spaces(String word) {
    return word.replaceAll("[^ ]", "").length();
  }

  private static int special(String word) {
    return word.length()
      - vowels(word)
      - consonants(word)
      - digits(word)
      - spaces(word);
  }

  // Utility function which counts how many times a character has been seen
  private static Map<Character, Integer> countAndMapCharacters(String word) {
    Map<Character, Integer> map = new HashMap();

    word.chars().forEach(item -> {
      Integer currentCount = map.get((char) item);
      if (currentCount == null) {
        map.put((char) item, 1);
      } else {
        map.put((char) item, currentCount + 1);
      }
    });

    return map;
  }
}

class Main {
  public static void main(String[] args) {
    StringAnalyzer.parse(InputReader.prompt());
  }
}

Bash:
# Sample output

 java -classpath .:/run_dir/junit-4.12.jar Main
Input String: asdafgr
Characters with duplicates: 1
Character: a : Count 2
Vowels: 2
Consonants: 5
Digits: 0
Spaces: 0
Special Characters: 0
Process completed.

 java -classpath .:/run_dir/junit-4.12.jar Main
Input String: asdf agr 12 4 & 3** 59@#%
Characters with duplicates: 3
Character:   : Count 6
Character: a : Count 2
Character: * : Count 2
Vowels: 2
Consonants: 5
Digits: 6
Spaces: 6
Special Characters: 6
Process completed.

 java -classpath .:/run_dir/junit-4.12.jar Main
Input String: 1234567888888 @@@ ** asdfasdf
Characters with duplicates: 8
Character:   : Count 3
Character: @ : Count 3
Character: a : Count 2
Character: s : Count 2
Character: d : Count 2
Character: f : Count 2
Character: 8 : Count 6
Character: * : Count 2
Vowels: 2
Consonants: 6
Digits: 13
Spaces: 3
Special Characters: 5
Process completed.
 
Top