英文:
Trying to build a basic calculator using multiple classes
问题
我正在尝试使用多个类,而不是在主类中包含整个计算器的全部内容。我计划使用switch语句,但在尝试将用户输入与您选择的操作结合时,我遇到了困难。
- ApplesUserInput.java
package applesuserinput;
import java.util.Scanner;
public class ApplesUserInput {
public static void main(String args[]){
calculator c1 = new calculator();
System.out.println("Hello! Welcome to my Calculator.");
System.out.print("You may add (A), subtract (S), multiply (M) or divide (D) two different numbers. Please select one of the letters for your desired operation: ");
calculator.geta();
}
}
- calculator.java
package applesuserinput;
import java.util.Scanner;
public class calculator {
public static void geta(){
Scanner scan = new Scanner(System.in);
String a;
a = scan.nextLine();
}
}
到目前为止,它可以成功编译和运行,但是我无法让switch语句识别来自geta()的字符串。所以我现在被困在这里。
英文:
I am trying to use multiple classes not to bulk the whole entirety of the calculator in the main class. I was planning to use switch but I have been stuck on trying to combine User Input when it comes to your choice of operation.
- ApplesUserInput.java
package applesuserinput;
import java.util.Scanner;
public class ApplesUserInput {
public static void main(String args[]){
calculator c1 = new calculator();
System.out.println("Hello! Welcome to my Calculator.");
System.out.print("You may add (A), subtract (S), multiply (M) or divide (D) two different numbers. Please select one of the letters for your desired operation: ");
calculator.geta();
}
}
- calculator.java
package applesuserinput;
import java.util.Scanner;
public class calculator {
public static void geta(){
Scanner scan = new Scanner(System.in);
String a;
a = scan.nextLine();
}
}
So far it compiles and runs well but I cannot get the switch statement to recognize the a String from my geta(). So I'm pretty much stuck here right now.
答案1
得分: 0
你的 geta() 方法没有返回任何内容,也没有将结果赋值给任何变量。
应该是:
public static String geta(){
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
return a;
}
在 ApplesUserInput.java 中应该是:
String a = calculator.geta();
英文:
Your geta() method isn't returning anything, nor have you assigned the result to anything.
It should be:
public static String geta(){
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
return a;
}
And in ApplesUserInput.java, it should be:
String a = calculator.geta();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论