I have posted with this code before but this is a different question.
When the 'guess' button is pressed, a random number is generated. The only problem with the code as it is is that it generates a new number every time regardless of whether the user guesses the right number or not. Ideally I want to give the user a 3 guess limit which would require the app to keep the random number generated the same and then reset after 3 incorrect attempts. I've come to a standstill as I've not done any java for a long time and it's perplexing me a bit in terms of incorporating it into this app.
Thanks in advance
package lab.mad.cct.c3375331task1;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class Task1Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
Random randGen = new Random();
int ranNum = randGen.nextInt(5);
int userNumber = Integer.parseInt(userGuess.getText().to String());
int attempts = 0;
if (userNumber >19 ) {
guessText.setText("Please guess between 0 and 20");
} else if (userNumber == ranNum) {
guessText.setText("You got it!");
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.RED);
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
}
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
});
}
}
remove int userNumber = Integer.parseInt(userGuess.getText().to String()); from onClick(View v) because every time guessme button will be pressed, it will generate the new number.
declare some variables in your class
public static final int ATTEMPTS = 3;
public int attempt = 0;
public int currentRandomNumber = new Random().nextInt(5);
inside onClick();
if(attempt >= ATTEMPTS){
attempt = 0;
currentRandomNumber = new Random().nextInt(5);
} else {
attempt++;
}
// the rest of your code..
also, you are using rand..nextInt(5) but by the looks of your code you should be using ..nextInt(20)
Related
Fair Warning: I'm a student trying to build an app for our research.
So I'm Trying to build an app where the user Defines the amount of Q/A he/she wants, then the app will ask for the user to put different Q/A until it reaches the an equal amount where it will then open up a new page to make the user answer those Q/A.
The Problem is that the Loop fails to repeat at the stated amount by user making the app not being able to store let's say 10 Q/A to the JShared / Shared Preference.
Here's the loop code:
package com.prgr.quizards.canary;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.AppCompatButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Objects;
public class question extends Activity {
private HashMap<String, Object> map = new HashMap<>();
private TextView text;
private EditText inop;
private TextInputEditText ans;
private AppCompatButton btn;
private SharedPreferences jshared2;
private SharedPreferences jshared;
#Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.activity_question);
initializedata();
AppCompatButton btn2 = findViewById(R.id.button3);
btn = findViewById(R.id.button);
btn2.setOnClickListener(v -> gotoback());
btn.setOnClickListener(view -> logicg());
}
public void gotoback(){
Intent intent = new Intent(question.this, activity_home_screen.class);
startActivity(intent);
}
private void initializedata(){
jshared = getSharedPreferences("j", Activity.MODE_PRIVATE);
jshared2 = getSharedPreferences("j2", Activity.MODE_PRIVATE);
inop = findViewById(R.id.inop);
ans = findViewById(R.id.ans);
text = findViewById(R.id.text1);
}
private void logicg() {
String mount = jshared.getString("amount", "");
int amounts = Integer.parseInt(mount);
for (int i = 1; i < amounts; i++) {
//String shite = Integer.toString(qloop);
//Toast.makeText(getApplicationContext(), shite, Toast.LENGTH_SHORT).show();
if (i == amounts) {
Intent intent = new Intent(question.this, answerscrn.class);
startActivity(intent);
} else{
map = new HashMap<>();
map.put("answer", Objects.requireNonNull(ans.getText()).toString());
map.put("question", inop.getText().toString());
jshared2.edit().putString("data", new Gson().toJson(map)).commit();
}
}
}
}
I tried to do a for loop + if else inside the for loop and that only returns the error of Condition 'i == amounts' is always 'false' what i expect is for it to loop till it reaches the same number stated by the amounts (which is the user defined value) to open up a new page using intent.
From what I understand, your problem it in the loop, tho I don't understand how do you ask/put diffrent questions.
i == amounts is never true because the condition in the FOR loop is: i < amounts
You can simplify your code like this:
private void logicg() {
String mount = jshared.getString("amount", "");
int amounts = Integer.parseInt(mount);
for (int i = 0; i < amounts; i++) {
//String shite = Integer.toString(qloop);
//Toast.makeText(getApplicationContext(), shite, Toast.LENGTH_SHORT).show();
map = new HashMap<>();
map.put("answer", Objects.requireNonNull(ans.getText()).toString());
map.put("question", inop.getText().toString());
jshared2.edit().putString("data", new Gson().toJson(map)).commit();
}
Intent intent = new Intent(question.this, answerscrn.class);
startActivity(intent);
}
for (int i = 1; i < amounts; i++) IF THIS WAS YOUR LOOP AND YOU TOLD THAT USE WILL SELECT THE NO OF QUESTION SO
IF YOU ADD THIS LOOP THEN YOUR APP WILL STOP AT -1 STEP FOR EXAMPLE
IF YOUR USER SELECT 10 AND THIS LOOP WILL END AT IT WILL END AT 9
BECAUSE YOUR APP IS STARTING AT I=1 AND I<AMOUNT (THE VALUE ENTER BY THE USE SO YOU CAN MEET THE GOAL
SO YOU NEED TO CHANGE THE LOOP TO for (int i = 1; i < =amounts; i++)
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 3 years ago.
Basically, I need to generate 5 random numbers that are unique every time they are generated (so they don't repeat) and then output them to a TextView.
I managed to generate the 5 numbers, however, they are not unique all the time, meaning sometimes the same number shows up twice or more when the button is pressed to generate those numbers.
Here's what I have gotten so far:
import androidx.annotation.IntegerRes;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView numbersGenerated;
private Button btnGenerate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numbersGenerated = findViewById(R.id.numbers);
btnGenerate = findViewById(R.id.btnGenerate);
btnGenerate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Integer> arrayRandom = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 5; i++)
{
Integer r = rand.nextInt(50) + 1;
arrayRandom.add(r);
}
numbersGenerated.setText(arrayRandom.toString());
}
});
}
}
I am not sure what type of validation I can do since this is my first ever contact with Java, so any help is appreciated.
instead of
ArrayList<Integer> arrayRandom = new ArrayList<>();
use a Set
Set<Integer> set = new HashSet<>();
and then do a
while (set.size() < 5) {
set.add(rand.nextInt(50) + 1);
}
I require a little bit of help with some java coding for my android guessing game app.
At the moment my if else statements cover whether a guess is too high, too low, or correct. What I want it to do is tell the user if the answer they give is close to the answer or far away from it. Say, within 50% or over 50% away. I can do if else where it uses numbers but I'm stumped when I'm trying to work out how to get it to work out the percentage based on the random number that the program generates. If it was a static number I'd be fine but I can't work it out this way.
Any help greatly appreciated.
package lab.mad.cct.c3375331task1;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class Task1Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
Random randGen = new Random();
int ranNum = randGen.nextInt(5);
int userNumber = Integer.parseInt(userGuess.getText().toString());
int attempts = 0;
if (userNumber >19 ) {
guessText.setText("Please guess between 0 and 20");
} else if (userNumber == ranNum) {
guessText.setText("You got it!");
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.RED);
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
}
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
});
}
}
You can calculate the percentage difference between two numbers (the random number and the guessed number) like this:
public float percentDiff(int randomNumber, int guessedNumber) {
int diff = Math.abs(randomNumber - guessedNumber);
float diffPercentage = (float) diff / (float) randomNumber;
System.out.println("" + diffPercentage);
return diffPercentage;
}
A value >0.5 would be more than 50% off and vice versa.
If you want to calculate (on the fly) what the Users supplied number is percentage wise towards the randomly generated number then you can use a simple formula like:
int percentOf = ((userNumber * 100) / ranNum);
Im building a converter app and it's to convert centimetres into inches but i want it to do the opposite too, so the user can enter a value into either box to convert it. Ive tried various ways but won't work.
Here's my src code
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class CentInch extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cent_inch);
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
double centimeters = Double.valueOf(editCentimeters.getText()
.toString());
double inches = centimeters * 0.393700787;
editInches.setText(String.valueOf(inches));
}
});
}
}
I know little about android but try to make something like this:
public void onClick(View arg0) {
double centimeters = 0;
double inches = 0;
//convert inches to centimeters
if(editCentimeters.getText().toString().isEmpty()){
inches = Double.valueOf(editInches.getText().toString());
//do the conversion
editCentimeters.setText(String.valueOf(inches));
}
//convert centimeters to inches
else if(editInches.getText().toString().isEmpty()){
centimeters = Double.valueOf(editCentimeters.getText().toString());
//do the conversion
editInches.setText(String.valueOf(inches));
}
}
if isEmpty() doesn't work try with .equals("") or == "". You get the point
I'm working on an app that involved comparing to numbers inputted by the user via text box, but wen I put in any if statements the program crashes whenever they are called. Otherwise the program runs just fine without any crashes or errors.
package improvecredit.app.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.text.Editable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ImprovrCreditBasicActivity extends Activity {
/** Called when the activity is first created. */
public int minCredScore = 300;
public int maxCredScore = 850;
public int inputScore;
public int idealScore;
public Editable inputString;
public Editable idealString;
public EditText user;
public EditText desired;
public TextView output;
public Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user = (EditText) findViewById(R.id.user_text);
desired = (EditText) findViewById(R.id.desired_text);
output = (TextView) findViewById(R.id.output_text);
submit = (Button) findViewById(R.id.submit_button);
//submit.setOnClickListener(new View.OnClickListener());
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//inputString = user.getText();
//idealString = desired.getText();
inputScore = Integer.getInteger(user.getText().toString());
idealScore = Integer.getInteger(desired.getText().toString());
if (inputScore >= 0 && idealScore >= 0){
if (inputScore < minCredScore || idealScore < minCredScore){
output.setText("Invalid Entries");
}
if (inputScore > maxCredScore || idealScore > maxCredScore){
output.setText("Invalid Entries");
}
if (inputScore > idealScore){
output.setText("Nice Credit Score!");
}
if (inputScore < idealScore){
output.setText("For more information on how to improve your credit score, please visit" + "/n" + "http://www.creditscoresandcredit.com/");
}
}
else{
output.setText("Please enter valid credit scores");
}
}
});
}
If someone can point out what may have been done wrong in the code I would really appreciate it.
On first glance, don't use Integer.getInteger(), use Integer.parseInt().
If that doesn't fix it, please include the crash log from the console so we can see exactly what exception is being raised.
I'm betting that there is a null value introduced. If you check for null before using the variables idealScore and inputScore in the If statement, it will avoid this error. Until you paste the error trace, we can only guess for you.