Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to put char in setter in Java

I’m trying to make a Calculator, so I have this Calculator.java and CalculatorTest.java using setters and getters.

public class Calculator {
  
    private int a;
  
    public int getA() {
      return a;
    }
    
    public void setA(int calcOneA) {
       this.a = calcOneA;
    }
  
    private int b;
    
    public int getB() {
      return b;
    }
    
    public void setB(int calcOneB) {
       this.b = calcOneB;
    }
        
    private char sign;
  
    public char getSign() {
      return sign;
    }
    
    public void setSign(char calcOneSign) {
        this.sign = calcOneSign;     
    }
}
import java.util.Scanner;

public class CalculatorTest {

    public static void main(String[] args) {
        Calculator calcOne = new Calculator();
        Scanner scanner = new Scanner(System.in);
        System.out.println("Введите первое число");
        calcOne.setA(scanner.nextInt());
        System.out.println("Введите знак математической операции");
        calcOne.setSign(nextLine());
        System.out.println("Введите второе число");
        calcOne.setB(scanner.nextInt());
      }
}

I don’t know how to put math sign into calcOne.setSign(). I tried nextLine() but it says can’t find symbol.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your problem isn’t the setter.

For example, you can call calcOne.setSign('a'); on its own.

Now, to reproduce that for user input, you need to fix your scanner usage, for example

calcOne.setSign(scanner.nextLine().charAt(0));

However, if you’re typing something like 2 + 2, the + is called the operator, and it’s not always a specific index within the string (if you type this on its own line, it might be okay)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading