编写一个程序,当给定字符串
s
和字符c
时,如果c
打印出“是” 存在于s
中。否则打印出'不'。 (你应该使用循环来做它。你 只能使用String类型的length()和charAt()函数。)
示例:
south u --> yes
north T --> no
输出应该如下所示:
>Please enter a string:
>ahmet
>Please enter a char:
>m
>yes
我试图实现它,但我不知道我的代码中有什么问题。我总是“真实”。 在我的实现中,我使用了一个可以是0或1的整数。 如果是0,我打印假。 如果它是1我打印真实。
这是我的代码:
package ass32;
import java.util.Scanner;
public class ass33
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("give me any string : ");
String name = in.next();
System.out.println(">Please enter a char: ");
char c = in.next().charAt(0);
int e = 0 ;
int t = name.length();
char f ;
char s ;
for ( int i = 0 ; i <t ; i++) {
f = name.charAt(i);
for ( int j = 0 ; j <t ; j++) {
s = name.charAt(j);
if (s==f)
e = 1 ;
}
}
if (e==1 )
System.out.println("yes");
else if (e==0 )
System.out.println("no");
}
}
答案 0 :(得分:1)
您正在将字符串的所有字符与同一字符串的所有字符进行比较,因此您找到匹配项并返回&#34;是&#34;。你只需要一个循环。
您只需要:
e = 0;
for ( int i = 0 ; i <t ; i++) {
f = name.charAt(i);
if (f==c) {
e = 1;
break;
}
}
答案 1 :(得分:0)
你应该试试这个:
for (int i = 0; i < t; i++) {
f = name.charAt(i);
for (int j = 0; j < t; j++) { // Remove this loop
s = name.charAt(j); // Remove this also
if (s == f) { // Change this to (c==f)
e = 1;
}
}
}
答案 2 :(得分:0)
试试这个:
boolean isCharFound = false;
for ( int i = 0 ; i <t ; i++) {
f = name.charAt(i);
if (f==c) {
isCharFound = true;
break;
}
}