jakiro

Android NumberShapes

Mar 26th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. package com.example.checkevenclass;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4.  
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.EditText;
  8. import android.widget.Toast;
  9.  
  10.  
  11. public class MainActivity extends AppCompatActivity {
  12.  
  13.     class NumberClass{
  14.         int value;
  15.  
  16.         public boolean isTriangular()   //check for triangular number
  17.         {
  18.             if (value < 0)
  19.                 return false;
  20.             int sum = 0;
  21.             for (int n = 1; sum <= value; n++)
  22.             {
  23.                 sum = sum + n;
  24.                 if (sum == value)
  25.                     return true;
  26.             }
  27.             return false;
  28.         }
  29.         public boolean isPerfectSquare()    //check for perfect square
  30.         {
  31.             double sq = Math.sqrt(value);
  32.             return ((sq - Math.floor(sq)) == 0);
  33.         }
  34.     }
  35.  
  36.     public void checkNumber(View view){
  37.  
  38.         EditText editText = (EditText) findViewById(R.id.editText);
  39.         if (editText.getText().toString().trim().length() <=0 ){        //if editText is empty
  40.             Toast.makeText(this, "Enter a number first", Toast.LENGTH_SHORT).show();
  41.         }
  42.         else {
  43.             obj.value = Integer.parseInt(editText.getText().toString().trim());
  44.             Toast.makeText(this, "Is Perfect square: " + obj.isPerfectSquare() + "\nIs triangular number: " + obj.isTriangular()
  45.                     , Toast.LENGTH_SHORT).show();
  46.         }
  47.     }
  48.     NumberClass obj = new NumberClass();
  49.  
  50.     @Override
  51.     protected void onCreate(Bundle savedInstanceState) {
  52.         super.onCreate(savedInstanceState);
  53.         setContentView(R.layout.activity_main);
  54.     }
  55. }
Add Comment
Please, Sign In to add comment