排序有错望指教

qq_44691584 2019-10-11 05:52:19
import java.util.*; public class MAIN { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int array[]= new int[n]; for(int i=0;i<n;i++) { array[i]=sc.nextInt(); } MyArrays.printArray(array);//显示数组的内容 MyArrays.sortArray(array); //对数组元素排序 MyArrays.printArray(array);//显示排序后的结果 int sum=MyArrays.sumOfArray(array);//数组元素求和 System.out.println(sum);//显示数组元素的和 } } class MyArrays{ static void printArray(int[] a) { for(int i = 0; i < a.length; i++) { if(i < a.length - 1) System.out.printf("%d,",a[i]); else System.out.printf("%d\n",a[i]); } } static void sortArray(int[] a) { int t = 0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length - i - 1; j++) { if (a[j] > a[j+1]) t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } static int sumOfArray(int[] a) { int sum = 0; for(int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } }
...全文
38 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

static void sortArray(int[] a) {
int t = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
//请把{}写上!!!如果不写if只算第一句完整代码
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}

建议写代码时不要使用这种省略方式,知道有这种方式就行,这是用来装比的,真正工作时,这种能省略方式就算只有一行代码也要写上{},一、方便阅读,二、减少出错率。这是一个代码规范态度。

51,409

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧