Search code examples
javafor-loopcomputer-science

Print how many pairs of characters in the input line where the first character is less than the second


Im not sure how to compare the characters char < Char and add the count

it should print Enter a line: antidisestablishmentarianism\(whatever the user wants to input)

Your Answer 15

import java.util.Scanner;

public class CountRisingPairs {

    public static void main(String[] args) {
        Scanner in =new Scanner(System.in);       
        System.out.println(" Enter a string");      

        String S=in.next();      
        int count;
        int value;
           for (int i=65; i<91; i++) {
              count=0;
              for (int j=0; j<in.length(); j++) {
              value=(int)in[j];
              if (value == i) {
                 count++;
              }
           }
           if (count>0) 
              System.out.println((char)i+" -- "+count);
        }
    }
}

i cant use hash map or any other type of loop.


Solution

  • For comparing chars in the input, you should probably keep a variable with the previous char to compare to. I don't think comparing to the index variable i is what you want. Then your if statement would be something like

    if (value > previous) {
        count++;
    }
    

    Also, when iterating over the input of a Scanner, you should probably do it with a while loop like this:

    while (in.hasNext()) {
        // Your counting here
    }
    

    You need a way to terminate that while loop - you can do that by checking for '\n' or something else. And of course, the while loop can be rewritten as a for loop if you want to.