A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 381890216 中级黑马   /  2015-9-30 17:50  /  535 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

遍历查找,对于数组内有重复元素的,
如果用程序一的写法:
  1. //遍历查找,程序一
  2. public class Day05{
  3. public static void main(String[] args){
  4.   int[] i = {3,1,4,3,5,2,3,4};
  5.   for (int x=0; x<i.length; x++){
  6.    if(i[x]==4)
  7.     System.out.println(x);
  8.   }
  9. }
  10. }
复制代码
输出
2
7

但是用第二种写法:
  1. //遍历查找,程序二
  2. public class Day05{
  3.         public static void main(String[] args){
  4.                 int[] i = {3,1,4,3,5,2,3,4};
  5.                 int i1 = getIndex(i,4);
  6.                 System.out.println(i1);
  7.         }
  8.         static int getIndex(int[] arr, int key){
  9.                 for (int x=0; x<arr.length; x++){
  10.                         if (arr[x] == key)
  11.                                 return x;
  12.                 }
  13.                 return -1;
  14.         }
  15. }
复制代码

因为只能return一个结果,所以只能输出2,
有没有办法让程序二也输出2 7?


7 个回复

倒序浏览
谢谢分享
回复 使用道具 举报
  1. class  {
  2.         public static void main(String[] args) {
  3.                 System.out.println("Hello World!");
  4.         }
  5. }
  6. public class Day05{
  7.         public static void main(String[] args){
  8.                 int[] i = {3,1,4,3,5,2,3,4};
  9.                 int i1 = getIndex(i,4);
  10.                 System.out.println(i1);
  11.         }
  12.         static int[] getIndex(int[] arr, int key){
  13.                 int []temp=new int[arr.length];
  14.                                 int count=0;
  15.                                 for (int x=0; x<arr.length; x++){
  16.                         if (arr[x] == key)
  17.                                                         temp[count++]=arr[x];
  18.                                                
  19.                 }
  20.                 return temp;
  21.                                 //如果这里想打印出来就把返回值写void,再遍历数组就可以了.
  22.                                 //或者在main里定义个数组接收再自己遍历
  23.         }
  24. }
复制代码

你要返回的是int 那你又想返回2个值 ( 方法只能有一个返回值的),所以只能存在数组里打出来了.菜鸟一枚,个人理解不对请指出
回复 使用道具 举报
顶。。。。。。实用
回复 使用道具 举报
我觉得需要定义一个集合,没找到一个index就添加到集合里一次,最后返回集合,但是getIndex的返回值就不能写int啦。不知道你学完集合部分了没,我也是菜鸟,这只是我的猜想……
回复 使用道具 举报
lostyou 发表于 2015-9-30 18:25
你要返回的是int 那你又想返回2个值 ( 方法只能有一个返回值的),所以只能存在数组里打出来了.菜鸟一枚,个 ...

后来问了朋友,说如果只用return貌似无解,最好直接在方法里输出或像你写的,用数组存起来。。。。。学习了
回复 使用道具 举报
没有办法。除非使用对象,或者集合。
回复 使用道具 举报
第一个求的是 元素4的重复求值吧,  第二个是先定义的getIndex ,然后直接求数组内的值。 不过看了下面的面向对象的创建使用,积累经验了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马