2014-03-02 46 views
1

我對Java比較陌生,我正在爲我的計算機編程類編寫一個程序,它將接受來自用戶的字符串(該字符串必須是類似於1 + 2 - 1的字符串)和然後取出字符串,使用分隔符來除去+/-符號,然後執行加法和減法並返回字符串輸入的總和。要做到這一點,我的程序必須運行一個while循環,並且每次找到一個整數時,它必須根據數字前面加上一個+還是 - 符號來執行相應的功能。我試圖使用.findInLine讓程序確定字符是否是+或 - 然後基於這個添加或減去後面的數字,但它似乎不工作,同時也使用分隔符,我'米堅持要做什麼。這裏是我的代碼:加法和減法程序

import java.util.*; 
import java.io.*; 

public class Lesson17p1_ThuotteEmily 
{ 
    public static void main(String args[]) 
    { 
     Scanner kb=new Scanner(System.in); 
     System.out.println("Enter something like 8 + 33 + 1,257 + 137"); 
     String s=kb.nextLine(); 

     Scanner sc=new Scanner(s); 
     char c=sc.findInLine("\\+").charAt(0); 
     sc.useDelimiter("\\s*\\+\\s*"); 

     double sum=0; 
     while(sc.hasNextInt()); 
     { 
      if(c=='+') 
      { 
       sum=sum+sc.nextInt(); 
       System.out.println(sum); 
      } 
     } 

     System.out.println("Sum is: "+sum); 
    } 
} 

我對代碼 - 在程序先前的跡象,但暫時刪除他們,因爲我想弄清楚如何使加法題的程序運行,然後我會在加後面的減法編程,使用與添加相同的東西。

我的代碼編譯並運行良好,但是當它到達應該添加的部分並返回問題總和時,它會停止。它不會返回錯誤或任何內容,它只會凍結。我不確定爲什麼會發生這種情況。我需要循環的分隔符和補充工作,並且當我嘗試將它取出時,它返回一個錯誤。我可以刪除找到的行,但然後我需要一種不同的方式來確定是否要添加或減去程序,我正在努力思考任何事情。我也嘗試重新排列我的代碼,以便先找到+或 - 符號,然後使用分隔符來刪除符號並繼續進行加法或減法,但程序又一次凍結。

任何幫助,你可以給予非常感謝!

回答

0

重拍的代碼註釋:

import java.util.Scanner; 
import java.util.LinkedList; 

public class AddSubstract { 
    public static void main(String[] args) { 
    Scanner userInputScanner = new Scanner(System.in); 
    System.out.print("Type in an expression using + and - operators.\n>> "); 
    String userInput = userInputScanner.nextLine(); 
    // our example input: " 35 - 245 + 34982 " 

    userInput = userInput.trim(); 
    // input is now "35 - 245 + 34982" 
    if(userInput.charAt(0) != '-') userInput = "+" + userInput; 
    // we need to change the input to a set of operator-number pairs 
    // input is now "+35 - 245 + 34982" 
    int result = 0; 
    // result 
    byte sign = 0; 
    // sign; 1 -> positive number, -1 -> negative number, 0 -> not yet checked 
    int numberToPush = 0; 
    for(char c : userInput.toCharArray()) { 
     if(c == '+' || c == '-') { 
     if(sign == 0) sign = (c == '+')?1:-1; 
     else { 
      result += sign*numberToPush; 
      sign = (c == '+')?1:-1; 
      numberToPush = 0; 
     } 
     } else if(c >= '0' && c <= '9') { 
     numberToPush = ((int) c-'0') + 10*numberToPush; 
     } 
    } 
    result += sign*numberToPush; 
    System.out.println("The result is: "+result); 
    } 
+0

感謝您提供幫助,但是這涉及到的東西我的編碼類沒有覆蓋,我不理解他們。對不起... – user2808951

+0

我會重新編寫代碼以刪除LinkedList好嗎? – ciuak

+0

刪除LinkedList – ciuak