2013-12-15 47 views
0

我的任务是创建一个返回true的方法,如果我的整数集中有一个非偶数。我的问题是,即使我在我的设置中有非均匀数字,它也会返回false。我在哪里犯错误?While循环对于偶数编号无法正常工作

import java.util.*; 
public class Chapter_11_E9 
{ 


    public static boolean odd; 
    public static boolean hasOdd(Set<Integer> tSet1) 
    { 
     Iterator<Integer> itr = tSet1.iterator(); 

      while (itr.hasNext()) 
      { 
       int current = itr.next(); 
       if ((current/2) == 1) 
       { 
        odd = true; 
       } 
       else 
       { 
        odd = false; 
       } 
      } 
     return odd; 
    } 

    public static void main(String[] args) 
    { 
     Set<Integer> tSet1 = new HashSet<Integer>(); 
     tSet1.add(6); 
     tSet1.add(2); 
     tSet1.add(5); 
     tSet1.add(4); 
     tSet1.add(12); 
     tSet1.add(6); 
     tSet1.add(14); 
     System.out.println(tSet1);  
     System.out.println(hasOdd(tSet1)); 
    } 
} 
+1

1)没有必要增加的主要标签的称号。 2)请使用代码格式化代码,输入/输出和结构化文档,如HTML或XML。为此,请选择样本并单击邮件发布/编辑表单上方的“{}”按钮。 –

回答

2

这条线:

 if ((current/2) == 1) 

应该是:

 if ((current % 2) == 1) 

/是潜水和%是获取剩余。此外,您的方法逻辑已关闭。假设你有多个赔率和平均数,你可能会得到错误的结果。我建议你这样做:

public static boolean hasOdd(Set<Integer> tSet1) 
{ 
    Iterator<Integer> itr = tSet1.iterator(); 

     while (itr.hasNext()) 
     { 
      int current = itr.next(); 
      if ((current % 2) == 1) 
      { 
       //odd = true; 
       return true;//once you find the odd, just return 
      } 
      //else 
      //{ 
      // odd = false; 
      //} 
     } 
    //return odd; 
    //if you're done iterating, that means it never found an odd so return false 
    return false; 
} 

一旦你发现一个奇怪的集合,那么你的情况是真的。一旦你浏览了整个集合,那么你知道可能没有任何可能性,所以只需返回false。

注意:由于用户ZouZou提到的,如果你想处理负片,然后使用:

current%2 != 0 
+2

总是比较喜欢'当前%2!= 0',因为如果数字是奇数和负数,那就不起作用。 –

0

您需要返回你第一次得到一个奇怪的值(是你只有最后一个项目是奇数时才会返回true)。

public static boolean hasOdd(Set<Integer> tSet1) 
{ 
    Iterator<Integer> itr = tSet1.iterator(); 
    while (itr.hasNext()) 
    { 
    int current = itr.next(); 
    if ((current % 2) != 0) // Check for odd, by computing the modulo 2 of the #. 
    { 
     return true;   // stop, there is an odd value. 
    } 
    } 
    return false;    // checked all the values... none are odd. 
} 
+2

我肯定会在'&'这里使用'%'。优化速度而不是可读性对于这项任务似乎是非常错误的。 – Keppil

0

我会使用,这里每一个循环

public static boolean hasOdd(Set<Integer> set) { 
    for (Integer current : set) { 
    // Check for odd, by computing the modulo 2 of the #. 
    if ((current % 2) != 0) { 
     // stop, there is an odd value. 
     return true; 
    } 
    } 
    // checked all the values... none are odd. 
    return false; 
}