我有两个Java类,一个包含getter和setter,另一个是驱动程序类。我需要来自驱动程序类中扫描程序的用户输入才能属于第一类中的getter。用户输入必须为double,因为它将用作getter中的公式。
//First Class public class shopping { String orangeSelected; public double getOrangeSelected() { return (user input makes a formula to be returned to the driver class) } public void setOrangeSelected(String orangeSelected) { this.orangeSelected = orangeSelected; } } //Driver Class import java.util.Scanner public class shoppingApp { public static void main(String[] args) { Scanner inputOrangeSelected = new Scanner(System.in) System.out.println("Premium Oranges"); String orangeSelected = inputOrangeSelected.nextLine(); } }
真正最好的是将所有内容都放在一个类中,没有理由将一个类分成两个类,只是为了使获取器和设置器与其他类分开,这 没有任何意义 。我确实想知道您是否误解了您的作业。
import java.util.Scanner; class shoppingApp { //since it's an instance field not local to the class it's declared here instead of main static String orangeSelected = ""; public static void main(String[] args) { //orange selected is an odd name for a scanner, just use scan or something similar Scanner scan = new Scanner(System.in); //note that you were missing a semicolon System.out.println("Premium Oranges\n"); //include a new line or a space before asking for input, for example with \n orangeSelected = scan.nextLine(); } //setter public static void setOrangeSelected(String str) { orangeSelected = str; } //getter public static String getOrangeSelected() { return orangeSelected; } //Note that all methods and instance fields are static because the main method must be static if you don't understand this yet that's ok. }
现在,如果出于某种原因您绝对 必须 使用两个类,则它看起来应该像这样,尽管我会注意到,只是在不理解的情况下复制和粘贴我的代码将是 作弊行为 。
import java.util.Scanner; class shoppingApp { //normally this shouldn't be public public static String orangeSelected = ""; public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Premium Oranges\n"); orangeSelected = scan.nextLine(); } } class gettersAndSetters { //setter public void setOrangeSelected(String str) { Main.orangeSelected = str; } //getter public String getOrangeSelected() { return Main.orangeSelected; } }