美文网首页Java
Conditionally return

Conditionally return

作者: JaedenKil | 来源:发表于2018-07-20 14:17 被阅读3次
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class TestReturnValues {
        public static void main(String[] args) {
            for (int i = 1; i <= 5; i ++) {
                List<Integer> randomList = new ArrayList<>();
                Random rd = new Random();
                for (int j = 1; j <= 5; j++) {
                    randomList.add(rd.nextInt(8) - 1);
                }
                Object result = allPositiveFigures(randomList);
                if (result instanceof Boolean) {
                    System.out.println("All figures are no less than zero.");
                } else if (result instanceof List) {
                    System.out.println("Some figures are not positive.");;
                } else {
                    System.out.println("Unknown return type found!!!");
                }
                System.out.println("----------------------------------");
            }
        }
        private static Object allPositiveFigures(List<Integer> list) {
            System.out.println(list);
            List<Integer> negativeFigures = new ArrayList<>();
            boolean flag = true;
            for (int i : list) {
                if (i < 0) {
                    flag = false;
                    negativeFigures.add(i);
                }
            }
            if (flag) {
                return true;
            } else {
                return negativeFigures;
            }
        }
    }
    
    [2, 5, 5, 4, 6]
    All figures are no less than zero.
    ----------------------------------
    [3, 3, 6, 0, 4]
    All figures are no less than zero.
    ----------------------------------
    [6, 4, 1, 3, 1]
    All figures are no less than zero.
    ----------------------------------
    [4, 3, 3, 1, 3]
    All figures are no less than zero.
    ----------------------------------
    [3, -1, 5, 5, 5]
    Some figures are not positive.
    ----------------------------------
    
    Process finished with exit code 0
    

    相关文章

      网友评论

        本文标题:Conditionally return

        本文链接:https://www.haomeiwen.com/subject/slzfmftx.html