Java 输入一组数,以-1结束,并输出

r囧r小猫 2022-11-20 08:24 348阅读 0赞
  1. import java.util.Scanner; //使用输入语句必须导入此类
  2. class Test{
  3. //class类似struct,其中可以包含数据和方法
  4. int[] a; //定义数组变量,注意,并未创建数组对象。
  5. int len;
  6. void input(){
  7. //注:由于a和len定义在input之外,因此,可以直接使用。
  8. /*c语言版
  9. int x,i;
  10. scanf("&d",&x); i=0;
  11. while(x!=-1){a[i]=x; i++; scanf("%d",&x);}
  12. len=i;
  13. */
  14. int x,i; i=0;
  15. //注意1:必须先创建数组对象,才能向数组中添加数据
  16. a=new int[100];
  17. Scanner sc=new Scanner(System.in); //构造Scanner对象的固定格式,其中System.in表示标准输入设备
  18. System.out.print("请输入一组数,以-1结束:\n");
  19. x=sc.nextInt(); //scanf("&d",&x);
  20. while(x!=-1){
  21. a[i]=x; i++; x=sc.nextInt(); }
  22. len=i;
  23. }
  24. void show(){
  25. for(int i=0; i<len; i++)
  26. System.out.print(a[i]+" ");
  27. }
  28. }
  29. class App{
  30. public static void main(String[] x){
  31. Test1 t=new Test1(); //必须先造对象,然后才能调用方法
  32. t.input();
  33. t.show();
  34. }
  35. }

//本例掌握:
1、class可以包含数据,如Test中的len、数组a,这些变量在该类中可视为全局变量,即a、len可以直接在input()、show()等方法中使用;
2、数组变量必须先用new造对象,然后才能向其中填写数据。如a = new int [100]; 或 a = new int [x]; // x是变量
3、使用Scanner输入的步骤:
(1)先导入,即import java.util.Scanner;
(2)创建Scanner对象,即 Scanner sc = new Scanner(System.in);
(3)借助对象读取数据,如sc.nextInt(); // nextInt() 是Scanner类提供的方法
4、以汽车为例:
类是汽车的设计图纸,图纸不能执行;
汽车是基于图纸造出的对象,对象才能调用方法

发表评论

表情:
评论列表 (有 0 条评论,348人围观)

还没有评论,来说两句吧...

相关阅读