2017-09-13 1 views
-1

나는 안드로이드 스튜디오에서 간단한 계산기를 만들려고 노력해 왔습니다. 모든 것은 괜찮지 만 문제는 있습니다. 계산기를 실행하고 도트 버튼을 누르면 텍스트보기에 표시됩니다. " 대신 "0." 또한 하나의 숫자 값에 2 개의 소수점이 있는지 확인해야합니다. 여기 계산기 안드로이드 스튜디오의 점

은 이미지이다. ""

enter image description here

가 도시

과 내가 원하는이 :

enter image description here 내가이 ??를 변경하는 방법

가 여기 내 코드입니다 :

private int cont=0; 

    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    display=(TextView)findViewById(R.id.display); 
    text=""; 
} 


    public void numero1(View view){ /*when i press a number, this method executes*/ 
    Button button = (Button) view; 
    text += button.getText().toString(); 
    display.setText(text); 
} 

    public void dot(View view){ /*This is not finished*/ 
    display.setText{"0."} 
    } 
나는 도트 단추에 대한 다른 방법을 만드는 생각

하지만, 다른 버튼을 누르면 텍스트 값의 내용이 사라집니다. 어떻게 수정합니까?

+0

포맷터를 사용하십시오. – Roman

답변

0

public void numero1(View view){ /*when i press a number, this method executes*/ 
Button button = (Button) view; 
text += button.getText().toString(); 
if(text.substring(0,1).equals(".")) 
text="0"+text;  
display.setText(text); 
} 
0

이 방법

public void dot(View view){ /*This is not finished*/ 
       String str=display.getText().toString().trim(); 
        if(str.length()>0){ 
         display.seText(str+".") 
        }else{ 
         display.setText("0.") 
        } 
    } 
0

사용을 문자열 빌더를 시도하고 모든 텍스트가 이미 문자열을 기존에 입력 추가하려고합니다. 표시하기 전에 문자열 작성기에서 toString() 메소드를 사용하십시오.

0

표시 할 문자 시퀀스를 나타내는 클래스를 생성하고 수신 문자를 처리합니다. 예를 들어

:

class Display { 
    boolean hasPoint = false; 
    StringBuilder mSequence; 

    public Display() { 
     mSequence = new StringBuilder(); 
     mSequence.append('0'); 
    } 

    public void add(char pChar) { 
     // avoiding multiple floating points 
     if(pChar == '.'){ 
      if(hasPoint){ 
       return; 
      }else { 
       hasPoint = true; 
      } 
     } 
     // avoiding multiple starting zeros 
     if(!hasPoint && mSequence.charAt(0) == '0' && pChar == '0'){ 
      return; 
     } 
     // adding character to the sequence 
     mSequence.append(pChar); 
    } 

    // Return the sequence as a string 
    // Integer numbers get trailing dot 
    public String toShow(){ 
     if(!hasPoint) 
      return mSequence.toString() + "."; 
     else 
      return mSequence.toString(); 
    } 
} 

설정하여 숫자와 "점/점"버튼에 이러한 클릭 리스너 :

class ClickListener implements View.OnClickListener{ 
    @Override 
    public void onClick(View view) { 
     // getting char by name of a button 
     char aChar = ((Button) view).getText().charAt(0); 
     // trying to add the char 
     mDisplay.add(aChar); 
     // displaying the result in the TextView 
     tvDisplay.setText(mDisplay.toShow()); 
    } 
} 

이 활동의 ​​()에서 onCreate의 표시를 초기화 :

mDisplay = new Display(); 
    tvDisplay.setText(mDisplay.toShow()); 
관련 문제