java语言,输入一个字符串,一个字符。输出这个字符串中该字符个数。这是我写的程序,求改错,在线等。

import java.util.Scanner;
import java.awt.*;

public class exercise2
{
public static void main(String[ ] args)
{
Scanner scan=new Scanner(System.in);
int i,n=0;
System.out.println("Type in a character string to be searched:");
System.out.print(">");
String a=scan.next();
System.out.println("Type in the character to be counted.");
System.out.print(">");
String b=scan.next();
for(i=0;i<a.length();i++)
{
char c = a.charAt(i);
char d = b.charAt(0);
if(c==d);
n=n+1;
}
System.out.println("The letter a occurs " + n + " time in the string.");
}
}

只要去了循环后的那个分号就可以了..

import java.util.Scanner;

public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i, n = 0;
System.out.println("Type in a character string to be searched:");
System.out.print(">");
String a = scan.next();
System.out.println("Type in the character to be counted.");
System.out.print(">");
String b = scan.next();
for (i = 0; i < a.length(); i++) {
char c = a.charAt(i);
char d = b.charAt(0);
if (c == d)//去了分号就可以了
n = n + 1;
}
System.out.println("The letter a occurs " + n + " time in the string.");
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-12-13
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i, n = 0;
System.out.println("Type in a character string to be searched:");
System.out.print(">");
String a = scan.next();
System.out.println("Type in the character to be counted.");
System.out.print(">");
String b = scan.next();
for (i = 0; i < a.length(); i++) {
char c = a.charAt(i);
char d = b.charAt(0);
if (c == d){
n = n + 1;/*此处错误,不要不打大括号,现在大公司里面都有要求代码规范的!*/
}
}
System.out.println("The letter a occurs " + n + " time in the string.");
}

/*一般情况下,不常使用char类型的,装箱,拆箱的,麻烦!也基本上很少有去比较一个char类型的,大部分都是字符转的比较!本回答被提问者采纳
第2个回答  2011-12-12
if(c==d); 多个分号
char d = b.charAt(0);拿到for前边
相似回答