How to fix this infinite loop? - java

I put in system print outs to see where the problem was, and 2 and 7 were the two that kept repeating in the infinite loop. This part of the code is suppose to search a list and find the match that the user puts in, but every time i use the search the GUI freezes or is stuck in an infinite loop. Can anyone help me fix this ?
Here is the code i have:
if (whichOne.equals("Search"))
{
System.out.println("1");
String[] results = new String [5];
int count = 1;
list.moveCursorToRear();
int last = list.cursor;
list.resetCursor();
while(list.hasNext() || list.cursor == last)
{
int found = list.search(searchField.getText());
String result = list.spaces[found].getData();
System.out.println("2");
if(current != found)
{
list.stepCursorBack();
System.out.println("3");
if(list.cursor == list.head)
{
results[count] = result;
System.out.println(results[count]);
list.spaces[current].setLink(list.spaces[found].getLink());
count++;
System.out.println("4");
}
else
{
results[count] = result;
System.out.println(results[count]);
list.spaces[current].setLink(list.spaces[list.cursor].getLink());
count++;
System.out.println("5");
}
list.getNext();
System.out.println("6");
}
else
{
//break;
//System.exit(0);
list.hasNext();
System.out.println("7");
}
}

else
{
//break;
//System.exit(0);
list.hasNext();
System.out.println("7");
}
I suspect you wanted list.getNext() here, and not hasNext().
However, without more code - and especially more information about this list, a definite answer might be impossible to be given.

Related

How do I implement the looping functionality in my BrainFuck Interpreter?

There's multiple questions here already, but I'll still proceed. This is a simple BrainFuck interpreter. I figured out all the other symbols, but I can't figure out how to implement loops. Can anyone help?
package com.lang.bfinterpreter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.lang.exceptions.TapeSizeExceededException;
public class Interpreter {
private Interpreter() {
super();
}
private static String getCode(final String inputFile) throws IOException {
String code = "";
// store the entire code
final BufferedReader br = new BufferedReader(new FileReader(inputFile));
for (String line = br.readLine(); line != null; line = br.readLine()) {
code += line;
}
br.close();
return code;
}
public static void interpret(final String inputFile) throws IOException,TapeSizeExceededException,IndexOutOfBoundsException {
// get the program as a string
final String code = getCode(inputFile);
// create the Turing tape (static size)
Character[] tape = new Character[12000];
Integer indexPointer = 0;
for (int i = 0; i != 12000; i++) {
switch (code.toCharArray()[i]) {
case ',':
tape[indexPointer] = (char) System.in.read();
break;
case '.':
System.out.println(tape[indexPointer]);
break;
case '+':
tape[indexPointer]++;
break;
case '-':
tape[indexPointer]--;
break;
case '>':
if (indexPointer == 11999) {
throw new IndexOutOfBoundsException();
}
else {
indexPointer++;
}
break;
case '<':
if (indexPointer == 0) {
throw new IndexOutOfBoundsException();
}
else {
indexPointer--;
}
break;
case '[':
// I have a feeling I'll need stack to store nested loops
break;
case ']':
// I have a feeling I'll need stack to store nested loops
break;
default:
break;
}
}
}
}
I have a feeling that I will need to use Stack, but I just can't seem to figure out how. I have constructed expression evaluators before... will this require the same logic?
The most challenging part, I suppose, is finding the matching brackets. After you find where the matching bracket is, you can just check tape[indexPointer]'s value, and set i to the position after it, which should be rather easy to do.
Given an opening bracket at index i in code, to find its matching close bracket, you just need to go to the right of i in code. You start with an stack with a single [ in it - this is the [ at i. Every time you encounter a new [, you push it onto the stack. Every time you encounter a ], you pop a [ from the stack - this ] you encountered matches the [ you popped! When you popped the last [ from the stack (i.e. when the stack becomes empty), you know you have found the matching close bracket of the open bracket at i.
In code, you don't even need a Stack. You can just use an int to encode how many elements are in the stack - increment it when you push, decrement it when you pop.
private static int findMatchingCloseBracketAfterOpenBracket(char[] code, int openBracketIndex) {
// parameter validations omitted
int stack = 1;
for (int i = openBracketIndex + 1; i < code.length ; i++) {
if (code[i] == '[') {
stack++;
} else if (code[i] == ']') {
stack--;
}
if (stack == 0) {
return i;
}
}
return -1; // brackets not balanced!
}
To find the matching [ of a ], the idea is same, except you go the other direction, and reverse the push and pop actions.
private static int findMatchingOpenBracketBeforeCloseBracket(char[] code, int closeBracketIndex) {
// parameter validations omitted
int stack = 1;
for (int i = closeBracketIndex - 1; i >= 0 ; i--) {
if (code[i] == '[') {
stack--;
} else if (code[i] == ']') {
stack++;
}
if (stack == 0) {
return i;
}
}
return -1; // brackets not balanced!
}
(Refactoring the code duplication here is left as an exercise for the reader)
Updated: here's example code. Before the main execution loop you scan the whole program for matches and store them in an array:
Stack<Integer> stack = new Stack<>();
int[] targets = new int[code.length];
for (int i = 0, j; i < code.length; i++) {
if (code[i] == '[') {
stack.push(i);
} else if (code[i] == ']') {
if (stack.empty()) {
System.err.println("Unmatched ']' at byte " + (i + 1) + ".");
System.exit(1);
} else {
j = stack.pop();
targets[i]=j;
targets[j]=i;
}
}
}
if (!stack.empty()) {
System.err.println("Unmatched '[' at byte " + (stack.peek() + 1) + ".");
System.exit(1);
}
And then inside the main execution loop you just jump to the precomputed location:
case '[':
if (tape[indexPointer] == 0) {
i = targets[i];
}
break;
case ']':
if (tape[indexPointer] != 0) {
i = targets[i];
}
break;
(Note, we jump to the matching bracket, but the for loop will still autoincrement i as usual, so the next instruction that gets executed is the one after the matching bracket, as it should be.)
This is much faster than having to scan through a bunch of code looking for the matching bracket every time a bracket gets executed.
I notice also: you probably want to convert code into an array once, and not once per instruction you execute. You probably want to run your "for" loop while i < codelength, not 12000, and you also probably want to compute codelength only once.
Definitely '.' should output only one character, not add a newline as well. Also, 12000 bytes of array is too small. 30000 is the minimum, and much larger is better.
Good luck!

Calculator dot function issue android

I am working on a calculator and practicing java and android development. Everything works fine except for the dot function. here is the problem(see the very last dot):
here are the codes:
case R.id.btn_dot:
if (dotSet) {
screenTV.append("");
} else if (isEmpty() || empty) {
screenTV.append("0.");
dotSet = true;
count++;
} else {
screenTV.append(".");
dotSet = true;
count++;
}
an operand:
ase R.id.btn_add:
if (isEmpty()) {
screenTV.append("");
} else if (screenTvGet().endsWith("+")) {
screenTV.append("");
} else if (!isEmpty()) {
screenTV.append("+");
dotSet = false;
empty = true;
resultSet = false;
count = 0;
}
break;
and a number:
case R.id.btn0:
if (resultSet) {
screenTV.append("");
} else if (isEmpty()) {
screenTV.append("");
} else {
screenTV.append("0");
empty = false;
}
Finally, the backspace function:
case R.id.btn_backspace:
String screenContent;
String screen = screenTV.getText().toString();
int screenMinusOne = screen.length() - 1;
String screenMinus = String.valueOf(screenMinusOne);
if (screen.endsWith("."))
dotSet = false;
if (isEmpty()) {
screenTV.setText("");
} else {
screenContent = screen.substring(0, screen.length() - 1);
screenTV.setText(screenContent);
}
break;
forget about the "count".
I believe you can see the whole picture. now I want somehow when I clear an operand with "BackSpace function" and the previous number has a dot in it, the dot button doesn't just add an '.' or "0." to the screen instead returns null or just adds this "". I hope my question is clear.
Remove dotSet. You don't need it.
Then, similar to how you do this for btn_add:
} else if (screenTvGet().endsWith("+")) {
screenTV.append("");
use a regex for btn_dot to check if there is a . in the last part of the text:
} else if (screenTvGet().matches(".*\\.\\d*")) {
screenTV.append("");

Calculate total number of if-else clauses(including nested)

Need to calculate the number of if-else clauses. I'm using java parser to do it.
What I've done till now:
I've obtained the count of all if and else-if clauses by using the function
node.getChildNodesByType(IfStmt.class))
Problem:
How do I count the else clauses?
This function ignores the "else" clause.
Example:
if(condition)
{
if(condition 2)
//
else
}
else if(condition 3)
{
if (condition 4)
//
else
}
else
{
if(condition 5)
//
}
In this case, I'd want the answer to be 8 but the size of the call will return 5 because it encounters only 5 "if's" and ignores the else clauses. Is there any function that can directly help me count the else clauses?
My code:
public void visit(IfStmt n, Void arg)
{
System.out.println("Found an if statement # " + n.getBegin());
}
void process(Node node)
{
count=0;
for (Node child : node.getChildNodesByType(IfStmt.class))
{
count++;
visit((IfStmt)child,null);
}
}
This answer has been solved on the following github thread.
The in-built methods of the java parser are more than sufficient to help out.
Answer:
static int process(Node node) {
int complexity = 0;
for (IfStmt ifStmt : node.getChildNodesByType(IfStmt.class)) {
// We found an "if" - cool, add one.
complexity++;
printLine(ifStmt);
if (ifStmt.getElseStmt().isPresent()) {
// This "if" has an "else"
Statement elseStmt = ifStmt.getElseStmt().get();
if (elseStmt instanceof IfStmt) {
// it's an "else-if". We already count that by counting the "if" above.
} else {
// it's an "else-something". Add it.
complexity++;
printLine(elseStmt);
}
}
}
return complexity;
}

Indent all lines after a certain character until another character

For an assignment we are creating a java program that accepts a java file, fixes messy code and outputs to a new file.
We are to assume there is only one bracket { } per line and that each bracket occurs at the end of the line. If/else statements also use brackets.
I am currently having trouble finding a way to indent every line after an opening bracket until next closing bracket, then decreasing indent after closing bracket until the next opening bracket. We are also required to use the methods below:
Updated code a bit:
public static void processJavaFile() {
}
}
This algorithm should get you started. I left a few glitches that you'll have to fix.
(For example it doesn't indent your { brackets } as currently written, and it adds an extra newline for every semicolon)
The indentation is handled by a 'depth' counter which keeps track of how many 'tabs' to add.
Consider using a conditional for loop instead of a foreach if you want more control over each iteration. (I wrote this quick n' dirty just to give you an idea of how it might be done)
public String parse(String input) {
StringBuilder output = new StringBuilder();
int depth = 0;
boolean isNewLine = false;
boolean wasSpaced = false;
boolean isQuotes = false;
String tab = " ";
for (char c : input.toCharArray()) {
switch (c) {
case '{':
output.append(c + "\n");
depth++;
isNewLine = true;
break;
case '}':
output.append("\n" + c);
depth--;
isNewLine = true;
break;
case '\n':
isNewLine = true;
break;
case ';':
output.append(c);
isNewLine = true;
break;
case '\'':
case '"':
if (!isQuotes) {
isQuotes = true;
} else {
isQuotes = false;
}
output.append(c);
break;
default:
if (c == ' ') {
if (!isQuotes) {
if (!wasSpaced) {
wasSpaced = true;
output.append(c);
}
} else {
output.append(c);
}
} else {
wasSpaced = false;
output.append(c);
}
break;
}
if (isNewLine) {
output.append('\n');
for (int i = 0; i < depth; i++) {
output.append(tab);
}
isNewLine = false;
}
}
return output.toString();
}

Else if condition being ignored?

I'm new to Java and i have to make a small application that will calculate GCD of up to 5 numbers.
If the input is nothing before 5 numbers have been entered, the application will calculate it on the already given numbers
Unfortunately my code seems to ignore my else if statement that will make sure it doesn't try to add "" to a int array.
This is the part that i am struggling on, i have already tried contains instead of equals but with no result.
Am i writing the !input.. wrong? The code runs correct when i try to add a 0, it will not execute the else if.
But if i enter "" to make the application run the first part of the if statement it will go to the else if after its done and try to add "" to the array which of course results in an error.
I'm sure its something small i am missing or am unaware of, but i can't seem to figure it out.
}else if(Integer.parseInt(input) != 0 || !input.equals(""));{
ggdGetallen[count] = Integer.parseInt(input);
count++;
txtGetal.selectAll();
}
Full code
private void txtGetalActionPerformed(java.awt.event.ActionEvent evt) {
String input = txtGetal.getText();
//Berekenen van het kleinste getal in het array
if(count > 4 || input.equals("")){
int kleinsteGetal = ggdGetallen[0];
for (int getal : ggdGetallen){
if (getal < kleinsteGetal && getal != 0){
kleinsteGetal = getal;
}
}
boolean isDividableBy;
boolean ggdFound = false;
while(!ggdFound){
for (int getal : ggdGetallen) {
if (getal != 0){
isDividableBy = (getal % kleinsteGetal == 0);
ggdFound = true;
if(!isDividableBy){
kleinsteGetal--;
ggdFound = false;
break;
}
}
}
}
lblResultaat.setText(String.format("De grootste gemene deler is %d", kleinsteGetal));
}else if(Integer.parseInt(input) != 0 || !input.equals(""));{
ggdGetallen[count] = Integer.parseInt(input);
count++;
txtGetal.selectAll();
}
}
remove semicolon from your else if.

Categories

Resources