Brief talk on the simple application of arrays in Java--------------------ideas and development
Known an array, below we do three things
1. Print an array of all elements
2, the value of the and
3, ask a number is 3440 in this array exists?
1 PackageCn.happy;2 3 Public classDay03 {4 Public Static voidMain (string[] args) {5 //ctrl+f: Quick Find and replace6 int[] nums={8,4,2,1,23,344,12};7 //1. Just print8 for(inti = 0; i < nums.length; i++) {9 System.out.println (Nums[i]);Ten } OneSystem.out.println ("=============== I am the noble dividing line ======="); A intSum=0; - for(inti = 0; i < nums.length; i++) { -sum+=Nums[i]; the } -System.out.println ("and yes" +sum); - //2. Just sum up -System.out.println ("=============== I am the noble dividing line ======="); + //3. Just compare the numbers - intnum=3440; + Booleanflag=false;//The default value does not exist in the array A for(inti = 0; i < nums.length; i++) { at if(num==Nums[i]) { - //if code execute here, it proves that there is -System.out.println ("Pro, exists! "); -flag=true; - Break; - } in } - if(flag==false) { toSystem.out.println ("does not exist"); + } - } the}
1. Use for loop to cycle through all elements of the array.
2, Sum. Give a variable sum=0; with a For loop, each loop sum=sum+nums[i] This formula can also be written sum+=nums[i] out of the loop out of sum, that is, these elements and
3, Boolean flag=false;//default this value in the array does not exist, with the For loop with if to find the value is not in the value of the existence. I think the focus of this problem is to set a Boolean value, the default state of this value is not present.
Personal impressions: When I was looking for numerical values in the array, I also thought of using for and if to combine, just in the loop when I will be the state with while to represent the phenomenon of a dead loop. Sometimes it is hard to think of the answer to the question.
Brief talk on the simple application of arrays in Java--------------------ideas and development