你可以选择最简单的方法解题,但是你需要掌握所有的方法当做知识储备
第一种最简单,但是其适用前提是输入: 4(个数) 然后是 1 2 3 4 (也就是输入数字),放入kk数组之中,输出1 2 3 4
import java.util.*;public class Main{ public static void main(String args[]) { Scanner cn=new Scanner(System.in); int count=cn.nextInt(); int []kk=new int[count]; for(int i=0;i<count;i++) { int p=cn.nextInt(); kk[i]=p; } for(int i=0;i<kk.length;i++) System.out.PRintln(kk[i]); } }第二种:前提是输入: 4(个数 ) 然后是 1 2 3 4 (也就是输入数字),放入kk数组之中,输出1 2 3 4 ,这是另一种思路,作为学习,建议也掌握一下
import java.util.*;public class Main{ public static void main(String args[]) { Scanner cn=new Scanner(System.in); int count=cn.nextInt(); //输入个数 String str=""; //我们是将第二行输入的当做字符串来处理的 方法如下: str=cn.nextLine(); //这个的作用就是吃掉输完数字之后 再输入字符的回车,这个很重要 str=cn.nextLine(); //这个才是用来读入 1 2 3 4 这一行,不是一个一个读入的,是一行 String []k=str.split(" "); //这是用来分割str字符串的 互相分割的条件是 空格 int []kk=new int[k.length]; //这是创建放1 2 3 4的数组 for(int i=0;i<k.length;i++) kk[i]=Integer.parseInt(k[i]); //这是强制转换成int类型的 for(int i=0;i<kk.length;i++) System.out.println(kk[i]); } }第三种:前提是输入: 4(个数 ) 然后是 1 2 3 4 (也就是输入数字),放入kk数组之中,输出1 2 3 4 这次换一个思路,
import java.util.*;public class Main{ public static void main(String args[]) { Scanner cn=new Scanner(System.in); int count=cn.nextInt();//输入个数 String str=""; //我们是将第二行输入的当做字符串来处理的 方法如下: str=cn.nextLine(); //这个的作用就是吃掉输完数字之后 再输入字符的回车,这个很重要 str=cn.nextLine(); //这个才是用来读入 1 2 3 4 这一行,不是一个一个读入的,是一行 int []kk=new int[count]; int r=0; Scanner s=new Scanner(str); for(int i=0;i<str.length();i++) //遍历字符串 { while(s.hasNextInt()) //判断字符串挨个是不是数字的 { int t=s.nextInt(); //放入kk数组之中 kk[r]=t; r++; } } for(int j=0;j<kk.length;j++) System.out.println(kk[j]); } }
新闻热点
疑难解答