2.将老数组的内容copy到新数组中
3.给新数组的最后一个元素赋值为 插入的字符串
4.删除老数组,(GC处理)
5,给你个例子,你看看
import java.util.Arrays
public class $
{
public static void main(String[] args)
{
String[] arr = { "1", "2" }
System.out.println(Arrays.deepToString(arr))
arr = insert(arr, "a")
System.out.println(Arrays.deepToString(arr))
arr = insert(arr, "b")
System.out.println(Arrays.deepToString(arr))
}
private static String[] insert(String[] arr, String str)
{
int size = arr.length
String[] tmp = new String[size + 1]
System.arraycopy(arr, 0, tmp, 0, size)
tmp[size] = str
return tmp
}
}
结果
[1, 2]
[1, 2, a]
[1, 2, a, b]
import java.util.Scanner
import java.util.InputMismatchException
public class saveInputToArr {
public static void main(String[] args) {
Scanner scan = null
try {
scan = new Scanner(System.in)
System.out.print( "请输入个数: " )
int inputNum = scan.nextInt()
if( inputNum <= 0 ) {
throw new Exception( "输入有误" )
}
System.out.println( "请输入数字: " )
int arr[] = new int[inputNum]
int num = 0
int count = 0
while( count <inputNum ) {
num = scan.nextInt()
arr[count] = num
count++
}
for( int i = 0i <arr.lengthi++ ) {
System.out.print( arr[i] + " " )
}
} catch ( Exception e ) {
throw new InputMismatchException( "\u8f93\u5165\u6709\u8bef\u002c\u0020\u8bf7\u91cd\u65b0\u8f93\u5165" )
} finally {
try {
if ( scan != null ) {
scan.close()
}
} catch ( Exception e2 ) {
e2.printStackTrace()
}
}
}
}
运行结果为:
请输入个数: 2
请输入数字:99
123
99 123
扩展资料
Java从输入中读取一个数组
import java.util.Scanner
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in)
String str = sc.nextLine().toString()//用nextLine()可以读取一整行,包括了空格,next()却不能读取空格
String arr[] = str.split(" ")//拆分字符串成字符串数组
int a[] = new int[arr.length]
for(int j = 0j <a.lengthj++)
{
a[j] = Integer.parseInt(arr[j])
System.out.print(a[j] + " ")
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)