Newbie looking for help on a password code - java

I am looking for some help with a project i am working on. I am relatively new to java and am working to make a function to generate a password. There is probably alot of error in this or this might be completely wrong so please be nice to a newbie >.<
import java.util.Random;
public class StillTesting {
public static void main(String[] args) {
System.out.println("Your new password is: " + generateValidPassword());
}
static private String generateValidPassword() {
String numcase = "";
String lowcase = "";
String upcase = "";
String halfpass = numcase.concat(upcase);
String returnString = halfpass.concat(lowcase);
System.out.print(returnString);
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for (int i = 0; i < 3; i++) {
num = r.nextInt(9);
numcase = String.valueOf(num = r.nextInt(9));
return numcase;
}
for (int i = 0; i < 3; i++) {
lowcase = String.valueOf(loweralphabet.charAt(r.nextInt(n)));
return lowcase;
}
for (int i = 0; i < 3; i++) {
upcase = String.valueOf(upperalphabet.charAt(r.nextInt(N)));
return upcase;
}
return returnString;
}
}

You may want to try removing your return statements in your loop something like this:
static private String generateValidPassword()
{
String numcase = "";
String lowcase = "";
String upcase = "";
String halfpass = "";
String returnString = "";
System.out.print(returnString);
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for(int i=0;i<3;i++)
{
num=r.nextInt(9);
numcase = String.valueOf(num);
returnString += numcase;
}
for(int i=0;i<3;i++)
{
lowcase = String.valueOf(loweralphabet.charAt(r.nextInt(n)));
returnString += lowcase;
}
for(int i=0;i<3;i++)
{
upcase = String.valueOf(upperalphabet.charAt(r.nextInt(N)));
returnString += upcase;
}
return returnString;
}
This will give you output like 637xiqHMR. You will combine the letters generated from each loop into one string then return the whole string at the end instead of returning at first iteration of first loop.

Is this what you are looking for? The output of the following program is something like 433raeWPV and 675croJWV
public static void main(String[] args) {
System.out.println("Your new password is: " + generateValidPassword());
}
static private String generateValidPassword() {
String pswd = "";
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for (int i = 0; i < 3; i++) {
num = r.nextInt(9);
pswd += String.valueOf(num = r.nextInt(9));
}
for (int i = 0; i < 3; i++) {
pswd += String.valueOf(loweralphabet.charAt(r.nextInt(n)));
}
for (int i = 0; i < 3; i++) {
pswd += String.valueOf(upperalphabet.charAt(r.nextInt(N)));
}
return pswd;
}

Alright, indeed there are some mistakes:
You are setting halfpass and returnString values before assigning the values of numcase, upcase and lowcase
You are returning a value in the first iteration of every for loop, The first return statement will return the first numcase value. More info about how the return statement works here
at the end, the returnString statement is never reached.
Try something like this:
static private String generateValidPassword()
{
String numcase = "";
String lowcase = "";
String upcase = "";
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for(int i=0;i<3;i++)
{
num=r.nextInt(9);
numcase += String.valueOf( num = r.nextInt(9));
}
for(int i=0;i<3;i++)
{
lowcase += String.valueOf(loweralphabet.charAt(r.nextInt(n)));
}
for(int i=0;i<3;i++)
{
upcase += String.valueOf(upperalphabet.charAt(r.nextInt(N)));
}
String halfpass = numcase.concat(upcase);
String returnString = halfpass.concat(lowcase);
System.out.print(returnString);
return returnString;
}
}

Well, it looks like a few people spotted the bugs while I was working, but as I've tidied up the whole thing you might like to take a look at this working version which addresses most of the issues in the original:
import java.util.Random;
public class StillTesting {
public static void main( String[] args )
{
System.out.println("Your new password is: " + generateValidPassword());
}
static private String generateValidPassword()
{
StringBuilder password = new StringBuilder();
Random r = new Random();
final String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
final String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int i=0;i<3;i++)
{
password.append(String.valueOf(r.nextInt(10)));
}
for(int i=0;i<3;i++)
{
password.append(loweralphabet.charAt(r.nextInt(loweralphabet.length())));
}
for(int i=0;i<3;i++)
{
password.append(upperalphabet.charAt(r.nextInt(upperalphabet.length())));
}
return password.toString();
}
}

Related

Why am I getting NullPointerException on my "plain1.findPosition(iMsg)"?

First Class which is giving me the error. I'm to make an array with the letters A-Z, and then have the user input the keys which it takes and compares each character's position in the array of the key with the position of a user inputted string
import java.util.*;
public class Encrypt{
private Square plain1;
private Square plain2;
private Square Encrypt1;
private Square Encrypt2;
public Encryption(String key1, String key2) {
Square plain1 = new Square();
Square plain2 = new Square();
Square Encrypt1= new Square(key1);
Square Encrypt2= new Square(key2);
}
public String encrypt(String msg) {
String EmpS = "";
String STR = "";
for(int i = 0; i < message.length(); i+=2){
char iMsg = message.charAt(i);
char iMsg2 = message.charAt(i+1);
int[] posRay = plain1.findPosition(iMsg);
int[] posRay2 = plain2.findPosition(iMsg2);
String answer = "" + Encrypt1.getChar(posRay[0], posRay2[1]);
String Combined = "" + answer;
String answer2 = "" + Encrypt2.getChar(posRay2[0], posRay[1]);
String Combined2 = "" + answer2;
String BothCom = Combined + Combined2;
STR = STR.concat(BothCom);
return STR;
}
return STR;
}
2nd class that is responsible for the array
public class Square {
private char[][] matrix;
public Square() {
arr= new char[5][5];
int ascii= 65;
for (int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
arr[i][j] = (char) ascii;
ascii++;
}
}
}
}
public int[] findPosition(char Chart) {
int[] position= new int[2];
position[0] = -1;
popositions[1] = -1;
for (int i = 0; i < 5; i++){
for (int j = 0; i < 5; j++){
if(matrix[i][j] == Chart){
posistion[0] = i;
position[1] = j;
return position;
}
}
}
I'm getting this as an error (everything else works), what's the issue?:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Square.getPos(char)" because "this.plain1" is null
at findPosition.encrypt(Encrypt.java:45)
at IO.printResults(IO.java:101)
at Test.main(Proj8.java:26)
You are not assigning your class variables, you are actually assigning new local variables inside the method. Change to:
public Encryption(String key1, String key2) {
plain1 = new Square();
plain2 = new Square();
Encrypt1= new Square(key1);
Encrypt2= new Square(key2);
}

How do you shift char values in an arraylist?

I'm trying to code a cipher project where the objective is for a user to send in a text and shift number. The result would be printed accordingly. For instance, if I sent "Hello World" with a shift value of 1, it should print: "Gfmmp Xrsme". The problem is that I'm having trouble with the shifting because I have an arraylist of char values (the alphabet).
This is what I have so far:
import java.util.ArrayList;
public class CaesarCipher
{
int shift;
String inputText;
ArrayList<String> arr;
ArrayList<String> exchange = new ArrayList<String>();
public CaesarCipher()
{
shift = 0;
inputText = "";
}
public CaesarCipher(int s, String iT)
{
shift = s;
inputText = iT;
}
public void alphabet()
{
arr = new ArrayList<String>();
arr.add("A");
arr.add("B");
arr.add("C");
arr.add("D");
arr.add("E");
arr.add("F");
arr.add("G");
arr.add("H");
arr.add("I");
arr.add("J");
arr.add("K");
arr.add("L");
arr.add("M");
arr.add("N");
arr.add("O");
arr.add("P");
arr.add("Q");
arr.add("R");
arr.add("S");
arr.add("T");
arr.add("U");
arr.add("V");
arr.add("W");
arr.add("X");
arr.add("Y");
arr.add("Z");
}
public void convert()
{
String revisedText = inputText.replaceAll("\\s","");
//Turn revisedText into an array and match it with array above
revisedText.toUpperCase();
int j = 1;
String letter = "";
for (int i = 0; i < revisedText.length(); i++)
{
exchange.add(revisedText.substring(i, j));
j++;
}
}
public void shift()
{
shift = shift % 26 + 26;
ArrayList<String> newArr = new ArrayList<String>(); // array with shifted values
int pos = 0;
for(int r = 0; r < exchange.size(); r++)
{
if(arr.get(r).equals(exchange.get(r)))
arr.indexOf(r) + shift = pos;
}
}
public String toString()
{
return "";
}
}
Here is quick for loop for an example
String string = "Hello World";
String newPhrase = "";
int shift = 1;
for(int i = 0; i < string.length(); i++){
if(string.charAt(i) != ' ')
newPhrase += (char)(string.charAt(i) + shift);
else
newPhrase += ' ';
}
System.out.println(string + " -> " + newPhrase);
Output
Hello World -> Ifmmp Xpsme
However you should note that there are a couple edge cases i am not checking for. Once you understand the above code you should be able to find the edge cases I am talking about.

Affine Cipher decryption

I feel as though I have the math and logic correct, I'm not sure what I'm doing wrong. Iv'e tried it with a few different values of b and nothing works. For some reason, "f" is always changed to "v" and "k" always to "q", no matter the constant used. My output is: glqvafkpuzejotydinsxchmrwb, abcdwvghijqlmnolqrstgvwxyb. Decipher method works when b = 0.
public class Asgn2No2CodeDecode {
public static void main(String[] args) {
System.out.println(affineCipher("abcdefghijklmnopqrstuvwxyz"));
System.out.println(affineDecipher(affineCipher("abcdefghijklmnopqrstuvwxyz")));
}
public static String affineCipher(String plainTxt)
{
StringBuilder cipherTxt = new StringBuilder();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int a = 5;
int b = 6;
int charNum = 0;
char alphChar;
char ciphChar;
for (int i = 0; i < plainTxt.length(); i++)
{
ciphChar = plainTxt.charAt(i);
if (Character.isLetter(ciphChar))
{
for (int j = 0; j<alphabet.length(); j++)
{
alphChar = alphabet.charAt(j);
if (ciphChar == alphChar)
{
charNum = ((a*j + b)%26);
}//end if
}//end for alph
cipherTxt.append(alphabet.charAt(charNum));
}else cipherTxt.append(plainTxt.charAt(i));
}//end for plain
return cipherTxt.toString();
}//end affineCipher(String)
public static String affineDecipher(String cipherTxt)
{
StringBuilder plainTxt = new StringBuilder();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int aInv = 21;
int b = 6;
int charNum = 0;
char alphChar;
char ciphChar;
for (int i = 0; i < cipherTxt.length(); i++)
{
ciphChar = cipherTxt.charAt(i);
if (Character.isLetter(ciphChar))
{
for (int x = 0; x<alphabet.length(); x++)
{
alphChar = alphabet.charAt(x);
if (ciphChar == alphChar)
{
if (x>=b)
{
charNum = (((aInv*(x-b))%26));
}
else charNum = (-((aInv*(x-b))%26));
}//end if
}//end for alph
plainTxt.append(alphabet.charAt(charNum));
}else plainTxt.append(cipherTxt.charAt(i));
}//end for plain
return plainTxt.toString();
}//end affineCipher(String)
}

Fancy looping in Java

I have a problem wherein I have two strings, the length of one of which I will know only upon execution of my function. I want to write my function such that it would take these two stings and based upon which one is longer, compute a final string as under -
finalString = longerStringChars1AND2
+ shorterStringChar1
+ longerStringChars3and4
+ shorterStringChar2
+ longerStringChars5AND6
...and so on till the time the SHORTER STRING ENDS.
Once the shorter string ends, I want to append the remaining characters of the longer string to the final string, and exit. I have written some code, but there is too much looping for my liking. Any suggestions?
Here is the code I wrote - very basic -
public static byte [] generateStringToConvert(String a, String b){
(String b's length is always known to be 14.)
StringBuffer stringToConvert = new StringBuffer();
int longer = (a.length()>14) ? a.length() : 14;
int shorter = (longer > 14) ? 14 : a.length();
int iteratorForLonger = 0;
int iteratorForShorter = 0;
while(iteratorForLonger < longer) {
int count = 2;
while(count>0){
stringToConvert.append(b.charAt(iteratorForLonger));
iteratorForLonger++;
count--;
}
if(iteratorForShorter < shorter && iteratorForLonger >= longer){
iteratorForLonger = 0;
}
if(iteratorForShorter<shorter){
stringToConvert.append(a.charAt(iteratorForShorter));
iteratorForShorter++;
}
else{
break;
}
}
if(stringToConvert.length()<32 | iteratorForLonger<b.length()){
String remainingString = b.substring(iteratorForLonger);
stringToConvert.append(remainingString);
}
System.out.println(stringToConvert);
return stringToConvert.toString().getBytes();
}
You can use StringBuilder to achieve this. Please find below source code.
public static void main(String[] args) throws InterruptedException {
int MAX_ALLOWED_LENGTH = 14;
String str1 = "yyyyyyyyyyyyyyyy";
String str2 = "xxxxxx";
StringBuilder builder = new StringBuilder(MAX_ALLOWED_LENGTH);
builder.append(str1);
char[] shortChar = str2.toCharArray();
int index = 2;
for (int charCount = 0; charCount < shortChar.length;) {
if (index < builder.length()) {
// insert 1 character from short string to long string
builder.insert(index, shortChar, charCount, 1);
}
// 2+1 as insertion index is increased after after insertion
index = index + 3;
charCount = charCount + 1;
}
String trimmedString = builder.substring(0, MAX_ALLOWED_LENGTH);
System.out.println(trimmedString);
}
Output
yyxyyxyyxyyxyy
String one = "longwordorsomething";
String two = "short";
String shortString = "";
String longString = "";
if(one.length() > two.length()) {
shortString = two;
longString = one;
} else {
shortString = one;
longString = two;
}
StringBuilder newString = new StringBuilder();
int j = 0;
for(int i = 0; i < shortString.length(); i++) {
if((j + 2) < longString.length()) {
newString.append(longString.substring(j, j + 2));
j += 2;
}
newString.append(shortString.substring(i, i + 1));
}
// Append last part
newString.append(longString.substring(j));
System.out.println(newString);

How to Find the Longest Palindrome (java)

Hi I've been doing this java program, i should input a string and output the longest palindrome that can be found ..
but my program only output the first letter of the longest palindrome .. i badly need your help .. thanks!
SHOULD BE:
INPUT : abcdcbbcdeedcba
OUTPUT : bcdeedcb
There are two palindrome strings : bcdcb and bcdeedcb
BUT WHEN I INPUT : abcdcbbcdeedcba
output : b
import javax.swing.JOptionPane;
public class Palindrome5
{ public static void main(String args[])
{ String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
for(int x=0; x<size; x++)
{ for(int y=x+1; y<size-x; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
Out = GetLongest(subword);
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
public static String GetLongest(String sWord)
{
int sLength = sWord.length();
String Lpalindrome = "";
int storage = 0;
if(storage<sLength)
{
storage = sLength;
Lpalindrome = sWord;
}
return(Lpalindrome);
}
}
modified program..this program will give the correct output
package pract1;
import javax.swing.JOptionPane;
public class Palindrome5
{
public static void main(String args[])
{
String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
String Lpalindrome = "";
int storage=0;
String out="";
for(int x=0; x<size; x++)
{ for(int y=x+1; y<=size; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
int sLength = subword.length();
if(storage<sLength)
{
storage = sLength;
Lpalindrome = subword;
out=Lpalindrome;
}
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
}
You have two bugs:
1.
for(int y=x+1; y<size-x; y++)
should be
for(int y=x+1; y<size; y++)
since you still want to go all the way to the end of the string. With the previous loop, since x increases throughout the loop, your substring sizes decrease throughout the loop (by removing x characters from their end).
2.
You aren't storing the longest string you've found so far or its length. The code
int storage = 0;
if(storage<sLength) {
storage = sLength;
...
is saying 'if the new string is longer than zero characters, then I will assume it is the longest string found so far and return it as LPalindrome'. That's no help, since we may have previously found a longer palindrome.
If it were me, I would make a static variable (e.g. longestSoFar) to hold the longest palindrome found so far (initially empty). With each new palindrome, check if the new one is longer than longestSoFar. If it is longer, assign it to longestSoFar. Then at the end, display longestSoFar.
In general, if you're having trouble 'remembering' something in the program (e.g. previously seen values) you have to consider storing something statically, since local variables are forgotten once their methods finish.
public class LongestPalindrome {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}
public static void printLongestPalindrome(String S)
{
int maxBack=-1;
int maxFront = -1;
int maxLength=0;
for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
{
int back = potentialCenter-1;
int front = potentialCenter + 1;
int longestPalindrome = 0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome+1;
maxBack = back + 1;
maxFront = front;
}
back = potentialCenter;
front = potentialCenter + 1;
longestPalindrome=0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome;
maxBack = back + 1;
maxFront = front;
}
}
if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
else{
System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
}
}
}
I have my own way to get longest palindrome in a random word. check this out
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.
public class LongestPalindrome {
public static void main(String[] args) {
HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
}
private static HashMap<String, Integer> findLongestPalindrome(String str) {
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (i < str.length()) {
String alpha = String.valueOf(str.charAt(i));
if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
if (isPalindrome(pali)) {
map.put(pali, pali.length());
i = str.lastIndexOf(str.charAt(i));
}
}
i++;
}
return map;
}
public static boolean isPalindrome(String input) {
for (int i = 0; i <= input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}
}
This approach is simple.
Output:
String:abcdeedcba Value:10
String:4444 Value:4
String:6776 Value:4
String:ghihg Value:5
This is my own way to get longest palindrome. this will return the length and the palindrome word
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.

Categories

Resources