2014-09-06 3 views
0

사용자가 음수 또는 양수일 수 있고 소수점 이하 자릿수를 포함 할 수있는 두 개의 숫자를 입력하는 프로그램을 작성해야합니다. 이론적으로 말하면, "256.78 + 78.6783"이라고 말하면 정상적인 추가 문제와 같이 처리하고 작업을 끝내야합니다.Java에서 문자열 번호 추가 및 빼기

양성인 경우에만 길이를 추가하는 방법을 알아 냈지만 음수를 추가하거나 숫자를 빼면 올바른 결과를 얻지 못합니다. 이것은 사용자가 입력하는 두 개의 숫자 세트로 작업해야합니다.

여기 내 코드는 무엇입니까?
P. 이 번호를 조작하기 전에 int 또는 double으로 변환 할 수 없으므로 구문 분석 할 수 없습니다.

public class Number { 
    static Scanner kbd = new Scanner (System.in); 
    private String sign; 
    private String whole; 
    private String decimal; 
    private String fraction; 
    private static double firstNumber; 
    private static double secondNumber; 

    public static void main(String[] args) { 

     System.out.println("Please enter the first number: "); 
     firstNumber = kbd.nextDouble(); 
     System.out.println("Next, enter the second number: "); 
     secondNumber = kbd.nextDouble(); 

     Number x = new Number (firstNumber); 
     Number y = new Number (secondNumber); 
     Number sum = x.add(y); 
     System.out.println("x = " + x); 
     System.out.println("y = " + y); 
     System.out.println("x + y = " + sum); 
     Number subtract = x.subtract(y); 
     System.out.println("x - y = " + subtract); 
    } 
    public Number() 
    { 
     whole = "0"; 
     decimal = "0"; 
     sign = "+"; 
    } 
    public String toString() 
    { 
     return sign + whole + "." + decimal; 
    } 
    public Number (double n) 
    { 
     whole = "0"; 
     decimal = "0"; 
     sign = "+"; 

     String numString = new Double(n).toString(); 
     if (numString.charAt(0) == '-') { 
      sign ="-"; 
      numString = numString.substring(1); 
     } 
     int position = numString.indexOf("."); 
     if (position == -1) 
      whole = numString; 
     else 
     { 
      whole = numString.substring(0,position); 
      decimal = numString.substring(position+1); 
      fraction = ""; 
     } 
    } 

    public Number add (Number RHS) { 
     this.fixWhole (RHS); 
     this.fixDecimal(RHS); 
     return this.addNum (RHS); 
    } 
    public Number subtract (Number RHS) { 
     this.fixWhole(RHS); 
     this.fixDecimal(RHS); 
     return this.subtractNum (RHS); 
    } 
    private void fixWhole (Number RHS) { 
     int firstWholeNum = this.whole.length(); 
     int secondWholeNum = RHS.whole.length(); 
     int difference = firstWholeNum - secondWholeNum; 
     if (difference > 0) { 
      for (int i = 1; i <= difference; i++) 
       RHS.whole = "0" + RHS.whole; 
     } 
     else if (difference < 0) { 
      difference = Math.abs(difference); 
      for (int i = 1; i <= difference; i++) 
       this.whole = "0" + this.whole; 
     } 
    } 

    private void fixDecimal (Number RHS) { 
     int firstDecimalNum = this.decimal.length(); 
     int secondDecimalNum = RHS.decimal.length(); 
     int difference = firstDecimalNum - secondDecimalNum; 

     if (difference > 0) { 
      for (int i = 1; i <= difference; i++) 
       RHS.decimal = RHS.decimal + "0"; 
     } 
     else if (difference < 0) 
     { 
      difference = Math.abs(difference); 
      for (int i = 1; i <= difference; i ++) 
       this.decimal = this.decimal + "0"; 
     } 
    } 

    private Number addNum (Number RHS) { 
     Number sum = new Number(); 
     sum.decimal = ""; 
     int carry = 0; 
     int decimalNum = this.decimal.length(); 
     for (int i = decimalNum - 1; i >= 0; i --) { 
      char c1 = this.decimal.charAt(i); 
      char c2 = RHS.decimal.charAt(i); 
      int tempSum= (c1 - 48) + (c2 - 48) + carry; 
      carry = tempSum/ 10; 
      int sumDigit = tempSum % 10; 
      sum.decimal = (char) (sumDigit + 48) + sum.decimal; 
     } 
     sum.whole = ""; 
     int wholeNum = this.whole.length(); 
     for (int i = wholeNum - 1; i >= 0; i --) { 
      char c1 = this.whole.charAt(i); 
      char c2 = RHS.whole.charAt(i); 
      int tempSum = (c1 - 48) + (c2 - 48) + carry; 
      carry = tempSum/10; 
      int sumDigit = tempSum % 10; 
      sum.whole = (char) (sumDigit + 48) + sum.whole; 
     } 
     if (carry != 0) 
      sum.whole = "1" + sum.whole; 
     return sum; 
    } 

    private Number subtractNum (Number RHS) { 
     Number sum = new Number(); 
     sum.decimal = ""; 
     int carry = 0; 
     int decimalNum = this.decimal.length(); 
     for (int i = decimalNum - 1; i >= 0; i --) { 
      char c1 = this.decimal.charAt(i); 
      char c2 = RHS.decimal.charAt(i); 
      int tempSum= (c1 - 48) - (c2 - 48) - carry; 
      carry = tempSum/ 10; 
      int sumDigit = tempSum % 10; 
      sum.decimal = (char) (sumDigit - 48) + sum.decimal; 
     } 
     sum.whole = ""; 
     int wholeNum = this.whole.length(); 
     for (int i = wholeNum - 1; i >= 0; i --) { 
      char c1 = this.whole.charAt(i); 
      char c2 = RHS.whole.charAt(i); 
      int tempSum = (c1 - 48) - (c2 - 48) + carry; 
      carry = tempSum/10; 
      int sumDigit = tempSum % 10; 
      sum.whole = (char) (sumDigit + 48) + sum.whole; 
     } 
     if (carry != 0) 
      sum.whole = "1" + sum.whole; 
     return sum; 
    } 
} 
+0

임 확실하지처럼 방법을 해당 숫자 객체로 부호 문자열로 표시를 저장하고 호출합니다. 당신은 현재의 접근법에서 이미 숫자를 파싱하고 있음에도 불구하고 문자열을 어떤 방식 으로든 또는 다른 방식으로 파싱해야합니다. – for3st

+0

@ for3st : 전적으로 사실이 아닙니다. 궁극적으로, 예, * 일부 포인트에서 문자열 입력을 '숫자'로 변환해야합니다 (추가/삭제해야하기 때문에). 그러나 OP의 임무는 한 번에 한 캐릭터 씩 그렇게하는 것이 분명합니다. 부유물로의 도매 전환의 경우는 그렇지 않습니다. 이 과제의 목적은 처음부터 BigNum 기능을 설계하는 것으로 보인다. – usr2564301

+0

'(char) (sumDigit - 48) + sum.decimal;'은'+':'sumDigit + 48'으로 더 잘 작동합니다. (명확성을 위해'sumDigit + '0'을 할 수도있다). 또한 당신은 빼기 _in english_ (자바가 아닌)의 알고리즘을 제공 할 수 있습니까? 빼기 구현에 분명히 잘못된 것이 있습니다. – Volune

답변

2

모두에게 문자열로 숫자를 가지고 당신이 그들을 구문 분석 어차피 당신이 무슨 뜻인지

System.out.println("Please enter the first number: "); 
     firstNumber = kbd.nextString(); 
     System.out.println("Next, enter the second number: "); 
     secondNumber = kbd.nextString(); 

     Number x = new Number (firstNumber.substring(1),firstNumber.charAt(0)); 
     Number y = new Number (secondNumber.substring(1),secondNumber.charAt(0)); 

/*convert the firstNumber.substring(1) and secondNumber.substring(1) to doubles using Double.parseDouble()*/ 

public String doTheOperation(Number other){ 
if(this.sign.equals(otherNumber.sign)){ 
    /*simply the double values and put the sign*/ in front of it and return it 
} 

else{ 
    do the simple double subtraction and by looking at your code i believe you can find out the bigger double among them 
} 
} 
+0

안녕하세요, 구문 분석을 사용하여 작업을 수행하지 않아도됩니다. 할당은 문자로 산술 문자를 수행하는 것입니다. 또한, 사용자가 음수를 입력하면 음수에 대한 연산을 수행하는 메소드를 호출하는 입력 확인을 의미합니까? – Rocketsm46

+0

당신은 어느 숫자가 더 크고 더 작은 지 알아낼 수 있습니까? 만약 내가 당신에게 논리를 말할 것입니다.하지만 먼저 말해 줄 수 있습니다. 당신이 더 큰 것을 발견 할 수 있다면 그 답을 말할 수 있습니다. 그래서 표지판이 다른 경우 더 큰 하나의 작은 것을 뺍니다. – saching

+0

실제로, 그럴 필요가 없습니다. 어쩌면 루프를 가지고 뭔가 할거야? 난 정말 붙어있어, 어떤 도움을 크게 주시면 감사하겠습니다! – Rocketsm46