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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 我一定要得到你 中级黑马   /  2016-3-2 14:21  /  799 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在视频中看到老师的讲解,如果想把return -1 改成String类型的语句,如:"越界了哦!!!",应该如何做呢?
class Demo3_Array {
    public static void main(String[] args) {
        
        int[] arr = {11,22,33,44,55};
        System.out.println(getIndex(arr,66));
        
        
    }
<
    public static int getIndex(int[] arr,int value){
        for(int i=0;i<arr.length;i++){
            if(arr[i] == value){
                return i;
            }
        }

        return -1;
        
    }
}
>

4 个回复

倒序浏览
因为是int类型的返回值,所以改进办法为void
改进一下就好

  1. class Demo3_Array {
  2.     public static void main(String[] args) {
  3.         
  4.         int[] arr = {11,22,33,44,55};
  5.         getIndex(arr,66);
  6.         
  7.         
  8.     }
  9.     public static void getIndex(int[] arr,int value){
  10.         for(int i=0;i<arr.length;i++){
  11.             if(arr[i] == value){
  12.                 System.out.println("索引值为:"+i);
  13.             }
  14.         }

  15.         System.out.println("越界了哦!!!");
  16.         
  17.     }
  18. }
复制代码
回复 使用道具 举报
楼上你不感觉,每次循环结束后都会打印“越界了哦”
回复 使用道具 举报 1 0
如果纯粹想达到你说的目的,下面的代码能够实现
  1. public class Test_3 {
  2.             public static void main(String[] args) {
  3.                 
  4.                 int[] arr = {11,22,33,44,55};
  5.                 getIndex(arr,66);
  6.                 
  7.                 
  8.             }
  9.             public static void getIndex(int[] arr,int value){
  10.                     int count =0;
  11.                 for(int i=0;i<arr.length;i++){
  12.                     if(arr[i] == value){
  13.                             count++;
  14.                         System.out.println("索引值为:"+i);
  15.                     }
  16.                 }
  17.                 if (count==0) {
  18.                          System.out.println("越界了哦!!!");       
  19.                         }
  20.             }
  21.         }
复制代码
回复 使用道具 举报 2 0
感谢大家为我解答难题!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马