例如,我想查找数字123900148中重复1的次数 它必须被写入2次,但每次都会得到错误的值
Scanner input = new Scanner(System.in);
@author Başar Ballıöz
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
for (int i = 0; i < number.length() - 1 ; i++) {
if (number.substring(i , i+1).equals(repeat))
counter++;
}
System.out.println(repeat + " number " + counter + " repeated.");
我希望看到如下输出:
number : 134211
number i want to find how many times repeated: 1
your number has repeated 3 times
答案 0 :(得分:4)
您正在将String
(由number.substring(i , i+1
返回)与Integer
进行比较,因此当然它将始终返回false
。
比较两个int
或两个String
。由于您本质上是比较两个数字,因此比较int
会更有效。
for (int i = 0; i < number.length(); i++) {
if (Character.getNumericValue(number.charAt(i)) == repeat) {
counter++;
}
}
答案 1 :(得分:3)
Scanner input = new Scanner(System.in);
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
while (tmp > 0) {
if (tmp % 10 == repeat) {
counter++;
}
tmp = tmp/10;
}
System.out.println(number + " number " + counter + " repeated.");
答案 2 :(得分:2)
您正在通过String
将Integer
与equals
进行比较,因此无法获得预期的结果。而是在比较之前将整数转换为字符串:
if (number.substring(i , i+1).equals(String.valueOf(repeat)))
此外,您可以将String.valueOf(repeat)
的结果缓存到for
循环之前的变量中,以防止在每次循环中构造字符串对象。
答案 3 :(得分:0)
尝试一下。我添加了一些有用的输出,以便您可以看到如何对其进行索引。
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class CountChars {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter A String: ");
Map<String, Integer> map = indexString(input.nextLine());
while (true) {
System.out.print("Enter A Character You Want To Count (ENTER to exit): ");
String repeat = input.nextLine();
if (repeat == null || repeat.isEmpty()) {
break;
}
System.out.println(String.format("'%s' was repeated %d time(s).", repeat, (map.containsKey(repeat)) ? map.get(repeat):Integer.valueOf(0)));
}
}
private static Map<String, Integer> indexString(String s) {
Map<String, Integer> map = new HashMap<>();
System.out.println(String.format("'%s' has %d characters. Indexing now.", s, s.length()));
for (int i = 0; i < s.length() ; i++) {
String c = String.valueOf(s.charAt(i));
if (!map.containsKey(c)) {
map.put(c, 0);
System.out.println(String.format("Indexing %s", c));
}
System.out.print(String.format("Incrementing '%s' from %d ", c, map.get(c)));
map.put(c, map.get(c) + 1);
System.out.println(String.format("to %d.", map.get(c)));
}
return map;
}
}