我在我的java項目中有兩個對象,我想從每個對象中取一個字段(例如,假設我們有兩個酒店房間,在其他字段中他們也有一個字段「價格」)並將em放在方法中並返回一個變量(在前面的例子中,我們假設這兩個房間的差異)。我的主要問題是在創建方法之後,你如何在主類中調用它? 我做了一個嘗試(下面的代碼),但我知道這是不正確的。所以如果你能給我一個關於如何做到或接近它的建議將是非常有用的。如何獲得java中的兩個對象字段之間的區別
difference = priceDifference(roomA.price, roomB.price);
全碼 主類
package project1;
import java.util.Scanner;
public class TestRoom {
public static void main(String[] args) {
String roomNumber, category, view;
int numberOfBeds;
double price;
double difference;
Room roomA = new Room("C101",2,"Standard","Sea",95.89);
Scanner sc = new Scanner(System.in);
System.out.println("Give room number \n");
roomNumber=sc.next();
System.out.println("Give number of beds \n");
numberOfBeds=sc.nextInt();
System.out.println("Give category \n");
category=sc.next();
System.out.println("Give view \n");
view=sc.next();
System.out.println("Give price \n");
price=sc.nextDouble();
Room roomB = new Room(roomNumber, numberOfBeds, category, view, price);
System.out.println(roomA.toString());
System.out.println(roomB.toString());
difference = priceDifference(roomA.getprice(), roomB.getprice());
}
}
教室
package project1;
public class Room {
public String roomNumber;
public int numberOfBeds;
private String category;
private String view;
private double price;
public Room(String roomNumber, int numberOfBeds, String category, String view, double price){
this.roomNumber = roomNumber;
this.numberOfBeds = numberOfBeds;
this.category = category;
this.view = view;
this.price = price;
}
public void setroomNumber(String roomnumber){
this.roomNumber = roomnumber;
}
public String getroomNumber(){
return this.roomNumber;
}
public void setnumberOfBeds(int numberofbeds){
this.numberOfBeds = numberofbeds;
}
public int getnumberOfBeds(){
return this.numberOfBeds;
}
public void setcategory(String category){
this.category = category;
}
public String getcategory(){
return this.category;
}
public void setview(String view){
this.view = view;
}
public String getview(){
return this.view;
}
public void setprice(double price){
this.price = price;
}
public double getprice(){
return this.price;
}
public double priceDifference(double double1 ,double double2){
double difference = 0;
difference = double1 - double2;
return difference;
}
@Override
public String toString() {
return "Room number:" + this.roomNumber + ",\n "
+ "Number of beds:" + this.numberOfBeds + ",\n " + "Category:"
+ this.category + ",\n " + "View:" + this.view + ",\n " + "Price:" + this.price;
}
}
以及這是priceDifference方法(這是在類「房間」,有setter和getter的構造函數房間),但我得到的錯誤「此方法是未定義的類型TestRoom(主) public double getpriceDifference(雙double1,雙double2){ \t \t \t 雙\t差= 0; \t差= double1 - double2; \t \t回差; \t} –
@sotosbic,您在拼寫方法相同的方式,當你在你def時調用它它呢?在你的代碼中,你寫了「getpriceDifference(...」在你的問題中你寫的只是「priceDifference(...」 – RaceYouAnytime
以及它說的使用PUBLIC方法double getpriceDifference(double1,double2)之間的價格。我認爲這個價格差是方法的名稱,並得到就像這個方法的getter(我是初學者在Java中,所以我不舒服,但與Java) –