打印输入行中第一个字符小于第二个字符的字符对数

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

我不确定如何比较字符 char < Char 并添加计数

它应该打印出来 输入一行: antidisestablishmentarianism\(用户想输入什么)

你的答案 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 进行比较是您想要的。那么您的 if 语句将类似于

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

此外,在遍历 Scanner 的输入时,您可能应该像这样使用 while 循环来完成它:

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

您需要一种方法来终止该 while 循环 - 您可以通过检查 '\n' 或其他内容来实现。当然,如果您愿意,可以将 while 循环重写为 for 循环。

String element = "antidisestablishmentarianism";

int count = 0;
for (int j=0; j<element.length(); j++)
{
  if(j+1 < element.length()){
    int x = Character.getNumericValue(element.charAt(j));
    int y = Character.getNumericValue(element.charAt(j+1));
    if(x>y){
        count++;
        System.out.println("Pair: "+element.charAt(j)+""+element.charAt(j+1));
    }
  }


}

System.out.println(count+" pairs found");

循环应该遍历从第一个到下一个但最后一个的所有字符,这样您就可以比较相邻的字符。它们可以像整数值一样进行比较。

String s = "antidisestablishmentarianism";
int count = 0;
for( int i = 0; i < s.length() - 1; ++i ){
    if( s.charAt(i) < s.charAt(i+1) ) count++;
}
System.out.println( "count = " + count );

根据您的代码,还可以使用 try-with-resources:

关闭扫描器
import java.util.Scanner;

public class CountRisingPairs {

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

            String inputString = in.next();
            int count = 0;
            char previousChar = 100;

            for (char currentChar : inputString.toCharArray()) {
                if (currentChar > previousChar) {
                    count++;
                }
                previousChar = currentChar;
            }
            System.out.println(count);
        }
    }
}