可以幫我解這兩個JAVA程式嗎??謝謝!!

2009-04-14 3:38 am
1. Write a Java class that represents a Student with String-type instance variables name and id. In addition, please define at least 2 constructors, 2 accessor methods and 2 mutator methods for the class. Write a simple main program to create a Student object.



2.Write a complete Java program that uses a "for loop" to compute the sum of the even numbers and the sum of the odd numbers between 1 and 25.

可以幫我解這兩個JAVA程式(一些會運用到的概念或方法)??
謝謝!!

回答 (2)

2009-04-14 8:03 am
✔ 最佳答案
for 1:
class Student
{
private String name="";
private String id="0";

public Student(String n, String i)
{
name = n;
id = i;
}

public Student()
{
}

public String getName()
{
return name;
}

public String getId()
{
return id;
}

public void changeName(String n)
{
name = n;
}

public void changeId(String i)
{
id = i;
}


public static void main(String[] agrs)
{
Student obj = new Student();

obj.changeName("abc");
obj.changeId("01234");
System.out.println(obj.getName());
System.out.println(obj.getId());
}
}

For 2:
public class Test
{
public static void main(String[] args)
{
int i;
int osum,esum;

for (osum=0,esum=0,i=25; i != 0; i--) {
if ( i % 2 != 0 ) {
osum += i;
} else {
esum += i;
}
}
System.out.println("sum of odd numbers is " + osum);
System.out.println("sum of even numbers is " + esum);
}
}



2009-04-14 2:35 pm
2.
int oddsum=0,evensum=0;
for(int i=0;i<=25;i++){
if(i%2==0)
evensum+=i;
else
oddsum+=i;
}
這是一個不好的程式片段,只是比較符合你要的
寫成2個迴圈(for loop)會比較好

1.
class Student{
private String name;
private String id;
Student(){
}
Student(String name,String id){
this.name=name;
this.id=id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setID(String id){
this.id=id;
}
public String getID(){
return id;
}
}


收錄日期: 2021-04-30 12:55:24
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090413000016KK08291

檢視 Wayback Machine 備份