Program freezes when trying to analyse a string - java

I am writing on a method which should analyse a polynomial given by the user (as String) and do different stuff with it in the future. At the moment, I was trying to test the code I have so far but whenever I execute the program, it freezes and after sitting for hours in front of the computer I still can't find the culprit in it.
I was testing if a polynomial of one variable could be analysed and then re-printed, but it doesn't work.
I hoped anyone could help me out on this.
Here's the code block in the main which executes the method, the string userInput is a polynomial (e.g 4x-6x^2):
String userInput = inputArea.getText().trim();
Monomials monomials = new Monomials();
monomials.analyse(userInput);
Here's the class monomials with its method analyse():
//Class Monomial
class Monomials
{
private int coeff = 0;
private char var;
private int addpow = 1;
private int pow;
private char powsign = '^';
private char minus = '-';
private boolean isnegative = false;
private String mono;
StringBuilder stringBuilder = new StringBuilder();
public int getCoeff(int coeff)
{
return coeff;
}
public void setCoeff(int coeff)
{
this.coeff = coeff;
}
public void setVar(char var)
{
this.var = var;
}
public void setPow(int pow)
{
this.pow = pow;
}
public String getMono(String monomials)
{
return mono;
}
// Method to further analyse user's input.
public void analyse(String polynomial)
{
//Split the poynomial into monomials and store them in an array list.
polynomial = polynomial.replaceAll("-","+-");
String polyParts[] = polynomial.split("\\+");
ArrayList<String> monomials = new ArrayList<String>(Arrays.asList(polyParts));
// Iterate the monomials.
for (int i = 0; i <= monomials.size(); i++)
{
String monomial = monomials.get(i);
// Analyse the monomial.
for (int x = 0; x <= monomial.length(); x++)
{
char c = monomial.charAt(x);
int countcoeff = 0;
int countvar = 0;
// check if negative.
if (c == minus)
{
isnegative = true;
x++;
}
// get the coefficient.
if (Character.isDigit(c))
{
while (Character.isDigit(c))
{
countcoeff++;
x++;
}
if (isnegative)
{
setCoeff(Integer.parseInt(monomial.substring(1, countcoeff)));
} else
{
setCoeff(Integer.parseInt(monomial.substring(0, countcoeff)));
}
}
// get the variable.
if (Character.isLetter(c))
{
char var = c;
while (Character.isLetter(var))
{
countvar++;
addpow++;
x++;
}
}
// get the power.
if (c == powsign)
{
countvar++;
x++;
while (Character.isDigit(c))
{
x++;
}
if (isnegative)
{
setPow(Integer.parseInt(monomial.substring(countcoeff+countvar+2, x)));
} else
{
setPow(Integer.parseInt(monomial.substring(countcoeff+countvar+1, x)));
}
pow += addpow;
}
}
if (isnegative)
{
stringBuilder.append(String.valueOf(minus));
}
stringBuilder.append(String.valueOf(coeff) + String.valueOf(var) + String.valueOf(powsign) + String.valueOf(pow));
mono = stringBuilder.toString();
monomials.set(i, mono);
}
for (int i = 0; i < monomials.size(); i++)
{
System.out.println(String.valueOf(monomials.get(i)));
}
} // End of method analyse().
} // End of class Monomial

You have a couple of loops which will never exit:
while (Character.isDigit(c))
{
countcoeff++;
x++;
}
How to find out Stuff like that?
If you use Eclipse, you can run your Code in Debug Mode, switch to the debug-perspective and click on the yellow Suspend-Symbol. That will suspend your Program, in the Debug-View you can see in which line the Thread is "hanging", if you click on it it will open the source-code.
If you don't use an IDE with that function, you can use the JDK-Tools: Use jps to find out the ID of your program:
C:\jdk\jdk8u45x64\jdk1.8.0_45\bin>jps
7216
5688 Jps
6248 Monomials
Then use jstack to print a stack trace of all running threads:
C:\jdk\jdk8u45x64\jdk1.8.0_45\bin>jstack 6248
[other threads omitted]
"main" #1 prio=5 os_prio=0 tid=0x000000000203e800 nid=0x1b2c runnable [0x000000000201e000]
java.lang.Thread.State: RUNNABLE
at Monomials.analyse(Monomials.java:77)
at Monomials.main(Monomials.java:10)

one of your loop is running infinitely. You should replace it with if condition.
while (Character.isDigit(c))
{
countcoeff++;
x++;
}
replace it with
if (Character.isDigit(c))
{
countcoeff++;
x++;
}
Or you could use break statement here.

As the others stated already
while (Character.isDigit(c))
is your problem.
But you have that two times not one time, so both are a problem. The 2nd isn't a real problem, because Character.isDigit and if (c == powsign) canĀ“t be both true at the same time, so the 2nd inifit loop never gets executed, which brings me to the next point: bugs.
In your code there are a tremendous amount of them :-D
Both for loops are running to far (<= .size() & <= .length()), replace <= with <.
Also, the x++ placed around in your code are wrong. x gets incremented automaticially and if you want to exit the loop early, use break; or use continue; if you want to jump to the next iteration early.

Related

how to get calculator to accept new numbers after equal sign is pressed? java

i am doing an exercise to create a simple calculator in java.
i want the calculator to keep taking numbers after the equal sign is pressed. so if i press "10+10 =" the result will be 20, and if I want to press "+1 = " and the result will be 21. or if I want to subtract as well.
my code is below. im sure the change has to be made to the "equals" portion of the code but i am unsure where/how to begin.
public int getDisplayValue()
{
return displayValue;
}
public void numberPressed(int number)
{
currentValue = (currentValue * 10) + number;
displayValue = currentValue;
}
private void applyPreviousOperation()
{
if (previousOp == '+')
{
heldValue = heldValue + currentValue;
displayValue = heldValue;
}
else if (previousOp == '-')
{
heldValue = heldValue - currentValue;
displayValue = heldValue;
}
else {
heldValue = currentValue;
}
}
public void plus()
{
applyPreviousOperation();
previousOp = '+';
currentValue = 0;
}
public void minus()
{
applyPreviousOperation();
previousOp = '-';
currentValue = 0;
}
public void equals()
{
applyPreviousOperation();
previousOp = ' ';
currentValue = 0;
heldValue = 0;
}
public void clear()
{
displayValue = 0;
previousOp = ' ';
}
}
You need to define your question more clearly.
what's the calculator flow should be. You describe an operation that contradicts a simple a+b.
It really matters how you input the numbers, If for example the very first operation is texted "a+b" ,"a-b" .... than you can keep it as currentValue.
than next opperations will be calculated against currentValue.
Have a variable called defaultOperand. When the equals button is pressed, update the defaultOperand variable with the output of the operation. It becomes the default left side operand. If an operation is inputted without a left side operand, then use the value in the defaultOperand as the default left hand operand.

String index out of range in Java

I am aware there are multiple threads like my assignment below, but I just can't figure it out. I can't exactly figure out the mistake. Help would be appreciated.
I am trying to do this program:
Everything works fine unless I input the same chains or similar (for example ACTG and ACTG or ACTG and ACTGCCCC), when it tells me
string index out of range
This is that part of my code:
int tries=0;
int pos=-1;
int k;
for (int i=0; i<longDNA.length(); i++) {
tries=0;
k=i;
for (int j=0; j<shortDNA.length(); j++) {
char s=shortDNA.charAt(j);
char l=longDNA.charAt(k);
if (canConnect(s,l)) {
tries+=1;
k+=1;
}
}
if (tries==shortDNA.length()-1) {
pos=i-1;
break;
}
}
Let's call the two DNA strings longer and shorter. In order for shorter to attach somewhere on longer, a sequence of bases complementary to shorter must be found somewhere in longer, e.g. if there is ACGT in shorter, then you need to find TGCA somewhere in longer.
So, if you take shorter and flip all of its bases to their complements:
char[] cs = shorter.toCharArray();
for (int i = 0; i < cs.length; ++i) {
// getComplement changes A->T, C->G, G->C, T->A,
// and throws an exception in all other cases
cs[i] = getComplement(cs[i]);
}
String shorterComplement = new String(cs);
For the examples given in your question, the complement of TTGCC is AACGG, and the complement of TGC is ACG.
Then all you have to do is to find shorterComplement within longer. You can do this trivially using indexOf:
return longer.indexOf(shorterComplement);
Of course, if the point of the exercise is to learn how to do string matching, you can look at well-known algorithms for doing the equivalent of indexOf. For instance, Wikipedia has a category for String matching algorithms.
I tried to replicate your full code as fast as I could, I'm not sure if I fixed the problem but you don't get any errors.
Please try it and see if it works.
I hope you get this in time and good luck!
import java.util.Arrays;
public class DNA {
public static void main(String[] args) {
System.out.println(findFirstMatchingPosition("ACTG", "ACTG"));
}
public static int findFirstMatchingPosition(String shortDNA, String longDNA) {
int positionInLong = 0;
int positionInShort;
while (positionInLong < longDNA.length()) {
positionInShort = 0;
while(positionInShort < shortDNA.length()) {
String s = shortDNA.substring(positionInShort, positionInShort + 1);
if(positionInShort + positionInLong + 1 > longDNA.length()) {
break;
}
String l = longDNA.substring(positionInShort + positionInLong, positionInShort + positionInLong + 1);
if(canConnect(s, l)) {
positionInShort++;
if(positionInShort == shortDNA.length()) {
return positionInLong;
}
} else {
break;
}
}
positionInLong++;
if(positionInLong == longDNA.length()) {
return -1;
}
}
return -1;
}
private static String[] connections = {
"AT",
"TA",
"GC",
"CG"
};
private static boolean canConnect(String s, String l) {
if(Arrays.asList(connections).contains((s+l).toUpperCase())) {
return true;
} else {
return false;
}
}
}
I finally changed something with the k as Faraz had mentioned above to make sure the charAt does not get used when k overrides the length of the string and the program worked marvelously!
The code was changed to the following:
int tries=0;
int pos=-1;
int k;
for (int i=0; i<longDNA.length(); i++) {
tries=0;
k=i;
for (int j=0; j<shortDNA.length(); j++) {
if (k<longDNA.length()) {
char s=shortDNA.charAt(j);
char l=longDNA.charAt(k);
if ((s=='A' && l=='T') || (s=='T' && l=='A') || (s=='G' && l=='C') || (s=='C' && l=='G')) {
tries+=1;
k+=1;
}
}
}
if (tries==shortDNA.length()) {
pos=i;
break;
}
}
I am not sure how aesthetically pleasing or correct this excerpt is but - it completely solved my problem, and just 2 minutes before the deadline! :)
A huge thanks to all of you for spending some time to help me!!

Java Program does not give the output for values of n>6, Why?

import java.util.*;
class A{
static int count=0;
static String s;
public static void main(String z[]){
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println(noOfBouncy(n));
}
public static int noOfBouncy(int k){
int limit=(int)Math.pow(10,k);
s=new String("1");
int num=Integer.parseInt(s);
while(num<limit){
if(isIncreasing(s) || isDecreasing(s) ){
}
else{
count++;
}
num++;
s=new String(Integer.toString(Integer.parseInt(s)+1));
}
count=limit-count;
return count;
}
}
public static boolean isIncreasing(String s){
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)>s.charAt(i+1)){
return false;
}
}
return true;
}
public static boolean isDecreasing(String s){
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)<s.charAt(i+1)){
return false;
}
}
return true;
}
I have given the definitions to the two functions used isIncreasing() & isDecresing()
The program runs well for the value of n<7 but does not respond for values above it, Why ?
I accept the programming style is very immature,please ignore.
I've tried to execute it with n=7 and it finishes in 810ms, returning 30817.
However, I recommend to you to optimize the performance of your program by saving unnecessary object instantiation: It will be better if you maintain the counter in num, and convert it to string just once, at the beginning of the loop:
int num=1;
while (num < limit)
{
s=Integer.toString(num);
if (isIncreasing(s) || isDecreasing(s))
{
}
else
{
count++;
}
num++;
}
Like this it takes just 450ms to finish.
The program was not actually stuck but it is taking way too much time to complete its execution when value of 'n' is larger.
So now the question is, I need to optimize the code to take minimum time #Little have an optimization bit that's not enough.
Any hint would be appreciable.
To increase the performance you should avoid the conversation to String and do the check with numbers.
As it doesn't matter for the result if you start the comparison from left to right or from right to left one computational solution could be.
as pseudo code
1) compare the value of the right most digit with the digit on it's left
2) is it lower --> we found a decreasing pair
3) else check if it is bigger --> we found an increasing pair
4) else --> not a bouncy pair
5) if we found already one decreasing and one increasing pair it's bouncy number
6) divide the number by ten if it's bigger then ten repeat with step 1)
The method to check if it's a bouncy number could look like this
static boolean isBouncyNumber(int number) {
boolean increasingNumber = false;
boolean decreasingNumber = false;
int previousUnitPosition = number % 10;
int remainder = number / 10;
while (remainder > 0) {
// step 1
int currentUnitPosition = remainder % 10;
if (currentUnitPosition > previousUnitPosition) {
// step 2
decreasingNumber = true;
} else if (currentUnitPosition < previousUnitPosition) {
// step 3
increasingNumber = true;
}
// step 5
if (decreasingNumber && increasingNumber) {
return true;
}
// step 6
previousUnitPosition = currentUnitPosition;
remainder = remainder / 10;
}
return decreasingNumber && increasingNumber;
}

For loop in the backEnd class not working?

The for loop in the backEnd class - CompareGuess method is not working.
....................................................................................................................................................
public class frontEnd
{
public static void main (String args[])
{
int GetGuess = 0;
backEnd e1 = new backEnd();
e1.InitializeArray();
while(e1.chanceCounter<3)
{
System.out.println("Enter a number");
GetGuess = (int)(Math.random()*6);
System.out.println(GetGuess);
e1.UserGuess(GetGuess);
e1.CompareGuess();
if(e1.suc!=1)
{
System.out.println("It is a miss");
}
}
System.out.println("Sorry, no chances left");
}
}
class backEnd
{
int Guess;
int HitCounter=0;
int[] abc = new int[7] ;
int chanceCounter=0;
int suc = 0;
int x =0;
public void InitializeArray()
{
abc[1]= 3;
abc[2] = 5;
abc[4] = 1;
}
public void UserGuess(int guess)
{
Guess = guess;
}
public void CompareGuess()
{
for(x=0; x<=6; x++ )
{
if (abc[x] == Guess)
{
System.out.println("It is a hit");
chanceCounter = chanceCounter + 1;
suc = 1;
}
break;
}
}
}
The problems seems to be here:
for(x=0; x<=6; x++ )
{
if (abc[x] == Guess)
{
System.out.println("It is a hit");
chanceCounter = chanceCounter + 1;
suc = 1;
}
break; //Here
}
Look what your code does:
Your for loop makes the first iteration, taking x = 0
If abc[x] it's equals to Guess then your program executes the code inside the if statement. After, the break statement will be executed.
If not, it just execute the break statement
So, in both cases, the break statement it's going to be executed in the first iteration (therefore, your program will go out of the for loop).
Look that your program only will execute your first iteration but not the rest (x = 1, x = 2 [....] x =6).
If you want that your for loop go through all the iterations you have to remove your break statement from your code.
I expect it will be helpful for you!
Since your game is all about guessing. I took a guess at what it's supposed to do then I rewrote your code, because I couldn't bear to leave it as it was. I left it as similar to your as I can cope with:
public class FrontEnd
{
public static void main (String args[])
{
int getGuess = 0;
BackEnd e1 = new BackEnd();
e1.initializeArray();
int totalChances = 3;
while(e1.chanceCounter < totalChances)
{
System.out.println("Enter a number");
getGuess = (int)(Math.random()*6);
System.out.println(getGuess);
e1.userGuess(getGuess);
e1.compareGuess();
if(!e1.suc)
{
System.out.println("It is a miss");
}
e1.suc = false;
e1.chanceCounter++;
}
System.out.println("Sorry, no chances left");
System.out.println("you scored " + e1.hitCounter + " out of " + totalChances);
}
}
class BackEnd
{
int guess;
int hitCounter = 0;
int[] abc = new int[7] ;
int chanceCounter = 0;
boolean suc = false;
public void initializeArray()
{
abc[1] = 3;
abc[2] = 5;
abc[4] = 1;
}
public void userGuess(int guess)
{
this.guess = guess;
}
public void compareGuess()
{
for( int x = 0; x <= 6; x++ )
{
if (abc[x] == guess)
{
System.out.println("It is a hit");
hitCounter++;
suc = true;
break;
}
}
}
}
As others have said the break statement is supposed to be inside the conditional block. Also it looks like you were forgetting to reset the suc variable after each guess. Also you weren't using hitCounter at all. I assumed it's for counting correct guesses, which left me wondering when to update chanceCounter: either after each guess or after each wrong guess. I didn't know if the guesser was supposed to run out of chances after 3 guesses, or after 3 wrong guesses. I went with the former and update the chanceCounter after every guess.
guesses of 0 are considered correct because they match with all the entries in the abc array that are not initialised.

Optimal Algorithm: how to stop my if statement when I don't find the number that matches with my number that I am going to replace it with

I am doing FIFO LRU and Optimal. I have a problem for Optimal ( replace it with the one that we will not use in the longest time, so the furthest one). I got it to replace my fram number with the one that i dont use in the longest. But the problem is that when the number that i want to replace it with doesn't even exist HOW DO I STOP MY IF statesman? And im not sure which "if" to stop? i tried this:
public int toss( int pr )
{
// if we get the same number just return -1
for (int s=numberOfFrames-1; s>=0; s--)
{
// if we get the same number dont kick anything
if ( pr == fram[s])
{
return -1;
}
}
// find which frame to replace
int look2 = 0; // this is the co for the number you want to replace with.
// next time it is used.
int co = 0; // this is index to pra.
int r = -1;
for ( int d=numberOfFrames-1; d>=0; d--)
{
lookFor(d,r);
}
if (r == -1)
{
//item not found, handle however you want, one suggestion is:
return -1; //have the caller handle this correctly
}
else
{
int q = fram[r]; // remember 2 which is page we are getting raid off
fram[r] = pra[co]; // fram one we want to get raid off and replace it with the pr
return q; // return the one we kicked
}
}
int co = 0;
int look2 = 0;
public int lookFor(int d, int r)
{
for( int f=co; f>=0; f++) // f looping for pra
{
co = tossCallCount++;
System.out.println("here");
if( fram[d] == pra[f])
{
System.out.println("by"+pra[f]);
if(look2<=f)
{
System.out.println("hi"+fram[d]);
r = d;
look2 = f;
break;
}
}
}
return d;
}
}
If you break out of your loop at the place you have the System.exit(0), you will only ever look at pra[co] (because f=co, rather than looping through with pra[f]). You likely want to put the break inside of the if, so when you find the match, you stop this loop. But this will just exit you from the inner for loop, and you probably want to stop looping entirely. See Breaking out of nested loops in Java for more information on breaking multiple loops.
int r = -1;
for ( int d=numberOfFrames-1; d>=0; d--) {
for( int f=co; f>=0; f++) {
if( fram[d] == pra[f]) {
if(look2<=f) {
r = d;
look2 = f;
break;
}
}
}
}
if (r == -1) {
//item not found, handle however you want, one suggestion is:
return -1; //have the caller handle this correctly
} else {
int q = fram[r]; // remember 2 which is page we are getting raid off
fram[r] = pra[co]; // fram one we want to get raid off and replace it with the pr
return q; // return the one we kicked
}

Categories

Resources