发几个java基础程序题 及其代码【如有更简便或更加好的方法 请高人指点】
写一个读入学生成绩 并能确定分数等级的程序(以最高分-10 A,-20 B,-30 C,-40 D划分等级)代码:【如有更简便或更加好的方法 请高人指点】
import javax.swing.JOptionPane;
public class Demo01 {
public static void main(String[] args) {
String numberOfStudentString = JOptionPane.showInputDialog("请输入学生总数:");
int numberOfStudent = Integer.parseInt(numberOfStudentString);
int[]scores = new int[numberOfStudent];
int best = 0;
char grade;
for(int i = 0;i < scores.length;i++){
String scoreString = JOptionPane.showInputDialog("请输入一个分数:");
scores[i] = Integer.parseInt(scoreString);
if(scores[i] > best)
best = scores[i];
}
String output="";
for (int i=0;i < scores.length;i++){
if(scores[i]>=best-10)
grade = 'A';
else if(scores[i]>=best-20)
grade = 'B';
else if(scores[i]>=best-30)
grade = 'C';
else if(scores[i]>=best-40)
grade = 'D';
else
grade = 'F';
output += "学生 "+i+" 号 的分数是:"+scores[i]+" 成绩等级是 "+grade+"\n";
}
JOptionPane.showMessageDialog(null,output);
}
}
----------------解决方案--------------------------------------------------------
貌似用switch语句也可以
----------------解决方案--------------------------------------------------------
求最小元素的下标
用数组{1,2,4,5,10,100,2,-22}测试
代码:【如有更简便或更加好的方法 请高人指点】
public class min {
public static void main(String[] args){
int test[]={1,2,4,5,10,100,2,-22};
int min =test[0];
int index=0;
for(int i=1;i<test.length;i++){
if(test[i] < min){
min = test[i];
index = i;
}
}
System.out.println(index);
}
}
----------------解决方案--------------------------------------------------------
回复 2楼 wsckt
用swith 怎么写呢~ ----------------解决方案--------------------------------------------------------
选择排序 从小到大排序
测试数组 {2,9,5,4,8,1,6}
public class sort {
public static void main(String [] args){
int [] test = {2,9,5,4,8,1,6};
for(int i=1;i<test.length;i++){
int min = test[0];
int minIndex = 0;
for(int j = i ;j<test.length;j++){
if(test[j]<min){
min = test[j];
minIndex = j;
}
}
if(minIndex != i-1){
test[minIndex] = test[i-1];
test[i-1] = min;
System.out.print(test[i-1]+" ");
}
}
for(int i=0; i<test.length;i++){
System.out.print(test[i]);
}
}
}
}
[ 本帖最后由 古博文 于 2009-10-21 11:33 编辑 ]
----------------解决方案--------------------------------------------------------
int [] test = {2,9,5,4,8,1,6};
Arrays.sort(test);
System.out.print("升序\n");
for(int i=0;i<test.length;i++){
System.out.print(test[i]+" ");
}
----------------解决方案--------------------------------------------------------
对于我这种菜鸟来说,这些小程序是最有用的。
----------------解决方案--------------------------------------------------------