public class Book {
private String title;
private String author;
private double price;
public Book(String title,String author,double price){
this.title = title;
this.author = author;
this.price = price;
}
public String getTitle(){
return this.title;
}
public String getAuthor(){
return author;/*这个author 指的是成员变量,所以返回的是成员变量的值*/
}
public double getPrice(){
return price;
}
public static void main(String[]args){
Book book1 = new Book("<<Java 入门>>", "杨鹏" ,50);
Book book2 = new Book("<<C 入门>>","小马",2);
System.out.println("书名:" + book1.getTitle());
System.out.println("作者:" + book1.getAuthor());
System.out.println("价格:" + book1.getPrice());
System.out.println("书名:" + book2.getTitle());
System.out.println("作者:" + book2.getAuthor());
System.out.println("价格:" + book2.getPrice());
book1.price = 1;
System.out.println(book1.price);
}
}
可以使用构造方法,把对象的属性传给class.Book book1 = new Book("<<Java 入门>>", "杨鹏" ,50);
2.
import java.util.Scanner;
public class CelsiusConverter {
public double getFahrenheit(double celsius){
return 1.8 * celsius + 32;
//return fahrenheit;
}
public static void main(String[]args){
System.out.println("请输入要转换的温度(单位:摄氏度)");
Scanner input = new Scanner(System.in);
double celsiu = input.nextDouble();
CelsiusConverter converter = new CelsiusConverter();
System.out.println("转换完成的温度(单位:华氏度)" + converter.getFahrenheit(celsiu));
}
}
可以用scanner的方法去输入,在主函数里一般要打印相应的值的,一般写出相应的方法converter.getFahrenheit(celsiu),book2.getPrice()
Keine Kommentare:
Kommentar veröffentlichen