I'm Mikamocha, and I just started programming Android apps. I have problems in my first calculator app (the results). What I mean is so that 2+2 will be 4 instead of 4.0, 5-2 will be 3 instead of 3.0, etc.
package com.yeshua.mikamocha.myxcalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText Scr;
private float NumberBf=0, NumAf, result=0;
private String Operation, mod="replace";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Scr = (EditText) findViewById(R.id.txtScreen);
Scr.setText("");
int idList[] = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn2, R.id.btn3, R.id.btn4,
R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9,
R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide,
R.id.btnClear,R.id.btnEquals, R.id.btnDot, };
for(int id:idList) {
View v = (View) findViewById(id);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onButtonClick(v);
}
});
}
}
public void mMath(String str) {
mResult();
try {
NumberBf = Float.parseFloat(Scr.getText().toString());
Operation = str;
}catch (Exception e) {
Toast.makeText(getApplicationContext(), (CharSequence) e, Toast.LENGTH_SHORT).show();
Scr.setText("SYNTAX ERROR");
mod = "replace";
}
}
public void mResult() {
NumAf = 0;
if(!Scr.getText().toString().trim().isEmpty())
NumAf = Float.parseFloat(Scr.getText().toString());
result = NumAf;
try {
switch (Operation) {
case "+":
result = NumAf + NumberBf;
break;
case "-":
result = NumberBf - NumAf;
break;
case "*":
result = NumAf * NumberBf;
break;
case "/":
result = NumberBf / NumAf;
break;
default:
result = NumAf;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Scr.setText(String.valueOf(result));
mod = "replace";
}
public void getKeyboard(String str) {
String ScrTxt = Scr.getText().toString();
ScrTxt += str;
if(mod.equals("add"))
Scr.setText(ScrTxt);
else
Scr.setText(str);
mod = "add";
}
public void onButtonClick(View v) {
switch (v.getId()) {
case R.id.btnClear: //Clear
Scr.setText("");
NumberBf = 0;
Operation = "";
break;case R.id.btnAdd:
mMath("+");
break;
case R.id.btnSubtract:
if(mod.equals("replace")) {
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
}
else mMath("-");
break;
case R.id.btnMultiply:
mMath("*");
break;
case R.id.btnDivide:
mMath("/");
break;
case R.id.btnEquals:
mResult();
Operation = "";
NumberBf = 0;
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
Thanks.
You should use NumberFormat.
For example:
public static void main(String[] args) {
System.out.println(format(14.0184849945)); // prints '14.01'
System.out.println(format(13)); // prints '13'
System.out.println(format(3.5)); // prints '3.5'
System.out.println(format(3.138136)); // prints '3.13'
}
public static String format(Number n) {
NumberFormat format = DecimalFormat.getInstance();
format.setRoundingMode(RoundingMode.FLOOR);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(2);
return format.format(n);
}
you are using float datatype for result instead of use int type and parse operation value in int.
result = (int)(NumAf + NumberBf);
For Ref. DecimalFormat
Change as follows as you are using float as result you are getting decimal so use int,
private int result=0;
//and
result =(int) (NumAf + NumberBf);
OR
float one= 2.0;
float two= 2.5;
//DecimalFormat format = new DecimalFormat();
//format.setDecimalSeparatorAlwaysShown(false);
DecimalFormat format=new DecimalFormat("#,###.#");
System.out.println( format.format(one) );//prints 2
System.out.println( format.format(two) );//prints 2.5
Related
I have an application where I set up the user interface completely programmatically, meaning I didn't draw the objects in XML. It works perfectly fine, but since I drew the objects in the content with different classes, I need to establish communication between the two classes. For example, if I press a button in Class1, I want to write the text on the button in Class2 and trigger the button in Class2 based on that. I think using an interface is the most logical solution for this, but I'm unable to transfer the data from Class1 to Class2 using the interface. I'm getting an error saying 'cannot be cast to...'
My GameInterface:
public interface GameInterface {
void seciliHucreyiDoldur(String seciliHucreyiDoldur);
}
Class1:
private class Cell implements GameInterface {
int value;
boolean fixed;
Button btn;
String hucreyiDolduracakVeri;
Context THIS;
public Cell(int initValue, Context THIS) {
this.THIS = THIS;
value = initValue;
if (value != 0) {
fixed = true;
} else {
fixed = false;
}
btn = new Button(THIS);
btn.setTextSize(16);
if (fixed) {
btn.setText(String.valueOf(value));
}
txtSayac.setGravity(Gravity.CENTER);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fixed) {
Toast.makeText(THIS, "Bu hücreyi değiştiremezsiniz!", Toast.LENGTH_SHORT).show();
return;
}
/*value++;
if (value > 9) {
value = 1;
}*/
btn.setBackgroundResource(R.drawable.hucre_arkaplani_kirmizimsi);
btn.setTextColor(Color.BLACK);
btn.setText(hucreyiDolduracakVeri);
btn.setTextColor(Color.RED);
if (correct()) {
textView.setText("");
} else {
textView.setText("Tekrar eden rakamlar var, kontrol etmelisin!");
}
}
});
}
#Override
public void seciliHucreyiDoldur(String seciliHucreyiDoldur) {
this.hucreyiDolduracakVeri = seciliHucreyiDoldur;
Toast.makeText(THIS, hucreyiDolduracakVeri, Toast.LENGTH_SHORT).show();
if (fixed) {
//Toast.makeText(THIS, "Bu hücreyi değiştiremezsiniz!", Toast.LENGTH_SHORT).show();
return;
}
/*value++;
if (value > 9) {
value = 1;
}*/
btn.setTextColor(Color.BLACK);
btn.setText(seciliHucreyiDoldur);
btn.setTextColor(Color.RED);
btn.setBackgroundResource(R.drawable.hucre_arkaplani_mavi_acik);
if (correct()) {
textView.setText("");
} else {
textView.setText("Tekrar eden rakamlar var, kontrol etmelisin!");
}
}
#Override
public void hucreSeciliMi(boolean hucreSecilimi) {
}
}
Class2:
public class AltBolumNumericTablo implements GameInterface{
Button btnClick;
boolean onClicked;
int value;
Activity activity;
GameInterface gameInterface;
public AltBolumNumericTablo(int value, Context THIS, Activity activity) {
this.activity = activity;
this.value = value;
btnClick = new Button(THIS);
btnClick.setTextSize(24f);
gameInterface = (GameInterface) activity;
switch (value) {
case 0:
btnClick.setText("1");
break;
case 1:
btnClick.setText("2");
break;
case 2:
btnClick.setText("3");
break;
case 3:
btnClick.setText("4");
break;
case 4:
btnClick.setText("5");
break;
case 5:
btnClick.setText("6");
break;
case 6:
btnClick.setText("7");
break;
case 7:
btnClick.setText("8");
break;
case 8:
btnClick.setText("9");
break;
case 9:
btnClick.setBackgroundResource(R.drawable.sil_icon);
break;
}
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickIslemleri(value);
}
});
}
public void clickIslemleri(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
gameInterface.seciliHucreyiDoldur(String.valueOf(value+1));
break;
case 9:
gameInterface.seciliHucreyiDoldur("");
break;
}
}
public void kayitliOyunuGuncelle() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
new MisafirGirisliOyunKaydiDAO().misafirgirisiKaydiGuncelle(misafirOyunKaydiDB,
1, input + " s", 0, "00:45", kayitZamanini());
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getTimestamp());
}
}
public void gecmisOyunlarGuest() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getId() + "");
}
}
#Override
public void seciliHucreyiDoldur(String seciliHucreyiDoldur) {
}
#Override
public void hucreSeciliMi(Boolean hucreSecilimi) {
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.devapost.mysudoku, PID: 4945
java.lang.ClassCastException: com.devapost.mysudoku.MainActivity cannot be cast to com.devapost.mysudoku.utils.GameInterface
at com.devapost.mysudoku.MainActivity$AltBolumNumericTablo.<init>(MainActivity.java:514)
at com.devapost.mysudoku.MainActivity.altNumericDoldur(MainActivity.java:297)
MainActivity.java:
public class MainActivity extends AppCompatActivity implements GameInterface{
Cell[][] table;
AltBolumNumericTablo[][] tableAltNumeric;
MisafirGirisEkrani[] tableMisafir;
UyeMenuEkrani[] tableUyeMenusu;
String input;
TableLayout tableLayout;
TextView textView, txtSayac;
Button buttonGenerate;
LinearLayout linearLayout;
Button btnGoogleLoginMainScreen, btnMisafirMainScreen;
int hangiEkranda = 0;
MisafirOyunKaydiDB misafirOyunKaydiDB;
ArrayList<MisafirGirisliOyunKaydiModel> misafirKaydiListesi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
girisSecenekleriEkrani();
}
#Override
public void onBackPressed() {
switch (hangiEkranda) {
case 0:
case 2://üye menusundeyse
super.onBackPressed();
linearLayout.removeAllViews();
onBackPressed();
break;
case 1://misafir menusundeyse
girisSecenekleriEkrani();
break;
case 3://misafir oyun ekranındaysa
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
new MisafirGirisliOyunKaydiDAO().saveGame(misafirOyunKaydiDB, input, input, 5, txtSayac.getText().toString(), 1, kayitZamanini());
misafirEkraniniDoldur();
break;
case 4://misafir ayarlardaysa
case 5://misafirden nasıl oynanıra gittiyse
misafirEkraniniDoldur();
break;
case 6://serüvene gittiyse
case 7://rastgele oyun kurma ekranına gittiyse
case 8://skorboard ekranına gittiyse
case 9://üye ekranından ayarlara gittiyse
case 10://üye ekranından nasıl oynanır ekranına gittiyse
uyelerinMenusu();
break;
}
}
public String kayitZamanini() {
Calendar anlikSaatDakika = Calendar.getInstance();
int yil = anlikSaatDakika.get(Calendar.HOUR_OF_DAY);
int ay = anlikSaatDakika.get(Calendar.MINUTE);
int gun = anlikSaatDakika.get(Calendar.SECOND);
int saat = anlikSaatDakika.get(Calendar.HOUR_OF_DAY);
int dakika = anlikSaatDakika.get(Calendar.MINUTE);
int saniye = anlikSaatDakika.get(Calendar.SECOND);
return gun + "." + ay + "." + yil + " - " + saat + ":" + dakika + ":" + saniye;
}
public void girisSecenekleriEkrani() {//giriş seçenekleri ekranı
hangiEkranda = 0;
linearLayout = new LinearLayout(MainActivity.this);
btnGoogleLoginMainScreen = new Button(MainActivity.this);
btnMisafirMainScreen = new Button(MainActivity.this);
btnGoogleLoginMainScreen.setText("Google İle Giriş Yap");
btnMisafirMainScreen.setText("Misafir Girişi");
btnGoogleLoginMainScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uyelerinMenusu();
}
});
btnMisafirMainScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayout.removeAllViews();
misafirEkraniniDoldur();
}
});
linearLayout.addView(btnGoogleLoginMainScreen);
linearLayout.addView(btnMisafirMainScreen);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT
);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.setLayoutParams(layoutParams);
setContentView(linearLayout);
}
public void yeniOyunMisafirIcin() {
hangiEkranda = 3;
linearLayout.removeAllViews();
int N = 9, K = 25;
Sudoku sudoku = new Sudoku(N, K);
sudoku.fillValues();
txtSayac = new TextView(MainActivity.this);
input = sudoku.printSudoku();
String[] split = input.split(" ");
table = new Cell[9][9];
tableLayout = new TableLayout(MainActivity.this);
for (int i = 0; i < 9; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
for (int j = 0; j < 9; j++) {
String s = split[i * 9 + j];
char c = s.charAt(0);
table[i][j] = new Cell(c == '?' ? 0 : c - '0', MainActivity.this);
paintCellBackground(i, j, table[i][j].btn);
tableRow.addView(table[i][j].btn);
}
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
textView = new TextView(MainActivity.this);
buttonGenerate = new Button(MainActivity.this);
linearLayout = new LinearLayout(MainActivity.this);
linearLayout.addView(txtSayac);
LinearLayout linearLayoutEkMetin = new LinearLayout(MainActivity.this);
linearLayoutEkMetin.setLayoutParams(
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayoutEkMetin.setOrientation(LinearLayout.VERTICAL);
linearLayoutEkMetin.setGravity(Gravity.CENTER_HORIZONTAL);
buttonGenerate.setText("Generate");
buttonGenerate.setVisibility(View.GONE);
buttonGenerate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
misafirEkraniniDoldur();
progressDialog.dismiss();
}
});
linearLayoutEkMetin.addView(buttonGenerate);
linearLayout.addView(tableLayout);
linearLayout.addView(textView);
linearLayout.addView(linearLayoutEkMetin);
linearLayout.setOrientation(LinearLayout.VERTICAL);
altNumericDoldur();
setContentView(linearLayout);
}
public void paintCellBackground(int i, int j, Button button) {
switch (i) {
case 0:
case 1:
case 2:
case 6:
case 7:
case 8:
switch (j) {
case 0:
case 1:
case 2:
case 6:
case 7:
case 8:
button.setBackgroundResource(R.drawable.hucre_arkaplani_gri);
break;
case 3:
case 4:
case 5:
button.setBackgroundResource(R.drawable.hucre_arkaplani_beyaz);
break;
}
break;
case 3:
case 4:
case 5:
switch (j) {
case 0:
case 1:
case 2:
case 6:
case 7:
case 8:
button.setBackgroundResource(R.drawable.hucre_arkaplani_beyaz);
break;
case 3:
case 4:
case 5:
button.setBackgroundResource(R.drawable.hucre_arkaplani_gri);
break;
}
break;
}
}
public void misafirEkraniniDoldur() {//misafir ekranını doldurur
hangiEkranda = 1;
tableMisafir = new MisafirGirisEkrani[5];
tableLayout = new TableLayout(MainActivity.this);
for (int i = 0; i < 5; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
tableMisafir[i] = new MisafirGirisEkrani(i, MainActivity.this);
tableRow.addView(tableMisafir[i].btnClick);
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.setMarginStart(16);
layoutParams.setMarginEnd(16);
tableLayout.setLayoutParams(layoutParams);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.addView(tableLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
}
public void altNumericDoldur() {//alt numerik tabloyu doldurur
tableAltNumeric = new AltBolumNumericTablo[2][5];
tableLayout = new TableLayout(MainActivity.this);
int butonID = 0;
for (int i = 0; i < 2; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
for (int j = 0; j < 5; j++) {
tableAltNumeric[i][j] = new AltBolumNumericTablo(butonID, MainActivity.this,MainActivity.this);
tableRow.addView(tableAltNumeric[i][j].btnClick);
butonID++;
}
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
//linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.setMarginStart(16);
layoutParams.setMarginEnd(16);
tableLayout.setLayoutParams(layoutParams);
linearLayout.addView(tableLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
}
private void uyelerinMenusu() {//google ile giriş yapanlar için serüven ekranı
hangiEkranda = 2;
tableUyeMenusu = new UyeMenuEkrani[5];
tableLayout = new TableLayout(MainActivity.this);
for (int i = 0; i < 5; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
tableUyeMenusu[i] = new UyeMenuEkrani(i, MainActivity.this);
tableRow.addView(tableUyeMenusu[i].btnClick);
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.setMarginStart(16);
layoutParams.setMarginEnd(16);
tableLayout.setLayoutParams(layoutParams);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.addView(tableLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
}
#Override
public void seciliHucreyiDoldur(String seciliHucreyiDoldur) {
}
#Override
public void hucreSeciliMi(boolean hucreSecilimi) {
}
public class UyeMenuEkrani {
Button btnClick;
boolean onClicked;
int value;
public UyeMenuEkrani(int value, Context THIS) {
this.value = value;
btnClick = new Button(THIS);
switch (value) {
case 0:
btnClick.setText("Serüven");
break;
case 1:
btnClick.setText("Rastgele Oyna");
break;
case 2:
btnClick.setText("Skor Tablosu");
break;
case 3:
btnClick.setText("Ayarlar");
break;
case 4:
btnClick.setText("Nasıl Oynanır");
break;
}
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickIslemleri(value);
}
});
}
public void clickIslemleri(int value) {
switch (value) {
case 0://seruven
Toast.makeText(MainActivity.this, "serüvene gider", Toast.LENGTH_SHORT).show();
break;
case 1://rastgele
yeniOyunMisafirIcin();//rastgele ekranı misafir giriş ekranına gider, çok benzer zaten
break;
case 2://skorboard
Toast.makeText(MainActivity.this, "skorboard", Toast.LENGTH_SHORT).show();
break;
case 3://ayarlar
Toast.makeText(MainActivity.this, "ayarlar", Toast.LENGTH_SHORT).show();
break;
case 4://nasıl oynanır
Toast.makeText(MainActivity.this, "nasıl oynanır", Toast.LENGTH_SHORT).show();
break;
case 5:
break;
}
}
}
public class MisafirGirisEkrani {
Button btnClick;
boolean onClicked;
int value;
public MisafirGirisEkrani(int value, Context THIS) {
this.value = value;
btnClick = new Button(THIS);
switch (value) {
case 0:
btnClick.setText("Yeni Oyun");
break;
case 1:
btnClick.setText("Devam Et");
break;
case 2:
btnClick.setText("Ayarlar");
break;
case 3:
btnClick.setText("Giriş Yap");
break;
case 4:
btnClick.setText("Nasıl Oynanır");
break;
}
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickIslemleri(value);
}
});
}
public void clickIslemleri(int value) {
switch (value) {
case 0:
yeniOyunMisafirIcin();
break;
case 1://eski oyunları listele ve onlardan seçip devam et
gecmisOyunlarGuest();
break;
case 2:
kayitliOyunuGuncelle();
Toast.makeText(MainActivity.this, "ayarlar", Toast.LENGTH_SHORT).show();
break;
case 3:
girisSecenekleriEkrani();
break;
case 4:
Toast.makeText(MainActivity.this, "nasıl oynanır", Toast.LENGTH_SHORT).show();
break;
}
}
public void kayitliOyunuGuncelle() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
new MisafirGirisliOyunKaydiDAO().misafirgirisiKaydiGuncelle(misafirOyunKaydiDB,
1, input + " s", 0, "00:45", kayitZamanini());
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getTimestamp());
}
}
public void gecmisOyunlarGuest() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getId() + "");
}
}
}
boolean complated() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (table[i][j].value == 0) {
return false;
}
}
}
return true;
}
boolean correct(int i1, int j1, int i2, int j2) {
boolean[] seen = new boolean[10];
for (int i = 1; i <= 9; i++) {
seen[i] = false;
}
for (int i = i1; i < i2; i++) {
for (int j = j1; j < j2; j++) {
int value = table[i][j].value;
if (value != 0) {
if (seen[value]) {
return false;
}
seen[value] = true;
}
}
}
return true;
}
boolean correct() {
for (int i = 0; i < 9; i++) {
if (!correct(i, 0, i + 1, 9)) {
return false;
}
}
for (int j = 0; j < 9; j++) {
if (!correct(0, j, 9, j + 1)) {
return false;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (!correct(3 * i, 3 * j, 3 * i + 3, 3 * j + 3)) {
return false;
}
}
}
return true;
}
}
Got the issue .
Issue is at below mentioned line in AltBolumNumericTablo class
gameInterface = (GameInterface) activity;
you just need to change as mentioned below
From
public AltBolumNumericTablo(int value, Context THIS, Activity activity)
To
public AltBolumNumericTablo(int value, Context THIS, GameInterface gameInterfaceParam){
gameInterface = gameInterfaceParam
.. existing code
}
I'm making a simple android calculator that has to support +,-,*,/ .
When I try to press any button - the app crashes. After some investigations, I found out that the problem is in the inner if statement :
public void buttonFunctionNumber(View view) {
if (view instanceof Button){
Button button = (Button) view;
String str = button.getText().toString();
if (Double.parseDouble(result.getText().toString()) == 0)
result.setText(str);
else
result.append(str);
}
}
The if: after the user pressed the desired number, and right before he prasses the second - the calculator's screen will show a 0. So in this if I want to check whether the result is 0 (the result is what the calculator's screen shows) to know that the user want to continue to the next number.
the else: the user wants to continue adding more digits to the number for the calculations so we append the next digit.
I would like to know how can I solve this problem.
Thanks for your time :)
The whole code:
package com.example.myfirstproj;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView result;
double num1=0.0, num2=0.0;
String sign = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.textViewResult);
}
public void buttonFunctionNumber(View view) {
if (view instanceof Button){
Button button = (Button) view;
String str = button.getText().toString();
if (Double.parseDouble(result.getText().toString()) == 0.0)
result.setText(str);
else
result.append(str);
}
}
public void buttonEqualFunction(View view) {
if (view instanceof Button) {
String temp2 = result.getText().toString();
num2 = Double.parseDouble(temp2);
double res = 0.0;
switch (sign) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
if (num2 != 0.0)
res = num1 / num2;
else
Toast.makeText(this, "Error Cant divide by 0", Toast.LENGTH_LONG).show();
break;
default:
break;
}
num1 = res;
result.setText(res + "");
}
}
public void buttonAddFunction(View view) {
if (view instanceof Button){
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "+";
result.setText(" ");
}
}
public void buttonSubtractFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "-";
result.setText("0");
}
}
public void buttonMultiplyFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "*";
result.setText("0");
}
}
public void buttonDivideFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "/";
result.setText("0");
}
}
public void buttonClearFunction(View view) {
result.setText("0");
}
}
Try trimming your result and checking for null and empty first before parsing
String result = result.getText().toString()).trim();
if (result != null && result.length() > 0) {
if (Double.parseDouble(result) == 0.0)
result.setText(str);
else
result.append(str);
}
I had a calculator app to do as a project and I'm a bit lost. My teacher only put the java text itself, but there's some elements in the xml document that I need to add.
Here is some problems with my main document. My onClickfunctions are underlined as unused.
public class MainActivity extends AppCompatActivity {
private TextView _screen;
private String display="";
private String currentOperator="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_screen=(TextView) findViewById(R.id.textView);
_screen.setText(display);
}
private void updateScreen() {
_screen.setText(display);
}
private void **onClickNumber**(View v) {
Button b = (Button) v;
display+=b.getText();
updateScreen();
}
public void onClickOperator(View v) {
Button b= (Button) v;
display+=b.getText();
currentOperator=b.getText().toString();
updateScreen();
}
private double operateArithmetic(String a, String b, String op) {
switch (op) {
case "+": return(Double.valueOf(a) + Double.valueOf(b));
case "-": return(Double.valueOf(a) - Double.valueOf(b));
case "x": return(Double.valueOf(a) * Double.valueOf(b));
case "\u00f7": try{
return(Double.valueOf(a) / Double.valueOf(b));
} catch(Exception e){
Log.d("Calc", e.getMessage());
}
default: return -1;
}
}
private double operateTrigonometric(String a, String op) {
switch (op){
case "sin": return(Math.sin(Double.valueOf(a)));
case "cos": return(Math.cos(Double.valueOf(a)));
case "tan": try{
return(Math.tan(Double.valueOf(a)));
}catch(Exception e) {
Log.d("Calc", e.getMessage());
}
case "\u221a": return(Math.sqrt(Double.valueOf(a)));
default: return -1;
}
}
public void **onClickEqual**(View v) {
String[] operation=display.split(Pattern.quote(currentOperator));
Double result;
if(operation.length==1) {
result = operateTrigonometric(operation[0], currentOperator);
_screen.setText(display + "\n" + String.valueOf(result));
}
else if (operation.length<2)
return;
else {
return = operateArithmetic(operation[0], operation[1], currentOperator);
_screen.setText(display + "\n" + String.valueOf(result));
}
}
private void clear() {
display="";
currentOperator="";
}
public void **onClickClear**(View v){
clear();
updateScreen();
}
What is in double * are the things that appear grey. (I am using Android Studio)
My buttons have nothing special, only Layout properties to them.
My teacher noted that I need to add an OnClickNumber to my xml file (with all the buttons) and the only option I have is to add
android:onClick="onClickfunction"
the function is either Operator, Clear or Equal.
when actually running the app I get an error message for line
return = operateArithmetic(operation[0], operation[1], currentOperator);
because I'm expected to add something before the =
I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.
Hello I'm a college student studying Java. I'm working on a android application. It compiles and shows no error. However when it runs, there's a unexpected close error.
Here's my application. When you click on the calculate ws you purpose to change to this screen.
Here's my code:
package com.warhammerdicerrolleralpha;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class myMain extends Activity
{
EditText enternumberofdice;
final TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
ImageView i = new ImageView(this);
{
i.setAdjustViewBounds(true);
}
private int myFaceValue;
int myNum;
/**
* Called when the activity is first created.
*
* #return
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void go()
{
while (myNum > 0)
{
// TODO Auto-generated method stub
textGenerateNumber.setText(String.valueOf(enternumberofdice));
--myNum;
return;
}
}
public int roll()
{
int val = (int) (6 * Math.random() + 1); // Range 1-6
setValue(val);
return val;
}
{
try
{
myNum = Integer.parseInt(enternumberofdice.getText().toString());
}
catch (NumberFormatException nfe)
{
enternumberofdice.setText("Does not work");
}
}
public int getValue()
{
return myFaceValue;
}
public void setValue(int myFaceValue)
{
this.myFaceValue = myFaceValue;
}
{
switch (myFaceValue)
{
case 5:
i.setImageResource(R.drawable.dicefive);
break;
case 1:
i.setImageResource(R.drawable.diceone);
break;
case 3:
i.setImageResource(R.drawable.dicethree);
break;
case 2:
i.setImageResource(R.drawable.dicetwo);
break;
case 4:
i.setImageResource(R.drawable.dicefour);
break;
case 6:
i.setImageResource(R.drawable.dicesix);
break;
default:
i.setImageResource(R.drawable.error);
break;
}
text = (EditText) findViewById(R.id.editText1);
text2 =(EditText) findViewById(R.id.editText2);
text3 = (EditText) findViewById(R.id.editText3);
btutorial1 = (Button) findViewById(R.id.button1);
btutorial1.setOnClickListener((OnClickListener) this);
Button buttonGenerate = (Button) findViewById(R.id.button1);
enternumberofdice = (EditText) findViewById(R.id.enternumberofdice);
Button buttonGenerate2 = (Button) findViewById(R.id.battlecalculate);
buttonGenerate2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
setContentView(R.layout.main2);
}
});
buttonGenerate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
go();
roll();
}
});
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.button1:
if (number1 > number2)
{
text3.setText("Three and above");
return;
}
else if (number1 < number2)
{
text3.setText("Five and above");
return;
}
else if (number1 == number2)
{
text3.setText("Four and above");
return;
}
else
{
text3.setText("Not Working");
return;
}
}
}
}
Look at your stack trace, but I think it may be because of this block:
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
It looks as though you are trying to parseInt over null values. You need to specify where text, text2, text3 are in your form using similar code to:
TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
Hope that helps.