今天上课老师讲的是各种语法,由于我们已经有了c语言的基础,所以这些对我们来说其实不是什么难事。上课上的有点快,今天主讲了一个排序的程序,就是输入三个数字进行排序,使用了if——else语句。我创建了一个包com.mxl.array,然后创建了两个的类。
package com.mxl.array;
public class Number {
void sort(int a,int b,int c) {
int count = 0;
int temp = 0;
if(b<a) {
temp = a;
a = b;
b = temp;
count++;
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
if(c<a) {
temp = a;
a = c;
c = temp;
count++;
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
if(c<b) {
temp = b;
b = c;
c = temp;
count++;
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
if(count==0) {
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
}
}
void sort(int a,int b,int c) {
int count = 0;
int temp = 0;
if(b<a) {
temp = a;
a = b;
b = temp;
count++;
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
if(c<a) {
temp = a;
a = c;
c = temp;
count++;
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
if(c<b) {
temp = b;
b = c;
c = temp;
count++;
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
if(count==0) {
System.out.println("排序的第"+count+"次操作的结果:"+a+","+b+","+c);
}
}
}
这段程序主要是讲方法,实现的过程。
package com.mxl.array;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("输入三个数,每输入一个都要回车确认!");
int x = reader.nextInt();
int y = reader.nextInt();
int z = reader.nextInt();
Number number = new Number ();
number.sort(x, y, z);
}
}这段是主函数,调用实现第一段函数。
public class Example {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("输入三个数,每输入一个都要回车确认!");
int x = reader.nextInt();
int y = reader.nextInt();
int z = reader.nextInt();
Number number = new Number ();
number.sort(x, y, z);
}
}这段是主函数,调用实现第一段函数。
我是新手,如果表达的方式不对或者说的不对,请大家多多指教!!!
本文介绍了使用Java实现的三数排序程序,通过if-else语句进行比较并交换位置,最终输出排序结果。同时提供了完整的代码示例。
371

被折叠的 条评论
为什么被折叠?



