Java Array Bound Exception - java

I'm trying to make a program for a password security, but many times I get Java Array Index Out of Bounds Exception...I tried to fix, but nothing, this is my code:
import java.util.Arrays;
public class BruteForce {
public static void main(String[] args) {
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true) {
if (attempt.equals(password)) {
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while (index >= 0) {
if (cg[index] == cs[cs.length - 1]) {
if (index == 0) {
cg = new char[cg.length + 1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString() {
return String.valueOf(cg);
}
}
When I try to add special char(s):
import java.util.Arrays;
public class BruteForce
{
public static void main(String[] args)
{
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true)
{
if (attempt.equals(password))
{
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength)
{
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment()
{
int index = cg.length - 1;
while(index >= 0)
{
if (cg[index] == cs[cs.length-1])
{
if (index == 0)
{
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
}
else
{
cg[index] = cs[0];
index--;
}
}
else
{
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString()
{
return String.valueOf(cg);
}
}
And I get something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -65

The difference between
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
and
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##"
is that in the first case, the characters are in ascending order (characters in java have a value).
Arrays.binarySearch requires the array to be in ascending order.
If you use
"#.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
instead (or use Arrays.sort in the BruteForce constructor) it should work.
Always remember to post the exact code that you are using!

Related

NZEC error for ACODE spoj

I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.

How can I continue permutation/combination where I stopped the program?

It's my second time asking here and straight to the point. I can't seem to find a solution and I know it's not impossible. I wrote a java program that can generate a set of combination of any length, when I stop the program I don't want to start from the beginning how can I pick up from where I stopped?
Thanks.
Example (for length 3):
If I start from aaa ==> 9zI and I stop the program here, I don't want to start from aaa all over but start from 9zI and continue to 999. I just want to continue from where I left off.
public class Main {
public static void main(String[] args) {
S_Permutation sp = new S_Permutation();
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
FileClass.fileExist("new.txt", true);
System.out.println("");
sp.permutation(text, "", 7, "sha256.txt","Kaaaaaa");
}
}
=====================================================================
public class S_Permutation {
private List<String> permutation;
public S_Permutation() {
permutation = new ArrayList<>();
}
public boolean saveThis(String words, char a, int limit) {
int count = 0;
limit++;
for (char character : words.toCharArray()) {
if (count == limit) {
return false;
}
if (character == a) {
count++;
} else {
count = 0;
}
}
return count < limit;
}
private int counter = 0;
private boolean seen = false;
public void permutation(String str, String prefix, int lengthOfPermutationString, String filename, String startPoint) {
if (prefix.equalsIgnoreCase(startPoint))
{
seen = true;
}
if (counter == 0) {
if (startPoint.length() != lengthOfPermutationString) {
for (int i = startPoint.length(); i < lengthOfPermutationString; i++) {
startPoint += str.charAt(0);
}
}
counter = -45;
}
if (prefix.length() == lengthOfPermutationString) {
boolean savethis = true;
for (int i = 0; i < prefix.length(); i++) {
savethis = this.saveThis(prefix, prefix.charAt(i), 13);
if (!savethis) {
break;
}
}
if (savethis && seen) {
System.out.println(prefix);
//permutation.add(prefix);
}
} else {
for (int i = 0; i < str.length(); i++) {
if (permutation.size() == 1000) {
FileClass.WriteFile("new.txt", permutation);
permutation.clear();
}
permutation(str, prefix + str.charAt(i), lengthOfPermutationString, filename, startPoint);
}
FileClass.WriteFile("new.txt", permutation);
permutation.clear();
}
}
}
=========================================================================
public class FileClass {
public static boolean WriteFile(String filename, List<String> doc) {
try {
if (!filename.contains(".txt")) {
filename += ".txt";
}
RandomAccessFile raf = new RandomAccessFile(filename, "rw");
String writer = "";
writer = doc.stream().map((string) -> string + "\n").reduce(writer, String::concat);
raf.seek(raf.length());
raf.writeBytes(writer);
raf.close();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Error");
new Scanner(System.in).nextLine();
return false;
}
return true;
}
static RandomAccessFile raf;
public static boolean fileExist(String filename, boolean delete){
File file = new File(filename);
if (file.exists() && delete)
{
return file.delete();
}
return file.exists();
}
public static void WriteFile(String filename, String text) {
try {
if (!filename.contains(".txt")) {
filename += ".txt";
}
raf = new RandomAccessFile(filename, "rw");
long length = raf.length();
raf.setLength(length + 1);
raf.seek(raf.length());
raf.writeBytes(text + "\n");
} catch (Exception e) {
}
}
private static void write(List<String> records, Writer writer) throws IOException {
for (String record : records) {
writer.write(record);
}
writer.flush();
writer.close();
}
public static void stringWriter(List<String> records, String filename) {
try {
File file = new File(filename);
FileWriter writer = new FileWriter(file, true);
write(records, writer);
} catch (Exception ex) {
System.out.println(ex.getMessage());
new Scanner(System.in).nextLine();
}
}
public static boolean CloseFile() {
try {
raf.close();
return true;
} catch (Exception e) {
return false;
}
}
}
In order to add a "Resume" mechanism, you need to make your program idempotent. One way to do it, is instead of saving the permutations - save to file the parameters that are sent to permutation on each iteration:
now each time that the program starts, it will check what were the last parameters that permutation was called with (the last line in the file), and start from there (when the program starts on the first time, nothing will be written in the file - so it will start from the beginning).
After that the recursion finished, we can call another method that will go over the lines of the file, and read only the permutations (ignoring the other parameters) and write them into a cleaner "final_result.txt" file.
Needless to say that this implementation is more costly (all the additional reads and write from disc) but that's the tradeoff for having it support "resume" operation.
To save/restore process in the middle of its work, you need something we can call a "state" and implement generating combinations in iterative way.
In my implementation the "state" is pos object (I assume set and k will not change on "resume").
My implementation of the problem would be following:
public class RepeatComb {
private int[] pos;
private String set;
public RepeatComb(String set, int k) {
this.set = set;
pos = new int[k];
}
public int[] getState() {return Arrays.copyOf(pos, pos.length);}
public void resume(int[] a) {pos = Arrays.copyOf(a,a.length);}
public boolean next() {
int i = pos.length-1;
for (int maxpos = set.length()-1; pos[i] >= maxpos; ) {
if (i==0) return false;
--i;
}
++pos[i];
while (++i < pos.length) pos[i]=0;
return true;
}
public String getCur() {
StringBuilder s = new StringBuilder(pos.length);
for (int i=0; i < pos.length; ++i)
s.append(set.charAt(pos[i]));
return s.toString();
}
public static void main(String[] args) {
int[] state;
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
RepeatComb comb = new RepeatComb(text, 3);
int stop = 10; //break after 10
do {
if (stop-- == 0) break;
System.out.println(comb.getCur());
} while (comb.next());
//save state
state = comb.getState();
System.out.println("---------");
//resume (with the same args: text,3)
stop = 10; //break after 10
comb = new RepeatComb(text, 3);
comb.resume(state); // resume here
do {
if (stop-- == 0) break;
System.out.println(comb.getCur());
} while (comb.next());
}
}
Update: I've added functions for getting state and resuming from it
and example of use. state array can be saved in file, then restored.

Hangman checking used guesses form user

I am looking for some help scanning the array for the used letters in the user input and tell them, so I am lost at this point.
/**
*
*/
package Hangman;
import java.io.IOException;
/**
* #author
*
*/
public class Hangman {
static int choice;
static String solve;
static String promt;
static String guess;
static char chaGuess;
static char[] guesses = new char[25];
static char[] check;
static int counter = 1;
static boolean contine;
public static void main(String[] args) throws IOException, InterruptedException {
playerOne();
for (int i = 0; i < 300; i++) {
System.out.println(" ");
}
while (contine = true) {
playerTwo();
choiceMade(choice);
}
}
public static String playerOne() throws IOException {
System.out.println("Welcome player one");
promt = ConsoleUI.promptForInput("Enter a Phrase or word for Player Two to guess", true);
return promt;
}
public static int playerTwo() throws IOException {
String[] ask = new String[3];
ask[0] = "Give up";
ask[1] = "Guess a letter";
ask[2] = "Solve the puzle";
choice = ConsoleUI.promptForMenuSelection(ask, true);
return choice;
}
public static void choiceMade(int c) throws IOException {
if (c == 0) {
contine = false;
System.out.println("Thank you for playing");
System.exit(0);
}
if (c == 1) {
guess = ConsoleUI.promptForInput("Enter your guess", true);
guessChar(guess);
contine = true;
} else if (c == 2) {
solve = ConsoleUI.promptForInput("Enter your answer", true);
if (solve.equals(promt)) {
System.out.println("You solved it you're amazing");
contine= false;
} else {
System.out.println("Sorry you guessed it wrong.");
System.exit(0);
contine= false;
}
}
}
public static char guessChar(String g) {
chaGuess = g.charAt(0);
promt = promt.replace(" ", "");
check = promt.toCharArray();
if(guesses[counter -1] != chaGuess)
if (chaGuess >= 'a' && chaGuess <= 'z' || chaGuess >= 'A' && chaGuess <= 'Z') {
guesses[counter] = chaGuess;
System.out.println(guesses);
}
if(guesses[counter - 1] == chaGuess)
{
System.out.println("You all ready guessed that");
}
}
counter++;
return chaGuess;
}
}
Use a string, append each used guess to the end of it, and then just use indexOf()

Java NoSuchMethodError

I am trying to understand stacks with Objects, so I typed this out, but the problem is that I am getting this really weird message that I can't make sense of. It says "Exception in thread "main" java.lang.NoSuchMethodError: Stack.push(Ljava/lang/Object;)V
at TestObjectStack.main(TestObjectStack.java:12)". I googled it, but I still can't figure out what I'm doing wrong. I redid the main method header, but that didn't fix it. Does anyone have any suggestions or insight that I am missing? Thanks a lot!:
public class TestObjectStack
{
public static void main(String[] args)
{
Object o;
Stack test = new Stack();
test.push("Fred");
test.push(20);
test.push(new ThingB("Barney", 42));
Stack copy = new Stack(test);
System.out.println("Stack test: " + test);
System.out.println(test.pop());
System.out.println("Stack test: " + test);
System.out.println("Stack copy: " + copy);
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a String");
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a string");
if(test.isEmpty()) System.out.println("empty");
}
}
class ThingB
{
private String _name;
private int _ID;
public ThingB(String name, int ID)
{
_name = name;
_ID = ID;
}
public String toString()
{
return "Thing B - name - " + _name + " ID = " + _ID;
}
}
class Stack
{
private Object[] _store;
private int _top;
private static final int MAXSIZE = 50;
public Stack()
{
_store = new Object[MAXSIZE];
_top = 0;
}
public Stack(Stack other)
{
_store = new Object[other._store.length];
_top = other._top;
for(int i = 0; i < _top; ++i)
{
_store[i] = other._store[i];
}
}
public boolean isEmpty()
{
return (_top == 0);
}
public void push(Object item)
{
if(_top >= _store.length)
{
Object[] temp = new Object[_store.length+ MAXSIZE];
for(int i = 0; i < _top; ++i)
{
temp[i] = _store[i];
}
_store = temp;
}
_store[_top] = item;
++_top;
}
public Object pop()
{
if(_top == 0) return 0;
--_top;
return _store[_top];
}
public String toString()
{
String s = "";
s = s + "--Top--";
for(int i = _top-1; i >= 0; --i)
{
s = s + " " + _store[i];
}
s = s + "--Bottom--";
return s;
}
}
I executed your code in the IDE: IntelliJ IDEA. And I have the following result:
Stack test: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
Thing B - name - Barney ID = 42
Stack test: --Top-- 20 Fred--Bottom--
Stack copy: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
20
Not a String
Fred
String length = 4
empty
Your source code is working fine, maybe you need to adjust your IDE parameters. Try with a simple "Hello World" program.
Best regards,
Alvaro

Java help! implementing a 2d array of a certain object, the object has multiple private data types and objects

I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.

Categories