ใช้ GUI คำนวณหาเกรด ในภาษา Java
ตัวอย่างแรกแบบง่าย ๆ ก่อน คิด 3 เกรด นศ. 3 คน
81 – 100 เกรด A
51 – 80 เกรด B
0 – 50 เกรด C
import javax.swing.JOptionPane;
public class Test1
{
public static void main( String args[] )
{
String a, m="";
int b=0;
char grade;
for(int i = 0; i < 3; i++){
m = String.format("Enter Student #%d's Score ?:",i+1 );
a = JOptionPane.showInputDialog( m);
b = Integer.parseInt(a) ;
if (b>80)
grade = 'A';
else if (b>50)
grade = 'B';
else
grade = 'C';
m = String.format("Student #%d's Score = %d Grade = %c",
i+1,b,grade );
JOptionPane.showMessageDialog( null, m );
} //end for
} // end main
} // end class
มาเปลี่ยนการหาเกรดเป็นแบบ static method ตามตัวอย่างต่อไป
import javax.swing.JOptionPane;
import java.io.*;
public class test1
{
public static void main( String args[] )
{
String m="";
String a;
int b=0;
for(int i = 0;i<3;i++){
m = String.format("Enter Student #%d's Score ?:",i+1 );
a = JOptionPane.showInputDialog( m);
b = Integer.parseInt(a) ;
m = String.format("Student #%d's Score = %d Grade = %c",
i+1,b,findGrade(b) );
JOptionPane.showMessageDialog( null, m );
}
} // end main
static char findGrade(int b)
{
char grade;
if (b>80)
grade = 'A';
else if (b>50)
grade = 'B';
else
grade = 'C';
return grade;
}
} // end class
ตัวอย่าง 2 ตัวอย่างแรกเป็นตัวอย่างง่าย ๆ ยังไม่มีการตรวจสอบการป้อนคะแนน มาดูตัวอย่างแบบตรวจสอบช่วงคะแนน
import javax.swing.JOptionPane;
import java.io.*;
public class Test1
{
public static void main( String args[] ) throws NumberFormatException, IOException
{
String m="";
String a;
int b=0, i = 0;
do {
m = String.format("Enter Student #%d's Score ?:",i+1 );
a = JOptionPane.showInputDialog( m);
try {
b=Integer.parseInt(a) ;
}// end try
catch (Exception e){
JOptionPane.showMessageDialog( null,
"Error number only!");
continue;
} //end catch
if (b < 0||b > 100)
JOptionPane.showMessageDialog( null,
"Error out of range!" );
else {
m = String.format("Student #%d's Score = %d Grade = %c",
i+1,b,findGrade(b) );
JOptionPane.showMessageDialog( null, m );
i++;
}// end else
}while (i< 3);
} // end main
static char findGrade(int b)
{
char grade;
if (b>80)
grade = 'A';
else if (b>50)
grade = 'B';
else
grade = 'C';
return grade;
}
} // end class
ลองไปเขียนโดยใช้ข้อมูลแบบแถว (Array)