how i can use this form 000-00-000 to input - java

the question
write a program that reads in a line consisting of a student's name, social security number, user ID, and password(separat by one space). The program outputs the string in which all digits of the social security number, and all the characters in the password are replaced by x.( The social security number is in the form 000-00-000, and the user ID and password do not contain any spaces,and the name does not contain any digits.)
for example
input :the user input : jimin 222-11-222 jimin22 jim2000
explanation: jimin is the name of user -should not contain any digits-
222-11-22 is social security number in form "000-00-000"
jimin22 is the user id
jim2000 is the user password
the output shoud be like
output: jimin xxx-xx-xxx jimin22 xxxxxxx
i dont know how the name making it without digits
and i dont know how output the social security number in form "000-00-000"
Scanner input=new Scanner(System.in);
String name,So_n,ue_id,password;
int x;
////to input
name=input.next();
So_n=input.next();
ue_id=input.next();
password=input.next();
///to output
System.out.print(name+"\t");
x = So_n.length();
for(int i=0;i<x;i++){
System.out.print("x"); }
System.out.print("\t");
System.out.print(ue_id+"\t");
x = password.length();
for(int i=0;i<x;i++){
System.out.print("x"); }

It seems that crux of the issue is to replace characters rather than just printing out some 'X' ones. Therefore, an approach that handles replacement would be most appropriate.
Here are a couple of sample methods that could address the OP's question. Additional methods to validate the user name, the password in terms of whatever complexity, etc., can be easily added. No details were provided on what to do in the event of an invalid input, so the one case here merely puts out a message.
// for a non-null password, return a String of the same length with all
// of the characters set to an 'X'
public static String getObfuscatedPassword(String pw)
{
Objects.requireNonNull(pw, "Null pw input");
return pw.replaceAll(".", "X");
}
// for a non-null ssn, return a String where every digit is replaced
// by an 'X'; other characters (such as a -) are unchanged
public static String getObfuscatedSSN(String ssn)
{
Objects.requireNonNull(ssn, "Null ssn input");
return ssn.replaceAll("[0-9]", "X");
}
// return true if the specified ssn is not null and
// matches the format of ###-##-###
public static boolean isValidSSN(String ssn)
{
// ensures there is something for us to validate
// NOTE: technically the .isEmpty is not needed
if (ssn == null || ssn.isEmpty()) {
return false;
}
// ensure in the format of ###-##-###
return Pattern.matches("[\\d]{3}-[\\d]{2}-[\\d]{3}", ssn);
}
// returns true if the username has at least one character, and
// no digits; does not prevent having spaces in the name (could
// be added); uses a for loop rather than regular expressions for
// a fun difference in approach
public static boolean isValidUsername(String name)
{
boolean charFound = false;
boolean digitFound = false;
if (name == null || name.isEmpty()) {
return false;
}
for (int i = 0; i < name.length(); ++i) {
// check if the current name[i] is a letter or digit
// the OR will keep a true once it is set
charFound = charFound || Character.isLetter(name.charAt(i));
digitFound = digitFound || Character.isDigit(name.charAt(i));
}
return charFound && ! digitFound;
}
Driver example:
public static void main (String[] args) throws java.lang.Exception
{
String user = "jimin";
String ssn = "222-11-222";
String password = "WhatAWonderfulWorldItWouldBe";
if (! isValidSSN(ssn)) {
System.err.println("Invalid SSN");
}
String xdSsn = getObfuscatedSSN(ssn);
String xdPw = getObfuscatedPassword(password);
System.out.printf("%12s\t%s\t%s%n", user, xdSsn, xdPw);
}
Sample Output:
jimin XXX-XX-XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Using better variable names would be a good thing.
Some online example at: https://ideone.com/cPV2ob

To replace the digits in the SSO:
x = So_n.length();
for (int i = 0; i < x; i++) {
if ('0' <= So_n.charAt(i) && So_n.charAt(i) <= '9') {
System.out.print("x");
} else {
System.out.print(So_n.charAt(i));
}
}

Related

The user must enter a string that contains at least one lowercase “a”

The user must do the question above or the question keeps repeating so I need a while loop. I need to do this using a subroutine too. My code below isn't working.
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
This is the second part:
System. out.print ("Please enter a string that contains at least one lowercase a. ");
String name = input.next ();
if (isAlpha(name)) {
System.out.println("That is a valid string onto stage 2.");
}
else {
System.out.println("That is an invalid string. Try again.");
}
You're passing a String to the isAlpha method, which iterates over the String and checks each letter to be 'a' or not. You're returning false for every char that isn't 'a', and returning false if you iterate through the entire String.
An easier way to handle this would be to return true upon finding the first 'a', or returning false after iterating over the entire String. It will make scaling easier as well if you reduce the number of return statements in a single method.
Here are three different ways to check whether a string contains at least one lowercase a. The first way uses a for loop as you have tried to do in the code in your question.
The second way uses regular expressions and the last way uses streams.
The code also contains a main method which contains a while loop as requested in your question.
do the question above or the question keeps repeating
import java.util.Scanner;
public class Solution {
public static boolean isAlpha(String name) {
/* Using a loop. */
char[] chars = name.toCharArray();
for (char ch : chars) {
if (ch == 'a') {
return true;
}
}
return false;
/* Using regular expression. */
// return name.matches("^.*a.*$");
/* Using stream API. */
// return name.chars()
// .filter(c -> c == 'a')
// .findFirst()
// .isPresent();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a string that contains at least one lowercase 'a': ");
String str = input.nextLine();
while (!isAlpha(str)) {
System.out.println("That is an invalid string. Try again.");
str = input.nextLine();
}
System.out.println("That is a valid string. On to stage 2.");
}
}
Here is a sample run:
Please enter a string that contains at least one lowercase 'a': 1 is the lonliest number.
That is an invalid string. Try again.
2 can be as bad as 1
That is a valid string. On to stage 2.
A couple of mistakes were made. Firstly, your method only returns false, there is no way in which it could be true. Secondly, your code here loops through the entire array for every single character.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
Try this instead.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for(char c : chars) {
if(c=='a') {
return true;
}
}
return false;
}

How to compare 2 strings if they have spaces?

I'm having some problem with a simple program I'm working on, I just need to ask the user if he wants the regular price or the sale price. And he needs to respond in a string value. Now I know that I just have to use if(price.equals("sale") == true). But the problem comes if I want the user to type something that has spaces in the words, example: if(price.equals("regular price") == true) when I the user types in "regular price" I don't get a response I wanted.
I'm also learning Java by the way.
You can determine if a string contains a word like this:
if (price.toLowerCase().contains("regular"))
If you want to get fancy, you can use regex to match a whole word (eg not "irregular"):
if (price.matches("(?i).*\\bregular\\b.*"))
java equals() method/function works perfectly with the spaces too. Also you don't need to compare the result with true/false. If two string is equal then equals() will automatically return true else it will return false.
public class MyClass {
public static void main(String args[]) {
String a = "A B C";
if(a.equals("A B C")){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
I tested the following program and it returned true while the string has spaces in it.
You want to compare strings with spaces right?
Then you can first compare their lengths, then
If string contains space split it by it, again compare lengths, next check every string.
If it not contains space, just use equals once, here what i come up with:
class cmp {
public static void main(String[] args) {
String s = "test some";
String s2 = "test some";
String s3 = "test not";
String s4 = "testxsome";
System.out.println(cmpStr(s,s2)); // True
System.out.println(cmpStr(s,s3)); // False
System.out.println(cmpStr(s,s4)); // False
}
public static boolean cmpStr(String str1, String str2) {
if (str1.length() != str2.length()) {
System.out.println("Length mismatch.");
return false;
}
if (str1.contains(" ") || str2.contains(" ")) {
String[] a1 = str1.split(" ");
String[] a2 = str2.split(" ");
if (a1.length != a2.length) {
System.out.println("Split Length mismatch.");
return false;
}
for (int i = 0; i < a1.length; i++) {
if (!a1[i].equals(a2[i])) {
System.out.println("One of split mismatch." + a1[i] + " " + a2[i] );
return false;
}
}
} else {
if (!str1.equals(str2)) {
System.out.println("Regular equals returns false.");
return false;
}
}
return true;
}
}
Here I see three methods
Remove all the spaces and hidden characters from the string and check
String input = "regular price";
input = input.replaceAll("\\s+","");
if(price.equals(input))
{
//your code here
}
Check whether the word contains keywords
if (price.toLowerCase().contains("regular"))
Create a regular expression to match your words

Get result from for loop and add it to another variable for every iteration

I have an assignment where I am supposed to write a program that can encrypt and decrypt a word the user enters, using an "encryption key" they enter. What I want to do is to check the value of every letter in the key the enter, compared to the alphabet (eg: a = 1, b = 2, c = 3) and then add the value of the letters, which will then be used to shift the characters in the word they assign.
This is the code I have for my assignment so far:
/* Validity Check from http://stackoverflow.com/questions/33965542/password-check-program-checking-capitals-lowercase-letters-digit-and-special
*
*
*
*
*/
import java.util.*;
public class SecretDecoderFinal
{
public static void main (String [] args)
{
optInput();
}
public static int optInput()
{
int opt = 0;
do {
String word = "";
String key = "";
System.out.println("Welcome to Seegson Security secure transmission terminal");
System.out.println("");
System.out.println("Enter an option for the terminal");
System.out.println("(1) to encrypt a word");
System.out.println("(2) to decrypt a word");
System.out.println("(0) to exit the terminal");
opt = In.getInt();
System.out.println("You selected: Option " +opt);
System.out.println("");
switch(opt)
{
case 1:
encryptWord(word, key);
break;
case 2:
decryptWord(word, key);
break;
case 0:
System.out.println("Thank you for using the encryption/decryption program");
break;
default:
System.err.println("Invalid option. Select 1 for encryption, 2 for decryption, or 0 to exit");
System.out.println("");
break;
}
}while (!isExit(opt));
return opt;
}
public static String keyInput(String key)
{
do
{
System.out.println("Enter the key you want for encryption/decryption");
key = In.getString();
System.out.println("Your key is: " +key);
System.out.println("");
}while (!isValid(key));
//printEncrypted(key);
return key;
}
public static String wordInput(String word)
{
do
{
System.out.println("Enter the word you want decrypted/encrypted");
word = In.getString();
System.out.println("You entered: " +word);
System.out.println("");
} while (!isValid(word));
//printEncrypted(word);
return word;
}
public static void encryptWord(String word, String key)
{
// String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
wordInput(word);
keyInput(key);
System.out.println("The word from the encryptWord metod " +word);
printEncrypted(word, key);
}
public static void decryptWord(String w, String k)
{
String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
wordInput(w);
keyInput(k);
}
This part of code is from my friend
public static String printEncrypted(String word, String key)
{
System.out.println("This is the word from the printEncrypted method: " +word);
int shift = 0;
//Uses the key length to determine how much the alphabet will shift
for (int x = 0; x < key.length(); x++)
shift += key.charAt(x) - 96;
shift = shift % 26;
//Creates an array to perform the shift
char [] y = word.toCharArray();
for (int x = 0; x < y.length; x++)
//Uses the shift to shift the alphabet to decrypt the word.
for (int d = 0; d < shift; d++)
if (y[x] == 'z')
y[x] = 'a';
else {
y[x]--;
}
String newWord = new String(y);
System.out.println("Encrypted is " +newWord);
return newWord;
}
public static boolean isValid (String s)
{
String strSpecialChars="!##$%&*()_+=-|<>?{}[]~";
//String alphabet2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
boolean upCase = false;
boolean isDigit = false;
boolean spChar = false;
if (s.matches(".+[A-Z].+")){
upCase = true;
}
if (s.matches(".+[1-9].+")){
isDigit = true;
}
if (strSpecialChars.contains(s)){
spChar = true;
}
if (upCase|| isDigit || spChar)
{
System.err.println("The string cannot contain capital letters, special characters or numbers. Try again.");
System.out.println("");
return false;
}
else
{
return true;
}
}
public static boolean isExit (int option)
{
if (option == 0)
{
return true;
}
else
{
return false;
}
}
}
And this is what I am trying to do for my character shift:
public class LetterTester
{
public static void main (String []args)
{
String input="craig";
final String alphabet="abcdefghijklmnopqrstvwxyz";
int finalValue = 0;
int[] numbers;
for(int i=0;i<input.length();i++){
finalValue=(alphabet.indexOf(input.charAt(i))+1);
System.out.print(finalValue);
}
}
}
However, I don't know how to create a variable and get my for loop to add its output to the variable every time it runs.
The LetterTester is just for testing. In my actual assignment, the input will be taken from another method, and then tested. So, for example, if the key is "abc", it will have the value of each of its letter determined, so a = 1, b = 2, c = 3. Then I want it to be added together into a variable which I can use.
So the variable should equal 6 when the calculations for the input are finished.
Also, not sure if I should make a second question for this, but in the code for my assignment, I am not able to pass in the value of my word and key inputs from their respective methods (keyInput and wordInput) to a method called encryptWord, it shows the word as blank when I try to test it from the encryptWord method.
If anyone is wondering what I have done for the input, I'm using the In class, which I got from here: http://www.ecf.utoronto.ca/~jcarter/
My instructor has taught the class from the beginning by teaching us to use the In class so far.
There is simply too much going on in the OP's question to fully answer. The following code is a guideline to the solution space.
Gather the input for the word and key separately from each other and any other operation. The method getWord() and getKey would need to use the In class as noted by the OP. The point here is that the methods do not need any parameters, have a return, and only gather the information (thus separating input from processing).
The encryptWord(String, String) method takes the gathered input and transforms it in some fashion, returning the transformation. It should not do any output (again, separate I/O from processing). I did not attempt to replicate the encryption algorithm.
The decryptWord(String, String) method also takes collected input and transforms it following an algorithm. No attempt here was made to implement anything, but essentially it is the inverse of the encryption.
Really not everything should be static, but it follows the OP's approach.
The isValid(String) appears to be limiting to only lower case letters. Obviously it can be adjusted if that assumption is incorrect.
//
// is valid checks to see if only lower case characters
//
private static boolean isValid(final String chkWord)
{
// returns true only if the match is lower case a-z
return chkWord.matches("^[a-z]+$");
}
private static String encryptWord(String word, String key)
{
// TODO: implement the encryption algorithm;
// The algorithm would use the key to do the encryption;
// here will just add to character as quick example
char[] wordChars = word.toCharArray();
for (int i = 0; i < wordChars.length; ++i) {
char c = wordChars[i];
if (c >= 'a' && c <= 'm') { c += 13; }
else if (c >= 'n' && c <= 'z') { c -= 13; }
wordChars[i] = c;
}
return new String(wordChars);
}
private static String decryptWord(String word, String key)
{
// TODO: implement the decryption algorithm
return "NEED TO IMPLEMENT";
}
private static String getWord()
{
// the word should be gathered from the user in some fashion
// using the In class that is provided
return "helloworld";
}
private static String getKey()
{
// the key should be gathered from the user in some fashion
// using the In class that is provided
return "doit";
}
public static void main(String[] args)
{
final String word = getWord();
final String key = getKey();
boolean validWord = isValid(word);
System.out.printf("Is valid [%s]: %b%n", word, validWord);
if (! validWord) {
System.err.println("Not a good word!");
return;
}
String encrypted = encryptWord(word, key);
System.out.printf("Encrypted %s: %s%n", word, encrypted);
String decrypted = decryptWord(word, key);
System.out.printf("Encrypted %s: %s%n", word, decrypted);
}
Quick test of isValid():
Is valid [Hello]: false
Is valid [hello]: true
Is valid [specialchar*]: false

How can I validate if a string is a string and not an integer in java?

I enter a list into a JTextArea, and when I push a button, it runs the method below. I need to check to see if str[i+1], str[i+2] is a String and not an int.
public void readData(JTextArea input) {
String[] str = input.getText().split("\n");
for(int i =1; i< str.length; i= i+3) {
try {
Integer.parseInt(str[i]);
simulator.add(new Process(Integer.parseInt(str[i]), str[i+1],str[i+2]));
} catch(NumberFormatException e) {
System.out.println("Please enter an integer only " +
str[i] + " is not an integer");
}
}
}
You could have a function that tries to parse the string into an Integer or a Double and return true if it succeeded, or return false is an exception was thrown during parsing. Parsing into a Double should be enough since all integer values are decimal values without the .0
public static boolean isNumber(String s) {
try {
Double.parseDouble(s);
/* Use Integer.parseInt(s) instead, if
you want to check if the String s
is an Integer */
} catch(NumberFormatException e) { // string is not a number
return false;
}
return true;
}
Then you can say if(!isNumber(str)) to check if the String str is not a number.
Alternatively, you could make the isNumber() be a isNotNumber() by swapping the return false and return true statements.
If you don't want to use exceptions, a different approach would be the following. Since we know a valid number can only contain digits and at most 1 dot for decimal point, we can iterate through the string and check for each character:
if it is not a digit and not a dot, return false
if it is a dot but a dot was already found, return false
otherwise it is valid number character and we do nothing
Here is a sample function:
public static boolean isNumber(String s) {
int dotCount = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '.' && !Character.isDigit(s.charAt(i))) {
return false;
} else if(s.charAt(i) == '.') {
if(dotCount == 1) {
return false;
}
dotCount = 1;
}
}
return true;
}
EDIT: based on #MadProgrammer's suggestions:
A more general approach that will accept values separated with commas such as 1,35 or any amount of spaces within the number string like with 123 456 . 333.
Approach:
Iterate through the string and check for each character:
if it is not a digit, dot, comma, or a space, return false
if it is a dot or a comma but one of them was already found, return false
otherwise it is valid number character and we do nothing
So the code would look something like:
public static boolean isNumber(String s) {
int separatorCount = 0; // count dots and commas
char currChar;
s.trim(); // remove trailing and leading whitespace
for (int i = 0; i < s.length(); i++) {
currChar = s.charAt(i);
if (currChar != '.' && currChar != ',' && currChar != ' '
&& !Character.isDigit(currChar)) {
return false;
} else if (currChar == '.' || currChar == ',') {
if (separatorCount == 1) {
return false;
}
separatorCount = 1;
}
}
return true;
}
Another solution could use the NumberFormat's parse() method. However, this method only checks the beginning of the string (for example, for 12.3.3 it will return 12.3) so we have to return false if the returned string doesn't equal the input string as well as if the ParseException is thrown.
public static boolean isNumber(String s) {
try {
String newVal = NumberFormat.getInstance().parse(s).toString();
if (!newVal.equals(s)) {
return false;
}
} catch (ParseException e) {
return false;
}
return true;
}
NOTE: All of the methods should probably have a check if(s == null) { return false; } for the input String s to prevent a NullPointerException
Your rules are sparse, you don't specify if things like , or . are considered part of a number or not (1, 000.01 for example), also, you don't define if the value is allowed to contain numerical values or not, but...
You Could...
Try parsing each value (or the concatenation of the two) using Integer.parseInt, if they pass, then they are not String (or text) based values...
You Could...
Verify each character within the String to see if it contains more than just digits, using something like Character#isLetter
You Could...
Use a regular expression to determine if the value contain other content other than numbers.
You can try this simple regular expression to check if a string represents a number or not:-
String str = "12345";
System.out.println(str.matches("\\d+"));
Regex seems the best option. Here's a regex that will parse float and integers and currency values with comma as well.
String numberRex = "^([\\d]*\\.*\\d*|[\\d,]*\\.*\\d*)$";
"1234,455.43".matches(numberRex); // true
This is a simple test that asserts there is at least one non numeric char:
if (str.matches(".*[^\\d.].*"))
the regex translates as "somewhere in the input there's a character that's not a digit or a dot"

Java Compare single char to char array

I need to compare single char to char array and see if array has that char.
My current code looks like this:
public boolean isThereChar(char[] chaArray, String chr){
boolean bool = false;
for(int i=0; i < chaArray.length; i++)
{
if(chr.equals(chaArray[i])){
bool = true;
}
}
return bool;
}
Edit Notes:
Really sorry for being confusing! I am just a Java Beginner =/
Basically I am writing small Hangman game with GUI.
My program reads off text file and randomly chooses word which player has to guess, then prints it out in hidden manner like this: _ _ _ _ _
In this case I want player to input character or string (person can guess either whole word or just one letter)
Then I want my program to take that letter or string and compare to my hidden word
Following code chooses word and hides it:
public String pickWord(){
String guessWord = (wordsList[new Random().nextInt(wordsList.length)]);
return guessWord.toLowerCase();
}
//Hides picked word
public char[] setWord(){
char[] word = new char[pickWord().length() * 2];
for (int i = 0; i < word.length; i+=2) {
word[i] = '_';
word[i + 1] = ' ';
}
return word;
}
Then person input his character which he guesses to program with following code:
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action == "Guess Letter"){
inputChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
if (inputChar.length() > 1){
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInString(inputChar);
//For testing purposes
System.out.println("This is String: " +glr.getInString());
}else{
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInChar(inputChar);
//For testing purposes
System.out.println("This is Char: " +glr.getInChar());
}
}
Lastly I want to take that character which was inputted and compare to my array of chars which is my hidden word:
public boolean isThereChar(char[] array, String str){
return isThereChar(array, str.charAt(0));
}
public boolean isThereChar(char[] array, char c){
for(int i=0; i<array.length; i++){
if (array[i] == c) return true;
}
return false;
}
I want to check what does my code returns (true or false), but I keep failing at doing so.
(Right now I am trying to call method in my main class to check it, if you can give me tips how to do it otherwise please let me know.)
I would use: Chars.contains(array, chr); with Guava Chars
The NullPointerException is happening because either chaArray or chr is null when you call the method. (And if not, then the NullPointerException is occurring somewhere else!!)
The other problem with your code is this line:
if (chr.equals(chaArray[i])) {
Since chr is actually a String, what is going to happen here is that the value of chaArray[i] will be auto-boxed as a Character object, and then passed as an argument to String.equals(Object). But the String.equals(Object) will return false unless its argument is a String ... so your code wouldn't find the character anyway.
You need to either compare the character like this:
if (chr.charAt(0) == chaArray[i]) {
or declare chr to be a char and compare it as:
if (chr == chaArray[i]) {
Let's see if I got what you need :
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action == "Guess Letter"){
inputChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
if (inputChar.length() > 1){ //User input is a string here, right?
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInString(inputChar);
System.out.println(wordToGuess.contains(glr.getInString())); //This will print true if wordToGuess is equal to glr.getInString() or if it just contains it
//For testing purposes
System.out.println("This is String: " +glr.getInString());
}else{ //Here the user gave us just a character, so we've got to know if this character is contained in the word, right?
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInChar(inputChar);
System.out.println(wordToGuess.contains(glr.getInChar()); //This will print true if your char is in the wordToGuess string
//For testing purposes
System.out.println("This is Char: " +glr.getInChar());
}
}
}
Select the character from the parameter passed in, or pass in a char e.g.
chr[0]
or
public String isThereChar(char[] chaArray, char chr){
for(int i=0; i < chaArray.length; i++)
{
if(chr.equals(chaArray[i])){
return chr;
}
}
return "Guess Again";
}
String chr might be null causing NullPointerException.
Use char chr instead of String.
public boolean isThereChar(char[] chaArray, char chr){
boolean bool = false;
for(int i=0; i < chaArray.length; i++) {
if(chr==chaArray[i])){
bool = true;
}
}
return bool;
}
public boolean isThereChar(char[] chaArray, char chr){
for(int i=0; i < chaArray.length; i++)
{
if((chaArray[i]==chr)){
return true; // means Character exist in the Character array
}
}
return false; //// means Character does not exist in the Character array
}

Categories

Resources