java数组插入后报错,算法问题?
用java写,一个数组,排序后,插入一个数字,得到新的数组,代码运行出来不对,不知道是哪里的问题,请大神指导,非常感谢!!我没什么分数,只能献出20以表感谢-----来自...
用java写,一个数组,排序后,插入一个数字,得到新的数组,代码运行出来不对,不知道是哪里的问题,请大神指导,非常感谢!!我没什么 分数,只能献出20以表感谢
-----来自java新人菜鸟
package com.hdu.java02;
import java.util.Arrays;
import java.util.Scanner;
public class java0112 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] score={12,45,36,78,6,20};
Arrays.sort(score);
for (int i = 0; i < score.length; i++) {
System.out.print(score[i]+"\t");
}
System.out.println();
int[] new_score=new int[score.length+1];
System.out.println("请输入一个数");
int num =input.nextInt();
int index=-1;
for (int i = 0; i < score.length; i++) {
if (num<=score[i]) {
index=i;
break;
}
}
if (index>-1) {
for (int i = 0; i < index; i++) {
new_score[i]= score[i];
}
new_score[index]=num;
for (int i = index; i < score.length; i++) {
new_score[i+1]=score[i];
}
}
else{
for (int i = 0; i < score.length; i++) {
new_score[i]=score[i];
}
new_score[score.length]=num;
}
System.out.println("-------------新数组-------------");
for (int i = 0; i < new_score.length; i++) {
System.out.print(new_score+"\t");
}
}
} 展开
-----来自java新人菜鸟
package com.hdu.java02;
import java.util.Arrays;
import java.util.Scanner;
public class java0112 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] score={12,45,36,78,6,20};
Arrays.sort(score);
for (int i = 0; i < score.length; i++) {
System.out.print(score[i]+"\t");
}
System.out.println();
int[] new_score=new int[score.length+1];
System.out.println("请输入一个数");
int num =input.nextInt();
int index=-1;
for (int i = 0; i < score.length; i++) {
if (num<=score[i]) {
index=i;
break;
}
}
if (index>-1) {
for (int i = 0; i < index; i++) {
new_score[i]= score[i];
}
new_score[index]=num;
for (int i = index; i < score.length; i++) {
new_score[i+1]=score[i];
}
}
else{
for (int i = 0; i < score.length; i++) {
new_score[i]=score[i];
}
new_score[score.length]=num;
}
System.out.println("-------------新数组-------------");
for (int i = 0; i < new_score.length; i++) {
System.out.print(new_score+"\t");
}
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询