Okay so I have this code that I wrote for an Android App personality quiz in Android studio. My GUi window works correctly and it correctly links to my phone and looks good. However, when i click the submission button(upload to the force) a different picture does not show up like it should when I enter the correct responses. I know it isnt a problem with my pictures since if I take the ImageSetter out of the switch case it appears in the App. So the conclusion I have come to is that somehow my code for reading in the text from the EditText field box int he GUI window is not right or I am building the list of letters to check wrong. (Yes I know putting it in an arraylist just to make it into a string is redundant however I was doing it the first way I thought of. Any suggestions Ive spent hours on this and cant think of what is going wrong?? You guys are the best I appreciate it.
`
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText nameTxt, answer2, answer3, answer4, answer5, answer6, answer7, answer8;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageview = (ImageView)findViewById(R.id.showCharacter);
//have to cast it into type (EditText) since by default is is a GUI container and an error
//will be generated if you do not again specify that the container is type EditText
nameTxt = (EditText) findViewById(R.id.inputA1);//links nameTxt to GUI editText field
answer2 = (EditText) findViewById(R.id.inputA2);//links nameTxt to GUI editText field
answer3 = (EditText) findViewById(R.id.inputA3);//links nameTxt to GUI editText field
answer4 = (EditText) findViewById(R.id.inputA4);//links nameTxt to GUI editText field
answer5 = (EditText) findViewById(R.id.inputA5);//links nameTxt to GUI editText field
answer6 = (EditText) findViewById(R.id.inputA6);//links nameTxt to GUI editText field
answer7 = (EditText) findViewById(R.id.inputA7);//links nameTxt to GUI editText field
answer8 = (EditText) findViewById(R.id.inputA8);//links nameTxt to GUI editText field
ArrayList<String> responses = new ArrayList<String>();//string array to hold temp responses
String respStr = "";//used for comparison to the answer key since it is easier than using an
//arraylist for comparison.
String character = "";// honestly this doesnt output anything or do anything except help me
//keep track of which key corresponds to which picture so I dont get confused
//creates a new button called addBtn and likes it to the GUI button btnAdd
final Button addBtn = (Button) findViewById(R.id.btnAdd);
if (addBtn != null) {//designed to not allow the submission button to be clickable unless
//the first field is filled out
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Using the Force", Toast.LENGTH_SHORT).show();
}
}) ;
}
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
addBtn.setEnabled(String.valueOf(nameTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
//takes the input of the first question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant wway to ensure that input from the
//user can be either upper or lower case.
String q1S = "";
q1S = nameTxt.getText().toString();
q1S = q1S.trim().toLowerCase();
if (q1S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q1S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q1S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q1S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q1S.equalsIgnoreCase("e")){
responses.add("e");
}
for(int i =0; 0>responses.size(); i++){
respStr += responses.get(i);
}
//takes the input of the second question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant wway to ensure that input from the
//user can be either upper or lower case.
String q2S = "";
q2S = nameTxt.getText().toString();
q2S = q2S.trim().toLowerCase();
if (q2S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q2S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q2S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q2S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q2S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the third question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q3S = "";
q3S = nameTxt.getText().toString();
q3S = q3S.trim().toLowerCase();
if (q3S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q3S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q3S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q3S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q3S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the fourth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q4S = "";
q4S = nameTxt.getText().toString();
q4S = q4S.trim().toLowerCase();
if (q4S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q4S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q4S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q4S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q4S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the fifth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q5S = "";
q5S = nameTxt.getText().toString();
q5S = q5S.trim().toLowerCase();
if (q5S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q5S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q5S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q5S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q5S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the sixth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q6S = "";
q6S = nameTxt.getText().toString();
q6S = q6S.trim().toLowerCase();
if (q6S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q6S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q6S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q6S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q6S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the seventh question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q7S = "";
q7S = nameTxt.getText().toString();
q7S = q7S.trim().toLowerCase();
if (q7S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q7S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q7S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q7S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q7S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the eigth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q8S = "";
q8S = nameTxt.getText().toString();
q8S = q8S.trim().toLowerCase();
if (q8S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q8S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q8S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q8S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q8S.equalsIgnoreCase("e")){
responses.add("e");
}
//imageview.setImageResource(R.drawable.sidious);
switch(respStr){
case "aabaacaa":
character ="Sideous";
imageview.setImageResource(R.drawable.sidious);
break;
case "abdbadaa":
character ="Maul";
imageview.setImageResource(R.drawable.maul);
break;
case "aadccdab":
character ="Vader";
imageview.setImageResource(R.drawable.vader);
break;
case "bbbdcaaa":
character ="Boba Fett";
imageview.setImageResource(R.drawable.boba);
break;
case "abeeadba":
character ="Grevous";
imageview.setImageResource(R.drawable.grievous);
break;
case "aaacbabb":
character ="Windu";
imageview.setImageResource(R.drawable.windu);
break;
case "abacbbbb":
character ="Obi-Won-Kenobi";
imageview.setImageResource(R.drawable.kenobi);
break;
case "bacbcaab":
character ="Solo";
imageview.setImageResource(R.drawable.solo);
break;
case "bbaccaba":
character ="Clone";
imageview.setImageResource(R.drawable.trooper);
break;
case "aacbbabb":
character ="Anakin";
imageview.setImageResource(R.drawable.anakin);
break;
default:
character = "R2D2";
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
`
your for loop have a wrong condition.
your code:
for(int i =0; 0>responses.size(); i++){
respStr += responses.get(i);
}
should be:
for(int i=0; i<responses.size(); i++){
respStr += responses.get(i);
}
Related
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
input.useDelimiter(".");
String given = input.next();
System.out.println(given);
}
}
When I run the above code and type in asdf. then enter, I get nothing.
It works fine with "," ";" "\"" "\\\\" or whatever, but just not with "."... So is there something about a dot or is it just a problem with Eclipse IDE or whatever?
Scanner is using regular expression (regex) as delimiter and dot . in regex is special character which represents any character except line separators. So if delimiter is any character when you write asdf. each of its character will be treated as delimiter, not only dot. So each time you will use next() result will be empty string which exists in places I marked with |
a|s|d|f|.
To create dot literal you need to escape it. You can use \. for that. There are also other ways, like using character class [.].
So try with
input.useDelimiter("\\.");
/This could be another helpful example, that how the use of Delimeter?
The scanner detects DOTs in any string then it will simply separate and store the string data in ArrayList by the help of any LOOP./
/If it is helped Hit the UP button./
public class MainActivity extends AppCompatActivity {
EditText et_ip_address;
TextView txt_1st;
TextView txt_2nd;
TextView txt_3rd;
TextView txt_4th;
Button btn_getResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_getResult = findViewById(R.id.button);
et_ip_address = findViewById(R.id.et_ip_address);
txt_1st = findViewById(R.id.txt_1st);
txt_2nd = findViewById(R.id.txt_2nd);
txt_3rd = findViewById(R.id.txt_3rd);
txt_4th = findViewById(R.id.txt_4th);
final ArrayList data = new ArrayList();
//Click on this button execute the code to separate Strings
btn_getResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.clear();
Scanner fromString = new Scanner(et_ip_address.getText().toString());
fromString.useDelimiter("\\."); //this is how we should use to detects DOT
while(fromString.hasNext()){
String temp = fromString.next();
data.add(temp);
}
txt_1st.setText(data.get(0).toString());
txt_2nd.setText(data.get(1).toString());
txt_3rd.setText(data.get(2).toString());
txt_4th.setText(data.get(3).toString());
}
});
}
}
So I have to write a program that prompts the user to enter a password that has to follow three requirements: at least 8 characters long, only letters and digits, and at least two digits. Now the method I created to check these three requirements I believe is sound, but my program also has to do some exception handling and be able to ask the user to reenter the password if one of the requirements is off and display the respective error message to go along with each requirement. I created a string errorMessage to relay that message but it gives me an error when i try to call it in my main ?
My other issue is that the password must be taken in to my program by using JPasswordField but I am struggling with even setting it up because of the numerous other factors like the JPanel, buttons, and action events that I read has to go along with it. I attempted to use JPasswordField and noticed that the line that takes in the password, takes it in as an array, when my checkPassword method needs a string, how can i take in that password as a string instead?
This is what I have for my program so far:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javafx.event.ActionEvent;
public class Ed10Chp6Ex6Point18CheckPasswordProgram {
public static void main(String[] args) {
final JFrame frame = new JFrame("Check Password Program");
JLabel jlbPassword = new JLabel("Please enter the password: ");
JPasswordField jpwName = new JPasswordField(15);
jpwName.setEchoChar('*');
jpwName.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char[] password = input.getPassword();
if(checkPassword(password)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
}
else{
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
}
}
public static boolean checkPassword(String x) {
String errorMessage = "";
//must have at least eight characters
if (x.length() < 8){
errorMessage = "The password you entered is invalid, password must be at least 8 characters";
return false;
}
//consists of only letters and digits
for (int i = 0; i < x.length(); i++) {
if (!Character.isLetter(x.charAt(i)) && !Character.isDigit(x.charAt(i))) {
errorMessage = "The password you entered is invalid, password must contain only letters and digits";
return false;
}
}
//must contain at least two digits
int count = 0;
for (int i = 0; i < x.length(); i++) {
if (Character.isDigit(x.charAt(i))){
count++;
}
}
if (count >= 2){
return true;
}
else {
errorMessage = "The password you entered is invalid, password must contain at least two digits";
return false;
}
}
}
I apologize in advanced in case some of my questions seem rudimentary, any help would be greatly appreciated, thank you!
Two things right off the bat:
(1) Make sure you are importing the correct classes, don't rely on an IDE to do proper imports. You are importing the ActionEvent class from JavaFX, but the framework you are working with is Swing.
Change
import javafx.event.ActionEvent;
To
import java.awt.event.ActionEvent;
I am not very familiar with how nicely JavaFX and Swing play with one another, but using the correct classes typically helps avoid headaches and compile/runtime errors.
(2) A static method in the java.lang.String class provides a convenient way to convert a char array into a string. In your actionPerformed method, add this:
String passStr = String.valueOf(password);
E.g.
#Override
public void actionPerformed(ActionEvent e) {
// Get the source of the event, we know it is a JPasswordField so we cast it.
JPasswordField input = (JPasswordField) e.getSource();
// Get the char array from the input the user typed stored in the input object.
char[] password = input.getPassword();
// Convert char[] to String
String passwordStr = String.valueOf(password);
if(checkPassword(passwordStr)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
} else {
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
how can i take in that password as a string instead
Either checkPassword(new String(input.getPassword)) or update your method to accept a char[] instead of a String.
As for error checking, you should use throw new ShortPasswordException(), where you want to throw that error, after you implement a class like ShortPasswordException extends Exception, for example.
Then, you can do
try {
checkPassword();
} catch (ShortPasswordException e) {
// TODO: Handle exception
}
Tip for the more adventurous: Use a regular expression to check your password requirements. A match of \d{2}, for example, means you have 2 consecutive digits.
I want to create a program that has the capability to check a string if it is valid to be as a person's name. But I am struggling to use regular expression for validating the string if its acceptable to be a person's name or not. Can you help me to implement the right conditions in my code? A string will be considered as a person's name if the following conditions are fulfilled:
no space before first word
no non-word character
no 2 or more consecutive spaces
I would also like to remove a space if it exists after the last word in my string. I am doing all of this just to force a user to input the right format of text that I will post soon on my JSON. That's why everything should be validated at the first place. No problem about whitespaces because I already defined the right inputType of my EditText on my XML file.
This is the code that I tried to implement:
public boolean isFirstnameValid(String regex, String text){
Pattern checkRegex = Pattern.compile(regex);
Matcher regexMatcher = checkRegex.matcher(text);
while(regexMatcher.find()){
if(regexMatcher.group().length()!=0){
Log.e("searched",regexMatcher.group().trim());
}
}
return false;
// I returned false because, I'm still confused about what conditions should I implement.
}
This is the main method where my actual parameter is implemented:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// String firstname = "Kirby Aster";
// String lastname = "Abadilla";
et =(EditText) findViewById (R.id.editText1);
b = (Button) findViewById (R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String text = et.getText().toString();
isFirstnameValid("[A-Za-z]{1,}", text);
}
});
}
I don't like the implementation of isFirstnameValid method. I think you are making it a bit complex than it should be. I would use simple String.matches to do the job, eg :
public boolean isFirstnameValid(String text){
return text..matches("^([A-Za-z]+)(\\s[A-Za-z]+)*\\s?$");
}
The above regex meets all your conditions including allowing a space at the end. You may consider another condition of capital letter at the first of each word(regex will change a little). Then call it like :
if( isFirstnameValid(text) ){
text = text.trim();
} else {
// define your failing condition here
}
If you have any query feel free to ask.
I am a newbie Android Developer. I am trying to get a text input from user using and Edittext box and then convert that text into string and then into a char array of size 4. i have an array already stored that is of size 4 and it contains values. i want to compare both the arrays and perform a task based on the result.
I don't know why am i getting the ArrayIndexOutOfBoundsExecption
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newgame);
Button submit = (Button) findViewById(R.id.guess);
EditText guess = (EditText) findViewById(R.id.editText1);
boolean c=false;
char[] guessword;
char[] appword = {'T', 'R', 'U', 'E'};
guessword = guess.getText().toString().toCharArray();
for(int i=0;i<appword.length;i++)
{
if(guessword[i]==appword[i])
{
c=true;
}
else
{
c=false;
}
}
final boolean correct=c;
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(correct){
startActivity(new Intent(Newgame.this, Win.class));
}
else{
startActivity(new Intent(Newgame.this, Loose.class));
}
}
});
}
}
The problem is that guessword may have fewer than four characters, and your code does not check for that condition.
Change your code as follows to account for this condition:
for(int i=0;i<appword.length;i++)
{
if((i < guessword.length) && (guessword[i]==appword[i]))
{
c=true;
}
else
{
c=false;
break; // <<<=== Add this to end the loop
}
}
Also note that your code as written does not "lock in" the false when characters are not equal to each other: for example, {'A','B','Z'} and {'X', 'Y', 'Z'} will compare equal under your old algorithm. Add break to exit the loop as soon as you see a false.
This is because you are going with the index from 0 to the value of the appword.
Take for example the case in which the user types in: "NO". Because you are iterating over appword which has the length greater than your actual text, when you do a guessword[i] it will crash throwing your IndexOutOfBoundsException.
I am not sure why you are using char[]. As I can see, for your example, String could solve the problems.
String appword = "TRUE";
String guessword = guess.getText().toString();
Then, the method that shows if the 2 are equal is :
if (appword.equals(guessword))
If you also want to match the case, use equalsIgnoreCase instead.
guessword is null when you walk over the first time (which happens in the onCreate). One thing you could do is change
if(guessword[i]==appword[i])
to
if(guessword != null && guessword.length =< i && guessword[i]==appword[i])
If you just want to compare the entered text to "TRUE", you can simply do:
String guessword = guess.getText().toString();
if ("TRUE".equals(guessword)) {
...
}
I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it.
Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml
You need to do if("".equals(text9.getText().toString())) { ...
The toString() is there because the TextView will return a CharSequence which may or may not be a String.
Right now you are comparing the TextView itself to "", and not the String it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}
Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText() from a TextView and not equals a String with a TextView.
One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.