【问题标题】:i have problems in this code and i get yes in the all answer [closed]我在这段代码中有问题,我在所有答案中都得到了肯定[关闭]
【发布时间】:2014-11-01 08:45:25
【问题描述】:

编写一个程序,当给定一个字符串s 和一个字符c 时,如果c 输出'yes' 存在于s。否则打印出“否”。 (你应该使用循环来做到这一点。你 只能使用 String 类型的 length() 和 charAt() 函数。)

示例:

 south u --> yes 
 north T --> no

输出应该是这样的:

 >Please enter a string: 
 >ahmet
 >Please enter a char: 
 >m
 >yes

我尝试实现它,但我不知道我的代码有什么问题。我总是得到“真实”。 在我的实现中,我使用了一个可以是 0 或 1 的整数。 如果它是 0,我打印 false。 如果它是 1,我打印 true。

这是我的代码:

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");
  }     
}

【问题讨论】:

  • 那是 Java 代码,而不是 C 或 C++!
  • 因为 e 永远是 1!为什么有两个循环?

标签: java string


【解决方案1】:

您将字符串的所有字符与同一字符串的所有字符进行比较,因此您当然会找到匹配项并返回“是”。你只需要一个循环。

你只需要:

e = 0;
for ( int i = 0 ; i <t ; i++) {    
    f = name.charAt(i);
    if (f==c) {
        e = 1;
        break;
    }
}

【讨论】:

  • 非常感谢它正在工作
【解决方案2】:

试试这个:

boolean isCharFound = false;
for ( int i = 0 ; i <t ; i++) {    
    f = name.charAt(i);
    if (f==c) {
       isCharFound = true;
       break;
    }
}
  • 您正在使用具有相同字符串的两个循环,因此如果您的字符串是“abc”,则您将 abc 与 abc 进行比较,因此您总是会在同一个字符串 abc 中看到 sat char a。所以这就是错误。
  • 另一种改进代码的方法是,您应该使用布尔值而不是整数来判断是否在字符串中找到字符。

【讨论】:

  • 谢谢,是的,现在可以使用了
【解决方案3】:

你应该试试这个:

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;
        }
    }
}

【讨论】:

  • 非常感谢它正在工作
猜你喜欢
  • 1970-01-01
  • 2022-06-10
  • 2022-06-30
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
相关资源
最近更新 更多