尝试使用多个类构建基本计算器。

huangapple go评论68阅读模式
英文:

Trying to build a basic calculator using multiple classes

问题

我正在尝试使用多个类,而不是在主类中包含整个计算器的全部内容。我计划使用switch语句,但在尝试将用户输入与您选择的操作结合时,我遇到了困难。

  1. 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();
  
    }
    
}
  1. 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.

  1. 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();
  
    }
    
}
  1. 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();

huangapple
  • 本文由 发表于 2020年9月12日 05:20:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63854441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定