Unable to get method to access characters in a String - java

I am trying to make a Caesar Cipher app on Android Studio. I have the XML file and most of the other code ready but was unable to continue past the point in the code where I must access each element of the string. I have tried using the charAt() function.
Also I just want the character at the point in the array to increase by the number specified, I say this because I saw that after 'z' special characters like '|' appear and that is fine by me. This is my first app and could really use some help. The error is at line 47 and 61.
Here is my code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity
{
EditText input;
EditText output;
EditText num;
String inp;
String out;
int choice;
Character c;
Button enc, dec;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.input);
output= (EditText) findViewById(R.id.output);
num = (EditText) findViewById(R.id.num);
enc = (Button) findViewById(R.id.enc);
dec = (Button) findViewById(R.id.dec);
enc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)+choice);
}
}
});
dec.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v1)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)-choice);
}
}
});
}
}

Building on #corsiKa's answer, I suggest the following. First, convert your input string into a char[]:
char[] array = inp.toCharArray();
Now you can iterate over the array and modify its contents:
array[i] = array[i] + choice;
And, at the end, you can build your output string from that array:
output.setText(new String(array));

I believe your first problem is here:
inp.charAt(i)= (char) (inp.charAt(i)+choice);
You are trying to assign a value to a method return. This is not possible in Java.
Strings are immutable in Java - if you'd like to replace a value in a String, you must build a new String and resassign the reference that points to the old String to instead point to the new String.
There may be other issues that I have not had a chance to get to, but I believe this is the real issue. I don't fully understand what you're trying to do, so unfortunately I can't make a suggestion for what you should use instead.

Related

how to get next item in ArrayList in java

i followed a YouTube tutorial about programming a quiz app using java android studio
in the tutorial you put the question in array list then you get randomly question from it
this can cause a problem of getting the same question many time.
How can i fix that? i thought about instead of using random i use a function to get the next item in the list but it didn't work for me.
Yhis is my code
package com.example.quiz20;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView questionTV,questionNumberTV;
private Button option1Btn,option2Btn,option3Btn,option4Btn;
private ArrayList<QuizModel> quizModelArrayList;
Random random;
int currentScore = 0 , questionAttempted = 0, currentPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTV= findViewById(R.id.idTVQuestion);
questionNumberTV=findViewById(R.id.idTVQuestionAttempted);
option1Btn=findViewById(R.id.idBtnOption1);
option2Btn=findViewById(R.id.idBtnOption2);
option3Btn=findViewById(R.id.idBtnOption3);
option4Btn=findViewById(R.id.idBtnOption4);
quizModelArrayList = new ArrayList<>();
random = new Random();
getQuizQuestion(quizModelArrayList);
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
option1Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option1Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option2Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option2Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option3Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option3Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option4Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option4Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
}
private void showBottomSheet(){
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MainActivity.this);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.score_bottom_sheet,(LinearLayout)findViewById(R.id.idLLScore));
TextView scoreTV = bottomSheetView.findViewById(R.id.idTVScore);
Button restartQuizBtn = bottomSheetView.findViewById(R.id.idBtnRestart);
scoreTV.setText("you score is \n"+currentScore + "/4");
restartQuizBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
questionAttempted = 0;
currentScore = 0;
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.setCancelable(false);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
private void setDataToViews(int currentPos){
questionNumberTV.setText("Question Attempted : "+questionAttempted + "/4");
if(questionAttempted == 4){
showBottomSheet();
}else {
questionTV.setText(quizModelArrayList.get(currentPos).getQuestion());
option1Btn.setText(quizModelArrayList.get(currentPos).getOption1());
option2Btn.setText(quizModelArrayList.get(currentPos).getOption2());
option3Btn.setText(quizModelArrayList.get(currentPos).getOption3());
option4Btn.setText(quizModelArrayList.get(currentPos).getOption4());
}
}
private void getQuizQuestion(ArrayList<QuizModel> quizModelArrayList) {
quizModelArrayList.add(new QuizModel("in which year google released?","1998","2000","2004","1995","1998"));
quizModelArrayList.add(new QuizModel("What does CPU stand for?","Core Processing Unit","Central Processing Unit","Command Processing Unit","Custom Processing Unit","Central Processing Unit"));
quizModelArrayList.add(new QuizModel("what is the name of the first internet search engine?","Google","Yahoo","AOL","Archie","Archie"));
quizModelArrayList.add(new QuizModel("Which Programming language is the most widely used?","JavaScript","JAVA","Python","PHP","JavaScript"));
}
}
To avoid getting the same selection multiple times, you may want to remove it from the list after it was chosen. The syntax could look something like this:
Random rand = new Random();
ArrayList <Type> list = new ArrayList<>();
int selection = rand.nextInt(list.size() + 1);
switch(selection)
{
case X:
do the X stuff;
list.remove(X);
break;
}
The ArrayList knows what index X is at, so calling it by name will remove the entry. Using the size of the ArrayList to create the bounds for Random numbers also helps keep it dynamic
NOTE this is NOT complete code
Information/examples about preserving contents of the ArrayList using list.clone()
https://www.tutorialspoint.com/clone-an-arraylist-in-java -- An ArrayList can be cloned using the java.util.ArrayList.clone() method. This method does not take any parameters but returns a shallow copy of the specified ArrayList instance. This means that the new ArrayList created using the ArrayList.clone() method refers to the same elements as the original ArrayList but it does not duplicate the elements.
If you want to maintain a list of questions, and then some method of identifying if those have been asked, there are multiple ways to do this.
You could add a boolean value inside QuizModel which holds whether the question has been asked or not in this round, and part of the process to starting a new round of the quiz would be to ensure they are all set to false. The value can be set to true when that question has been asked, and you'd check that value before deciding to use this question or getting another.
Alternatively, you could make the problem less specific to your usecase and more generalised. - for example, all you're really asking is how to get a random number, from a set of numbers, minimising the possibility of duplicates. This is a common software problem that has been solved many many times before.
see Creating random numbers with no duplicates for example. Then you could work this solution into your question selection code.
there are two ways to get the next item in the list:
Using the index:
list.get(list.indexOf(item)+1);
list - your list of questions
item - current question
use LinkedList and its methods
You can drop the question from the array list and make the random number 1 smaller each time. You have to make sure the list can be reset and is automatically reset when it gets to 0 if you do this.

Simple Encrypt Decrypt String with array in Android

My problem seems easy, I am trying to encrypt a string in android.
What the program should do
The objective of the program is, put a word or a letter in textbox1, click on button encrypt and textbox2 should to show the symbol in the same position in second array of the letter that you put in.
For example I write letter A (array 1 [0]) must show symbol $ (array 2 [0]) if a click on ENCRYPT button, if I put a symbol and click on DECRYPT must show the letter which is equivalent in position of array
Need help. Sorry for grammar and edit question, first time and no English speaker, i tried to make it more simple.
Arreglo Class, just for declare 2 arrays.
package PaqueteArreglo;
public class Arreglo {
public String [] encrypt = new String[3];
public String [] decrypt = new String[3];
}
Main Activity
package com.example.encrypt;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import PaqueteArreglo.Arreglo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//Instance the class with the arrays
PaqueteArreglo.Arreglo ins = new Arreglo();
public Button button1,button2;
public EditText text1, text2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
ins.encrypt[0] = "a";
ins.encrypt[1] = "b";
ins.encrypt[2] = "c";
ins.decrypt[0] = "$";
ins.decrypt[1] = "%";
ins.decrypt[2] = "&";
}
private void initialize(){
text1 = (EditText)findViewById(R.id.txtWord);
text2 = (EditText)findViewById(R.id.txtResult);
button1 = (Button)findViewById(R.id.btnEncrypt);
button1.setOnClickListener(this);
button2 =(Button)findViewById(R.id.btnDecrypt);
button2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String word = String.valueOf(this.text1.getText());
if (view.getId() == R.id.btnEncrypt)
{
String demo = "";
int lon = 0;
lon = word.length();
for (int i = 0; i < lon; i++ )
{
if (ins.encrypt[i].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[i];
text2.setText(demo);
}
}
}
}
}
There are two solutions to your problem using two different approach:
1- Using your defined structure (which is not optimized by the way) you need to put two nested loop for checking:
for (int i = 0; i < lon; i++ )
{
for(int j = 0; j<ins.encrypt.length;j++)
{
if (ins.encrypt[j].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[j];
}
}
}
text2.setText(demo);
2- Using much better data structure like HashMap:
Change your Arreglo to the following:
public class Arreglo {
public HashMap<Character, Character> encrypt = new HashMap<>();
public HashMap<Character, Character> decrypt = new HashMap<>();
}
Now change the way you add your data like:
ins.encrypt.put('a','#');
ins.decrypt.put('#','a');
...
and finally do the encryption like:
for (int i = 0; i < lon; i++ )
{
demo = demo + ins.encrypt.get(word.charAt(i));
}
text2.setText(demo);
The second implementation is more efficient

if statement to match users input to string answer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm doing a word shuffle app on android studio for a class project. I need help understanding how I can get the users input and match it to the correct String answer. I tried a few approaches and have fallen short. I tried using an if(word.equals(userAnswer)) statement but having a hard time understanding it. How can I write the if statement for text input/output to match my answer in android studio?
(Optional question) Also is public void OnClick(View v) a good approach or should I go with something else?
Any help will be greatly appreciated. Thanks in advance!
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
public void OnClick(View v){
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
Button button = (Button) v;
String word = "Animals"; // scan for word
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
String shuffledWord = new String(shuffled);
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
This will allow you to determine if they are the same
if(word.equalsIgnoreCase(userAnswer.getText().toString())) {
answerOutput.setText("Correct");
}
However, generally speaking you have a much larger problem, unless it's in code somewhere that you aren't showing us.
Somewhere in your activity onCreate/onStart you want to initialize your button with whatever view it might be.
Button checkAnswer = (Button) findViewById(//whatever your id is)
Then you want to set the onClick listener of the button. With the approach that you are using, it would end up needing two things. First this
public class MainActivity extends Activity implements View.OnClickListener {
Then in you need to set the onClick listener to your Button, probably in OnCreate.
checkAnswer.setOnClickListener(this);
Then your onClick would look something like
#Override
public void onClick(View v) {
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
}
else {
answerOutput.setText("Sorry try again.");
}
}
The logic for scrambling the word etc, probably wouldn't be in onClick here.
Also, if you have multiple things you want to set click listeners for you would do something like this
#Override
public void onClick(View v) {
switch(v.getId()) {
case(R.id.//whatever): {
//dosomething
break;
}
}
}
Where you can multiple cases for all of the views that you have set the MainActivity to handle.
Edit: Since you updated your code
public class MainActivity extends Activity implements View.OnClickListener {
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
private String word;
private String shuffledWord;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
createWord();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
private void createWord() {
word = "Animals";
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
shuffledWord = new String(shuffled);
shuffledText.setText(shuffledWord);
}
#Override
public void OnClick(View v){
if (word.equalsIgnoreCase(userAnswer.getText().toString())){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
Did you set the onClickListener of the button to your MainActivity?
Your MainActivity should implement OnClickListener too
You need to use userAnswer.getText() to get the answer. Your userAnswer variable currently is of type EditText, which means a check to see if word.equals(userAnswer) will always return false, as they are of different types. Instead, try word.equals(userAnswer.getText()) to check if their answer equals the original word. To check if their answer equals the scrambled word, use shuffledWord.equals(userAnswer.getText()).

Retain Values from edit boxes android code

I have this code, I want to retain my value of the editbox from the first input after change or start of new activity.
this what happens in this code:
editbox1 = 1 > start new activity > back to recent activity > editbox1 = null
I need this to happened:
editbox1 = 1 > start new activity > back to recent activity > editbox1 = 1
CODE
package org.example.touch;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.EditText;
public class SettingsClass extends Activity {
private EditText Alpha;
private EditText Beta;
private EditText Charlie;
private EditText Delta;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Alpha = (EditText) findViewById(R.id.editText1);
Beta = (EditText) findViewById(R.id.editText2);
Charlie = (EditText) findViewById(R.id.editText3);
Delta = (EditText) findViewById(R.id.editText4);
}
public void buttonSBHandler (View view){
String Aint = Alpha.getText().toString();
String Bint = Beta.getText().toString();
String Cint = Charlie.getText().toString();
String Dint = Delta.getText().toString();
Intent startNewActivityOpen = new Intent(SettingsClass.this, GameUi.class);
startNewActivityOpen.putExtra("Aint", Aint);
startNewActivityOpen.putExtra("Bint", Bint);
startNewActivityOpen.putExtra("Cint", Cint);
startNewActivityOpen.putExtra("Dint", Dint);
startActivityForResult(startNewActivityOpen, 0);
//startActivity(new Intent(view.getContext(), GameUi.class));
}
}
1)One thing is that you can go with shared preference store your value in shared preference and on oncreate() method first check whether shared preference is null or not if it is not null than get the value from shared preference.
or
2)Just make those data of edit text as static like-
static String Aint = Alpha.getText().toString();
static String Bint = Beta.getText().toString();
static String Cint = Charlie.getText().toString();
static String Dint = Delta.getText().toString();
so whenever you will come back to the activity so the previous data of the edit text will be shown there.
hope these thing will work for you perfectly.
thanks

Comparing strings in Java

Im trying to compare the values of two edittext boxes. What i would like is to just compare passw1 = passw2. As my code is now comparing two strings i have entered as i could not get to compare them.
final EditText passw1= (EditText) findViewById(R.id.passw1);
final EditText passw2= (EditText) findViewById(R.id.passw2);
Button buttoks = (Button) findViewById(R.id.Ok);
buttoks.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (passw1.toString().equalsIgnoreCase("1234") && passw2.toString().equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplication(),"Username and password doesn't match", Toast.LENGTH_SHORT).show();
}
} });
Using the == operator will compare the references to the strings not the string themselves.
Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.
String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();
if (passwd1Text.equals(passwd2Text))
{
}
[EDIT]
I made a mistake earlier, because, to get the text, you need to use .getText().toString().
Here is a full working example:
package com.psegina.passwordTest01;
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.LinearLayout;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener {
LinearLayout l;
EditText user;
EditText pwd;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
l = new LinearLayout(this);
user = new EditText(this);
pwd = new EditText(this);
btn = new Button(this);
l.addView(user);
l.addView(pwd);
l.addView(btn);
btn.setOnClickListener(this);
setContentView(l);
}
public void onClick(View v){
String u = user.getText().toString();
String p = pwd.getText().toString();
if( u.equals( p ) )
Toast.makeText(getApplicationContext(), "Matches", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), user.getText()+" != "+pwd.getText(), Toast.LENGTH_SHORT).show();
}
}
Original answer (Will not work because of the lack of toString())
Try using .getText() instead of .toString().
if( passw1.getText() == passw2.getText() )
#do something
.toString() returns a String representation of the whole object, meaning it won't return the text you entered in the field (see for yourself by adding a Toast which will show the output of .toString())
In onclik function replace first line with this line u will definitely get right result.
if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){
You can compare the values using equals() of Java :
public void onClick(View v) {
// TODO Auto-generated method stub
s1=text1.getText().toString();
s2=text2.getText().toString();
if(s1.equals(s2))
Show.setText("Are Equal");
else
Show.setText("Not Equal");
}
You need both getText() - which returns an Editable and toString() - to convert that to a String for matching.
So instead of: passw1.toString().equalsIgnoreCase("1234")
you need passw1.getText().toString().equalsIgnoreCase("1234").
ou can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}
Try to use .trim() first, before .equals(), or create a new String var that has these things.
did the same here needed to show "success" twice
response is data from PHP
String res=response.toString().trim;
Toast.makeText(sign_in.this,res,Toast.LENGTH_SHORT).show();
if ( res.compareTo("success")==0){
Toast.makeText(this,res,Toast.LENGTH_SHORT).show();
}
String password=passw1.trim();
if (password.equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
You need to use the trim method in the String

Categories