java 当我运行我的代码时,变量仍然具有它们在开始时给定的值,我做错了什么?

kuuvgm7e  于 2023-11-15  发布在  Java
关注(0)|答案(3)|浏览(120)
  1. import java.util.Scanner;
  2. class Product{
  3. //Class attributes
  4. private String name;
  5. private double price;
  6. private int score;
  7. public Product() {
  8. name = "";
  9. score = 0;
  10. price = 1;
  11. }
  12. public void printData(){
  13. System.out.println("Name: " + name);
  14. System.out.println("Price: " + price);
  15. System.out.println("Score: " + score);
  16. }
  17. public void read() {
  18. Scanner in = new Scanner(System.in);
  19. System.out.println("Product name: ");
  20. String name = in.nextLine();
  21. System.out.println("Price: ");
  22. double price = in.nextDouble();
  23. System.out.println("Score: ");
  24. int core = in.nextInt();
  25. }
  26. public boolean is_better_than(Product other) {
  27. if (score/price > other.score/other.price)
  28. return true;
  29. return false;
  30. }
  31. }
  32. public class Main {
  33. public static void main(String[] args) {
  34. Scanner in = new Scanner(System.in);
  35. Product best = new Product();
  36. boolean more = true;
  37. while(more) {
  38. Product current = new Product();
  39. current.read(); //
  40. if (current.is_better_than(best)) {
  41. best = current;
  42. }
  43. System.out.println("More Products? 1:YES, 2:NO");
  44. int answer = in.nextInt();
  45. if (answer != 1)
  46. more = false;
  47. in.nextLine();
  48. }
  49. best.printData();
  50. }
  51. }

字符集
当我输入一个名字,一个分数和一个价格,它显示什么价格的变量被赋予在begining的programm,而不是新的

a1o7rhls

a1o7rhls1#

在read方法中,你已经为name price和core创建了局部变量。你阅读这些局部变量,而不是你的类的成员变量(字段)。
而不是

  1. String name = in.nextLine();
  2. double price = in.nextDouble();
  3. int core = in.nextInt();

字符集
你应该做

  1. this.name = in.nextLine();
  2. this.price = in.nextDouble();
  3. this.core = in.nextInt();

hts6caw3

hts6caw32#

您已经声明了新的 local 变量来存储输入数据,而不是将其赋值给示例变量。

  1. public void read() {
  2. Scanner in = new Scanner(System.in);
  3. System.out.println("Product name: ");
  4. name = in.nextLine();
  5. System.out.println("Price: ");
  6. price = in.nextDouble();
  7. System.out.println("Score: ");
  8. core = in.nextInt();
  9. }

字符集

vc6uscn9

vc6uscn93#

  • ".当我键入一个名字,一个分数和价格它显示什么价格的变量在begining的programm而不是新的."*

你不必在 read 方法中重新声明这些值。

  1. public void read() {
  2. Scanner in = new Scanner(System.in);
  3. System.out.println("Product name: ");
  4. name = in.nextLine();
  5. System.out.println("Price: ");
  6. price = in.nextDouble();
  7. System.out.println("Score: ");
  8. score = in.nextInt();
  9. }

字符集
输出

  1. Product name:
  2. abc
  3. Price:
  4. 1.23
  5. Score:
  6. 123
  7. More Products? 1:YES, 2:NO
  8. 2
  9. Name: abc
  10. Price: 1.23
  11. Score: 123

展开查看全部

相关问题