关于数组的返回问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | package dataManagement; import java.io.InputStream; import java.util.Scanner; public class Demo { static Scanner sc = new Scanner(System.in); //输出操作方法 public void Output(){ System.out.println( "*****************************" ); System.out.println( " 1--插入数据" ); System.out.println( " 2--显示所有数据" ); System.out.println( " 3--在指定位置插入数据" ); System.out.println( " 4--查询能被3整除的数据" ); System.out.println( " 0--退出程序" ); System.out.println( "*****************************" ); System.out.println( "请输入对应的数字进行操作:" ); } //插入数据方法 public int [] insertData(){ int [] a= new int [ 10 ]; for ( int x= 0 ;x<a.length- 1 ;x++){ System.out.println( "请输入第" +(x+ 1 )+ "个数据" ); a[x]=sc.nextInt(); } System.out.println( "数组元素为:" ); for ( int y= 0 ;y<a.length- 1 ;y++){ System.out.print(a[y]+ " " ); } return a; } //显示所有数据方法 public void showData( int [] a, int length){ System.out.println( "数组元素为:" ); for ( int x= 0 ; 0 <=length- 1 ;x++){ System.out.println(a[ 0 ]+ " " ); } } //主方法 public static void main(String[] args){ Demo Dian = new Demo(); Dian.Output(); while ( true ){ int shu = sc.nextInt(); switch (shu){ case 1 :{ Dian.insertData(); System.out.println(); Dian.Output(); break ; } case 2 :{ int [] n; n=Dian.insertData(); Dian.showData(n, 10 ); } } } } } |
为什么我在插入数据完后,再输入2进行显示所有数据,显示的是方法insertData()中的输出内容,而不是insertData()方法中返回的数组进行操作?
源自:Java方法
9-1 方法课程总结
34
收起
正在回答
2回答
在循环外定义一个数组int[] a,然后case 1后面写上a=Dian.insertData();这样case 2后面就不用再调用insertData方法了,直接调用showData方法,参数是a就行了。另外,对象的名字Dian要满足变量命名规则,所以不能首字母大写,改成dian。祝学习愉快!
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧