My variable may not have been Initialized - java

So I think my while loop is not even occurring and I am not quite sure why. It is probably an something obvious however I cannot seem to find the solution. What this code is attempting to do is use the variable "firstLetter" and add to the String "passcode" and continue to add the different characters that are specified within the while loop. however it is saying that my variable may have not been initialized which makes me think that the whole loop is messed up and is not being seen. Im pretty new to coding so any help would be appreciated
import java.util.Scanner;
public class Password
{
public static void main (String [] args)
{
System.out.println("This program will take a phrase by you and"
+ "\ncreate a strong and safe password that "
+ "\nwill be similar. Please enter a phrase.");
Scanner keyboard = new Scanner (System.in);
String message = keyboard.nextLine();
String firstLetter;
int index = 0,
number = 0, //a counting mechanism
spot = 2, // how many characters in each word you put down
pass = 1; //counting up the number of char in the password
if (message.charAt(0) == ' '){
System.out.println("Make sure the first character in your "
+ "phrase is not a space");
System.exit(1);
}//if
System.out.print("\nYour Password is: ");
char white = message.charAt(index);
firstLetter = Character.toString(white);
System.out.println(firstLetter);
index = 1;
String passcode;
while(index < message.length()) {
white = message.charAt(index);
if ((white != ' ') && (number != spot)) {
pass = pass + 1;
index = index + 1;
number = number + 1;
passcode = firstLetter + white;
}//if
else if (white != ' ') {
index = index + 1;
}//else if
else { spot = spot + 1;
number = 0;
index = index + 1;
}//else
}//while
System.out.print(passcode);
}
}

You have declared a variable passcode like:
String passcode;
The only way to initialize it when you go in while loop (meaning while condition satisfies), you go into if if ((white != ' ') && (number != spot)) { What if it doesn't satisfies condition? That means you dont have any values for pass code and then you try to access it like:
System.out.print(passcode);
Hence compiler complains about the same. So you need to do something addition to String declaration like:
String passcode = "";//define it as well with default value and you might need to check defining values within if/else where its not already present

Just had a brief look at the code, I feel this would not compile and complain about passcode variable not being initialized. What if the condition
index < message.length() is not true first time and while loop is never entered!!
I guess that explains why compiler is giving error.
You can initialize passcode to any value, null or empty string may be depending on your use case which I am not sure of.
Hope this helps.

Related

Why is my method returning false even though the conditions are true?

public class Lab3Exercises {
public static void main(String[] args){
Scanner s = new Scanner([System.in](https://System.in));
System.out.println("Please enter a word to check if it is a palindrome");
String myP = [s.next](https://s.next)();
System.out.println(palindrome(myP));
}
public static boolean palindrome(String p){
String myWord = p;
String reverseWord = "";
int i = 1;
while (i < myWord.length()){
reverseWord = myWord.charAt(i) + myWord.substring(0, i) + myWord.substring((i + 1), myWord.length());
i++;
}
if (reverseWord.equals(myWord)) {
return true;
}
else{
return false;
}
}
I checked and the reverseWord is the exact same as myWord yet it returns false everytime. I've tried hannah, racecar, etc. they all return false
Let’s start from the simpler examples.
If p has length 1, for example s (a palindrome), you are setting reverseWord to the empty string. Since i starts from 1, it is not less than the length, so the loop does not run. Since the empty string is not equal to s, the method returns false.
Input tt (another palindrome). You are running once through the loop, setting reverseWord to "t" + "t" + "" = "tt". The method correctly returns true in this case.
Input obo: You are setting reverseWord first to boo, then to "oob" ("o" + "ob" + ""), discarding the first value.
I think you need to think your logic through once more.
Tip: learn to use a debugger.
You're condition isn't true because the way you build the reversed word is wrong.
You're beginning with i equals to 0
You reassign a new value to reverseWord in every loop
The way you're building the reversed string is totally a mystery to me
A good solution would be the following (you write the code :))
Try beginning your loops with the index beginning at the very end of the original word
Loop down until you reach 0, basically until no letter remains to be appended to reverseWord
In every loop, append a single letter to reverseWord instead of the result of a complex operation
No need to make a new reference for the plaindrome word that you're going to check.
You should store the word in the reverse order in reverseWord variable.
Last index of a char array (String) in java is 1 less than string length. First index is 0.
So,the while loop read the string from the end to start index and store.
public static boolean palindrome(String p){
String reverseWord = "";
int i = p.length() - 1;
while (i >= 0){
reverseWord += p.charAt(i);
i--;
}
if (reverseWord.equals(p)) {
return true;
}
return false;
}

Java for loop isn't terminating in my code

For some reason my for loop is not terminating in my CapitalizeFirstSentence method. I set a breakpoint at that line and the condition (i != -1) is unmet, so the loop should terminate, but it doesn't!
It works when I use (i > 0) for the condition.
I'm not sure what's going on here.
import javax.swing.JOptionPane;
public class SentenceCapitalizer {
//Main Method
public static void main(String[] args) {
String input; //creates a String to hold keyboard input
//Prompt the user to enter a String using JOptionPane and set it equal to input
input = JOptionPane.showInputDialog("Enter a string. ");
//Display the new String with the first letter of each sentenced capitalized
JOptionPane.showMessageDialog(null, CapitalizeFirstSentence(input));
//Exit the program
System.exit(0);
}
//Capitalize first letter of each sentence
public static String CapitalizeFirstSentence(String in)
{
//Creates a StringBuilder object initiralized to the String argument "in"
StringBuilder temp = new StringBuilder(in);
//Capitalize first letter of the string if string length is > 0
if (temp.length() > 0)
{
temp.setCharAt(0, Character.toUpperCase(temp.charAt(0)));
}
//sets i equal to index of the space,
//keep capitalizing first letters of each sentence (loops each time it capitlizes a letter)
//until very end of the String
for (int i = temp.indexOf(". ")+1; i != -1; i++)
{
//Checks for extra spaces and moves index to first character of next sentence
while (i < temp.length() && temp.charAt(i) == ' ')
{
i++;
}
//Capitalize character
temp.setCharAt(i, Character.toUpperCase(temp.charAt(i)));
//Index the end of the sentence
i = temp.indexOf(". ", i);
}
//Convert temp to a String and return our new first-sentenced-capitalized String
return temp.toString();
}
}
First, it is not a good idea to modify the loop-controlling variable inside a for loop - it is quite hard to read and understand such code, and is prone to errors.
Now, to your example:
for (int i = temp.indexOf(". ")+1; i != -1; i++)
This means:
Initialize i to temp.indexOf(". ")+1, which is always >= 0
Terminate if i == -1
After each iteration, increment i by 1
So:
At the start, the cycle won't terminate because the initialization always returns >= 0
Each iteration, the loop body will set i = temp.indexOf(". ", i);, which is >= -1
After each iteration, i will be incremented by 1, so it will now be >= 0
As i is always >= 0, it will never meet the condition i == -1 and thus will never terminate
This line: for (int i = temp.indexOf(". ")+1; i != -1; i++) initializes i to be the result of indexOf + 1. IndexOf gives -1 if there is no hit, but you always add 1 to that during initialization, so it'll never be smaller than 0.
Using i > 0 seems perfectly fine there.

Using methods to check for palindromes

I have to use methods to test a sentence for palindromes and I have got most of it done but it will only do the first word in the string and won't move on to the next one. I believe its something got to do with the spaces, if anyone could help that'd be great. Also I haven't studied arrays so I'd appreciate if arrays were not used.
class palindromeTesting
{
public static void main(String[] args)
{
String userInput;
String goodWords;
String palindromes;
System.out.println("Please enter a sentance to be tested for palindrome: ");
userInput = EasyIn.getString();
userInput += " " ;
goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
System.out.println("The valid palindromes are " + palindromes);
} //Main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
public static String charsCheck(String userInput)
{
String validWords;
String firstWord;
Boolean goodWord;
int spacePos;
char letter;
spacePos = userInput.indexOf(" ");
validWords = "";
while(spacePos > 0)
{
firstWord = userInput.substring(0 , spacePos);
goodWord = true;
for(int index = 0 ; index < firstWord.length() && goodWord == true ; index++)
{
spacePos = userInput.indexOf(" ");
letter = Character.toUpperCase(firstWord.charAt(index));
if(letter < 'A' || letter > 'Z' )
{
goodWord = false;
}
} //for
if(goodWord == true)
{
firstWord = firstWord + " ";
validWords = validWords + firstWord;
}
userInput = userInput.substring(spacePos + 1);
spacePos = userInput.indexOf(" ");
} //While
return validWords;
} //charsCheck main
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
public static String palinCheck(String goodWords)
{
String firstWord;
String validPalins = "";
String backward = "";
int spacePos;
spacePos = goodWords.indexOf(" ");
while(spacePos > 0)
{
firstWord = goodWords.substring(0 , spacePos);
for(int i = firstWord.length()-1; i >= 0; i--)
{
backward = backward + firstWord.charAt(i);
}
if(firstWord.equals(backward))
{
validPalins = validPalins + firstWord;
}
goodWords = goodWords.substring(spacePos + 1) ;
spacePos = goodWords.indexOf(" ") ;
}//While
return validPalins;
} //palinCheck main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
} //Class
If you believe the issue are spaces, you could always remove all spaces (and any other unwanted characters) with the replaceAll() method (check out the API). Say you have word1 and word2 you'd like to compare to see if they are palindromes, then do the following:
String word1 = "du mb";
String word2 = "b,mu d";
word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
Once you've gotten ridden of unnecessary characters or spaces, then you should do the check. Also, you could always use Regex expressions for this kind of task, but that may be a bit difficult to learn for a beginner.
Also, I recommend using for loops (can probably be done in one for loop, but nested loops will do) instead of while loop for this task. Check out this example.
Sidenote:
Also I haven't studied arrays so I'd appreciate if arrays were not
used.
Strings are essentially char arrays.
The problem you described is actually not what is happening; your code does indeed move on to the next word. For my test, I used the test input Hi my name is blolb.
The problem is in your palinCheck method. You are using the backward variable to reverse the word and check whether it and firstWord, are equal. However, you aren't resetting the backward variable back to a blank string in the loop. As a result, you're constantly adding to whatever was in there before from the previous loop. At the end of the method, if I examine the content of backward using my test string above, it actually looks like iHymemansiblolb.
To solve this, simply declare String backward inside the while loop, like so:
while(spacePos > 0) {
String backward = "";
// rest of loop
Quick side note:
During the run of the palinCheck method, you're changing the goodWords parameter each iteration when you do this:
goodWords = goodWords.substring(spacePos + 1) ;
While this is technically acceptable (it has no effect outside of the method), I wouldn't consider it good practice to modify the method parameter like this. I would make a new String variable at the top of the method, perhaps call it something like currentGoodWords or something like that, and then change your line to:
currentGoodWords = goodWords.substring(spacePos + 1) ;
Also, I assume this is homework, so if you are allowed to use it, I would definitely take a look at the StringBuilder#reverse() method that Elliot Frisch mentioned (I admit, I never knew about this method before now, so major +1s to Elliot).
I had this code written as a personal project quite a while ago on palindrome using the shortest amount of code. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}

Get the last word in a string using a for loop?

I have to find the last word in a string and can't understand why my code isn't working. This is what I have:
int i, length;
String j, lastWord;
String word = "We the people of the United States in order to form a more perfect union";
length = word.length();
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" ") == true);
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
However, when I run it, it prints the last letter. I know I could use
String lastWord = word.substring(word.lastIndexOf(" ") + 1)
But I'm pretty sure my teacher doesn't want me to do it this way. Any help?
You need to remove the ; after the if to make it work:
if (j.equals(" ")) // <== No semicolon, and no == true
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
You do not need == true for booleans inside control statements, either.
Finally, making single-character substrings is more expensive than using single characters. Consider using charAt(i) instead:
if (word.charAt(i) == ' ') // Single quotes mean one character
{
lastWord = word.substring(i+1);
System.out.println("Last word: " + lastWord);
break; // there is a better way to stop the loop
}
You've terminated the if statement. It should be,
if(j.equals(" "))
{
...
}
Just take that ; from if (j.equals(" ") == true); out.
Your code remade cleaner:
String word = "We the people of the United States in order to form a more perfect union";
for (int i = word.length() - 1; i > 0; i--)
if (word.charAt(i - 1) == ' ') {
System.out.println("Last word: " + word.substring(i));
break; // To stop the loop
}
Minimum iterations.
Convert the string to char array and look for space from the end of array. Don't forget to remove white spaces from the end using trim() as they could be counted as separate words.
s = s.trim();
char[] c = s.toCharArray();
for(int i=0; i<c.length; i++)
{
if(c[c.length-1-i]==' ')
{
return s.substring(c.length-1-i);
}
}
return s;
This also covers the null string case.
Another alternative using split.
s = s.trim();
String[] strs = new s.split(' ');
return str[str.length-1];
The semicolon after your "if" statement means "do nothing." Also, the "== true" is redundant. Lastly, you don't want to include the space you just found. Try this:
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" "))
{
lastWord = word.substring(i + 1);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
There's a method for strings to split up at http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
A good, fast and easier way would be:
word = word.split(" ")[word.length-1];
split() returns an array of substrings based on " ". Since an array starts with 0, its last element is the length of the array - 1.

Simple JAVA: Password Verifier problem

I have a simple problem that says:
A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string and print out a message as to whether or not the string entered would be considered a valid password.
I need help on completing this code. I have this pseudocode that I can't workout into Java code:
print "enter new password"
input newPassword
digitCounter =0
letterCounter = 0
for I = 0 to newPassword.length() by 1
c = newPassword.charAt(i)
if c is a digit
increment digitCounter
else if c is a letter
increment letterCounter
endif
endFor
if newPassword.length() >= 6 and digitCounter > 0 and letterCounter > 0
print "the password is valid"
else
print " password rejected, must be at least 6 characters long and be a mix of letters and digits "
endif
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
So far all I have is this for the Java code:
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String thePassword;
int len, i, letterCounter = 0, digitCounter = 0;
char c;
Len = thePassword.length();
System.out.print("Enter the password: ");
thePassword = in.nextLine();
for (i = 0,i = len, )
{
c = in.charAt(1);
if ()
}
}
}
Take a look at Character.isDigit() and Character.isLetter() for checking the characters:
If you want to use String.charAt() to get the characters of your string, you could do a for loop like so:
for (int i = 0;i < s.length();i++) {
char c = s.charAt(i);
//Check things about c
}
Although Java 1.5 instroduced a For-Each loop which will loop automatically over arrays like so:
for (char c : s.toCharArray()) {
//Check things about c
}
impot javax.swing.JOptionPane;
class PasswordDemo{
public static void main(String[] agrs){
String pass = "abcdef";
String right = "Success!";
String wrong = "Failed to login";
String input = JOptionPane.showInputDialog("Enter the password to login: ");
do{
JOptionPane.showMessageDialog(null,wrong);
input = JOptionPane.showInputDialog("Enter the password to login: ");
}while(!input.equals(pass));
//when login successfully
JOptionPane.showMessageDialog(null,right);
}
}
I'd check that the Regex \d (any digit), and the Regex [a-z] (any letter) both matches the string. And then check for length.
A couple quick tips:
your pseudo code algorithm is not correct. It will correctly validate that strings must indeed be at least 6 characters in length, but won't invalidate passwords with weird characters in them (e.g. ~%). Based on the problem statement, it seems implicit that the sentence "made up of a combination of letters and digits" means made up only of those. For this part, as others have mentionned, you can use built-in methods of the String or Character classes such as String.charAt(), Character.isDigit() and Character.isLetter().
make it a habit to declare stuff at the latest possible time (i.e just before it's used). In your example, you have String thePassword, then 2 other lines, then you assign something to thePassword. Instead, write it directly as String thePassword = in.nextLine(). This will help make the code less cluttered and easier to read. Same for your other declarations (char c, int len, etc.).
try to use the enhanced for loop if you can, in order to avoid having to figure out the length and determine where to stop (potential for errors). In your example, your loop could be something like for (char c : thePassword.toCharArray()). If you haven't talked about this loop in your class yet, you don't have to use, and you should know how the simple for loop works as well, but this is just a suggestion. In your code example, your loop does not make sense, so I'd advise you to read up on loops.
I'm going to pretend that you just read in from the command line arguments, if you need it to be able to accept multiple passwords you can generalize it. Here is how I would easily do it:
public class Password {
public static void main(String[] args) {
String thePassword = args[0];
int passLength = thePassword.length();
boolean hasLetters = false;
boolean hasDigits = false;
boolean hasSomethingElse = false;
for (int i=0; i < passLength; i++) {
char c = thePassword.charAt(i);
if(Character.isLetter(c)) hasLetters = true;
else if(Character.isDigit(c)) hasDigits = true;
else hasSomethingElse = true;
}
if (hasLetters && hasDigits && !hasSomethingElse && (passLength >= 6)) {
System.out.println("Password is correctly formatted");
} else {
System.out.println("Password is not correctly formatted");
}
}
}

Categories