I have an array of buttons which contains two elements.
I'd like to create a string from the text of the buttons.
The thing i am struggling with is the if statement. Basically, it is never firing the toast. Why?
String word2 = "ok";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttons[] = new Button[2];
buttons[0] = (Button) findViewById(R.id.btn);
buttons[1] = (Button) findViewById(R.id.btn2);
buttons[0].setText("o");
buttons[1].setText("k");
buttons[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = "";
for (int i = 0; i < 2; i++) {
word += buttons[i].getText().toString();
}
if (word == word2) {
Toast.makeText(getApplicationContext(), "Good",
Toast.LENGTH_LONG).show();
}
}
});
}
Change this:
if (word == word2) {
with this:
if(word.equals(word2)) {
You can't compare String with ==
Write Better Questions (basically questions)
Compare string with .equals() not ==.
Just use if(word.equals(word2) {
Why? The first one is content comparision, but the second one i just
a reference comparision so:
String a = new String("x");
String b = new String("x");
if(a==b){
System.out.println("It wont work");
}else if(a.equals(b)){
System.out.println("It will");
}
Dont ever use new String(), it was just for proof
I must write it.
Change line
for (int i = 0; i < 2; i++) {
into
for (int i = 0; i < buttons.length; i++) {
So your application will be easier to change
Related
We are trying to use this array of integers in other methods. Setting the final shuffled Array to a global variable has become next to impossible. We have set other variable as global. The goal here is to have a new int [] fix array every time a button is clicked. We have been able to generate a random int [] ar but can not utilize the array in other methods. So our questions after making the random int [] ar how can we use it in the onClickBtnOne method? Code with comments below
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3,btn4,btn5,btn6;
String T1,T2,T3,T4,T5,T6;
int test[] = new int[7];
int count = 0;
int v1,v2,v3,v4,v5,v6;
int[] fix = {3,2,1,4,6,5};
// Trying to not use above values
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
main(null);
}
// end onCeate
public static void main(String args[]) {
int [] fix = {1,2,3,4,5,6};
shuffleArray(fix);
// Want to USE this fix shuffleArray
//==================================
for (int i = 0; i < fix.length; i++) {
System.out.print(fix[i] + ",");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int [] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void onClickBtnOne(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
count = count + 1;
v1 = count;
test[v1] = count;
if(fix[0] == test[v1]){
// Need a global fix[] here
// =========================
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
The array you are trying to use does not have an add method you need to put the values in from another variable like this ar[i] = a; So if you use this type of Array declaration List value = new ArrayList<>(); where you declared the other global variable life will be much easier. Modified code below
This will do the shuffle NOTICE value.clear() without this the List will grow each time it is initialized
public void shf(View view){
value.clear();
for (int i = 1; i <= 6; i++) {
value.add(i);
}
Collections.shuffle(value);
}
And here is your test method call value.get(index) Arrays are ZERO based
public void on1(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
if(value.get(0) == 1){
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
I am getting only a single value.how can i get data from all of the editText which i have created dynamically so that i can pass all editText data using comma after every editText .
Here is my code:
Diagnolist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText ed;
Integer count = 1;
final List<EditText> allEds = new ArrayList<EditText>();
for (int i = 0; i < count; i++) {
ed = new EditText(MainActivity.this);
allEds.add(ed);
ed.setId(i);
ed.setHint("add diagonis");
ed.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addDiagnosis.addView(ed);
}
Toast_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[(allEds.size())];
String st = "";
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
st = strings[i]+"," +st;
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
}
});
}
});
do changes as per below code.
final List<EditText> allEds = new ArrayList<EditText>();
declare above list after class define.
Diagnolist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText ed;
Integer count = 1;
for (int i = 0; i < count; i++) {
ed = new EditText(MainActivity.this);
allEds.add(ed);
ed.setId(i);
ed.setHint("add diagonis");
ed.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addDiagnosis.addView(ed);
}
Toast_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[(allEds.size())];
String st = "";
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
st += strings[i]+",";
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
}
});
}
});
I'm not sure what you mean, so correct me if i am wrong. I think you want to get a comma-separated String of all values.
I would just change the onClick to following:
#Override
public void onClick(View view) {
String st;
for(EditText ed : allEds){
st += "," + ed.getText().toString();
}
st = st.substring(1); // cut leading comma
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
I am trying to build a Bengali calculator. Here is the layout of English calculator :
By editing layout I can easily replace English digits with Bengali digits. But when it comes to the calculation i am unable to do it. Like i want it to calculate in Bengali too. e.g it will perform in Bengali like this (২+২=৪) instead of (2+2=4). I have tried the replacing method but it didn't work.
Bengali digits(০ ১ ২ ৩ ৪ ৫ ৬ ৭ ৮ ৯)
English digits(1 2 3 4 5 6 7 8 9)
Thank you for your time.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(result);
}
}
}
Your code tries to extract numerical values from the text on buttons.
You should write custom Double parser which parses Bengali number text to numerical value.
Also you should write a method which converts numerical double value to Bengali number text. You have to use this method while setting screen text.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = BengaliUtils.toDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = BengaliUtils.toDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(BengaliUtils.toString(result));
}
}
}
class BengaliUtils {
static String toString(double value) {
//TODO implement logic
// You can convert value to regular number text, and then replace each char with the Bengali version. The performance could be improved with better logic.
return text;
}
static double toDouble(String text) {
//TODO implement logic
//You can do that, first replace each Bengali char with normal number char. The use Double.parse on new text. The performance could be improved with better logic.
return value;
}
}
#Override
public void onClick(View view) {
String num = editText.getText().toString();
//split the num
char[] charArray = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder(charArray.length);
// loop and convert using switch case
for (int i=0; i<charArray.length; i++ ){
char character = charArray[i];
switch (character){
case '.':
stringBuilder.append(".");
break;
case '0':
stringBuilder.append("০");
break;
case '1':
stringBuilder.append("১");
break;
}
}
//Final result..
textView.setText(stringBuilder);
}
Try above code...
Here is the output
NOTE
I am taking English numbers from EditText on Button click. You will
have to change that in your code.
Currently, switch can handle 0,1,.(decimal) only. You can easily
add cases for other numbers too.
Please Check this answer too. Convert String to another locale in java
As you can see below, I am dynamically creating some sort of quiz with different types of questions (RadioButtons and CheckBoxes).
So I can generate them correctly and they appear as they should.
At the end of the questions there is a normal Button.
And I want to make it available for click only after all the questions have been answered.
I have a function to make sure that all the RadioButtons are answered.
But since I have two types of buttons I can't figure out how to make sure that the questions with the CheckBox answers have at least 1 checked answer.
I have the following code:
ArrayList<RadioGroup> arrGroup;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
buttHole = (Button) findViewById(R.id.button1);
buttHole.setEnabled(false);
getQuestions();
//Creating the list of Questions
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
try
{
for (int i = 0; i <= question.length; i++)
{
if(question[i].multichoice == true)
{
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++)
{
CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
mLinearLayout.addView(box);
}
}
else
{
// create text button
TextView title = new TextView(this);
title.setText(question[i].questionName);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[question[i].answers.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
checkQuestionsAnswer();
}
});
for (int j = 0; j < question[i].answers.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(question[i].answers[j].answer);
}
mLinearLayout.addView(radGr);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean checkQuestionsAnswer()
{
int count = arrGroup.size();
for (int i = 0; i < count; i++)
{
if (arrGroup.get(i).getCheckedRadioButtonId() == -1)
{
Toast.makeText(getApplicationContext(), "Not all questions are answered!", Toast.LENGTH_SHORT).show();
return false;
}
}
Toast.makeText(getApplicationContext(), "Thank you!", Toast.LENGTH_SHORT).show();
buttHole.setEnabled(true);
//Return true if all answer are given
return true;
}
If you have less than 10 answers per question set the id of the checkboxes to (i*10)+zed for example. This way you could loop through the answers like this
for(int i=0; i<question.length; i++){
boolean questionAnswered = false;
for(int zed = 0; zed < question[i].answers.length; zed++) {
CheckBox box = (CheckBox) findViewById(i*10+zed);
if(box != null && box.isChecked()) {
questionAnswered = true;
...
}
}
}
I didn't try this code, and it's just a quick and dirty hint, but I hope it helps.
I need to know how to jumble a word entered into EditText.
The jumbled word will show in another TextView in the same interface.
I have tried to do this but I get a force close error. This is what I have tried within the button:
wordE = (EditText)findViewById(R.id.entry);
jumble = (TextView) findViewById(R.id.jumble);
Button link5Btn = (Button)findViewById( R.id.selected );
link5Btn.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
jumbleMe(al);
}
Which calls the method:
private void jumbleMe( String word ){
al = wordE.getText().toString();
ArrayList<Character> al = new ArrayList<Character>();
for (int i = 0; i < wordE.length(); i++) {
al.add(word.charAt(i));
}
Collections.shuffle(al);
jumble.setText( al.toString() );
}
I would appreciate any help on this. Thanks
You made some mistakes.
Try changing the code to:
link5Btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
jumbleMe(wordE.getText().toString());
}
});
and
private void jumbleMe(String word) {
ArrayList<Character> al = new ArrayList<Character>();
for (int i = 0; i < wordE.length(); i++) {
al.add(word.charAt(i));
}
Collections.shuffle(al);
String result = "";
for (Character character : al) {
result += character;
}
jumble.setText(result);
}