I am a newbie Computer Science high school student and I have trouble with a small snippet of code. Basically, my code should perform a basic CLI search in an array of integers. However, what happens is I get what appears to be an infinite loop (BlueJ, the compiler I'm using, gets stuck and I have to reset the machine). I have set break points but I still don't quite get the problem...(I don't even understand most of the things that it tells me)
Here's the offending code (assume that "ArrayUtil" works, because it does):
import java.util.Scanner;
public class intSearch
{
public static void main(String[] args)
{
search();
}
public static void search()
{
int[] randomArray = ArrayUtil.randomIntArray(20, 100);
Scanner searchInput = new Scanner(System.in);
int searchInt = searchInput.nextInt();
if (findNumber(randomArray, searchInt) == -1)
{
System.out.println("Error");
}else System.out.println("Searched Number: " + findNumber(randomArray, searchInt));
}
private static int findNumber(int[] searchedArray, int searchTerm)
{
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
}
}
This has been bugging me for some time now...please help me identify the problem!
I don't know about the infinite loop but the following code is not going to work as you intended. The i++ can never be reached so i will always have the value 0.
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
You probably mean this:
for (int i = 0; i < searchedArray.length; i++)
{
if (searchedArray[i] == searchTerm)
{
return i;
}
}
return -1;
I don't know what is the class ArrayUtil (I can not import is using my Netbeans). When I try to change that line with the line int[] randomArray = {1 , 2, 3, 5, 7, 10, 1 , 5}; It works perfectly.
And you should change the loop condition. I will not tell you why but try with my array and you will see the bug soon. After you see it, you can fix it:)
There are 4 basic issues here.
1. Putting searchedArray[i] == searchTerm before i < searchedArray.length can result in an out-of-bounds exception. You must always prevent that kind of code.
2. Your intention seems to be the opposite of your code. Your method name implies finding a search term. But, your code implies that you want to continue your loop scan until the search term is not found, although your loop won't do that either. Think of "for (; this ;) { that } " as "while this do that".
3. Place a break point at the beginning of "search". Then, with a small array, step through the code line by line with the debugger and watch the variables. They don't lie. They will tell you exactly what's happening.
4. Please use a standard IDE and compiler, such as Eclipse and Sun's JDK 6 or 7. Eclipse with JDK 7 is a serious combination that doesn't exhibit a strange "infinite loop" as you describe above.
Related
A couple days ago I started learning Java and I implemented an algorithm which outputs all results of the MU-puzzle over a certain amount of iterations.
The code worked perfectly fine until I decided to make it so that you have to enter the amount of iterations through a JOptionPane window.
When I tried to import javax.swing.JOptionPane, that didn't work, so I looked up a tutorial, which has helped me before in that matter, however, somehow it didn't work this time (this is the tutorial in case you're curious: https://www.youtube.com/watch?v=GBzwSf8bEdQ).
Or I guess I should really say that it did fix the issue of import javax.swing.JOptionPane not being recognized by Eclipse (i.e. the red, squiggly line underneath it is gone).
But now whenever I try and access any member variables/functions of JOptionPane the program gives me an error and Intellisense doesn't even show the them in the first place, all it shows is class: Class<javax.swing.JOptionPane>.
Now all that happens when I try to compile my code is that I get this error message (even if I revert it back to its previously functional state):
So right now this is what my package (if that's the right term for it) looks like:
This is my code (again please note that I'm a beginner so it's not perfect)
This version is the one with JOptionPane:
(all that was different in the other version that worked (but doesn't anymore), was that the JOptionPane line is missing, the function miuExecute() did not exist and the code inside miuExecute() was put directly into the main function with iterations being just a fixed positive integer)
package miuSystem;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
miuExecute();
}
static void miuExecute() {
int iterations = JOptionPane.showInputDialog("Enter the amount of iterations you'd like to perform");
String input = "MI";
ArrayList<String> res = new ArrayList<String>();
ArrayList<String> miuIterations = new ArrayList<String>();
miuIterations.add(input);
for (int u = 0; u < iterations; u++) {
for(int q = 0; q < miuIterations.size(); q++) {
res.add(rule1(miuIterations.get(q)));
res.add(rule2(miuIterations.get(q)));
res.add(rule3(miuIterations.get(q)));
res.add(rule4(miuIterations.get(q)));
}
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res.size(); j++) {
if (j == i) {continue;}
else if (res.get(i).equals(res.get(j))) {
res.remove(i);
i--;
break;
}
}
}
System.out.println("Iteration #"+(u+1)+":");
System.out.println(res);
System.out.println();
miuIterations.clear();
for(String s : res) {
miuIterations.add(s);
}
res.clear();
}
}
static String rule1(String input) {
if (input.charAt((input.length())-1) == 'I') {
return input+"U";
}
else {
return input;
}
}
static String rule2(String input) {
String copy = "";
for (int i = 1; i<input.length(); i++)
{
copy = copy + input.charAt(i);
}
return input+copy;
}
static String rule3(String input) {
return input.replace("III", "U");
}
static String rule4(String input) {
return input.replace("UU","");
}
}
As already stated above, I tried following this tutorial (https://www.youtube.com/watch?v=GBzwSf8bEdQ) but it didn't work.
Googling my problem(s) (both on and off of StackOverflow) also yielded either no result at all / results that I don't understand yet and would take too long to understand instead of just asking or results that didn't help me.
Edit: as requested here is what I think was meant by "show us the contents of your module-info.java" (if not please just tell what else you need) the part of the image thats censored is obv. just my name, which i don't like.
enter image description here
I've written code for a foobar challenge that works in my IDE but not in the solutions file provided by foobar. Also, is there anyway to show the output even if the test fails? Possibly to with it being a static method or the input being {1, 2, 3, 4} whereas mine is working with new int {1,2,3,4,5}? My code is:
public static int solution(int[] l) {
List<Integer> numberList = Arrays.stream(l).boxed().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
while (true) {
StringBuilder number = new StringBuilder();
int i = 0;
while (i < numberList.size()) {
number.append(numberList.get(i));
i++;
}
List<Integer> startingList = Arrays.stream(l).boxed().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
int testValue = numberList.size();
for (Integer integer : numberList) {
if (startingList.contains(integer)) {
startingList.remove(integer);
testValue--;
}
}
if (testValue == 0) {
int f = 0;
int total = 0;
while (f < numberList.size()) {
total = total + numberList.get(f);
f++;
}
if (total % 3 == 0) {
StringBuilder answer = new StringBuilder();
int c = 0;
while (c < numberList.size()) {
answer.append(numberList.get(c));
c++;
}
return Integer.parseInt(answer.toString());
}
}
Integer nextNumber = Integer.parseInt(number.toString()) - 1;
String[] stringArray = valueOf(nextNumber).split("");
numberList = new ArrayList<>();
for (String s : stringArray) {
numberList.add(Integer.parseInt(s));
}
}
}
Pretty rubbish but it does the job (at least in my IDE!)
As mentioned in a comment on the question, you should undoubtedly give some more context for your questions (since it is pretty unclear what your code is intended to do). I'm pretty sure I've inferred the actual question from context though, and I can suggest a couple of problems. In short (and a pretty good assumption for coding in general) the issue is not the environment running your code incorrectly, but rather your code having missed bugs due to lack of comprehensive testing. If you had presented a number of sample inputs and results I would guess you would have seen that your solution does not work locally.
The Java List.remove() method takes an index rather than a value to be removed (https://docs.oracle.com/javase/8/docs/api/java/util/List.html). The way it is used in your sample will result in throwing exceptions in a number of circumstances. Proper testing would have identified this (and will pick up most of your problems if fixed)
What happens if there is no solution? For example, an input of {1, 1} is going to get into a pretty messy state as the 'nextNumber' value slips below 0. You should know what the desired behavior is in this situation, and your tests should cover it before you try to upload a solution
This happened to me as well, but I then realized that my compilation was not successful because I have not imported the package that I am using at the top of the source code file like all java programs are write
I tried this a lot, and debugged it a few times, everything seems to be working and largest prime does indeed become the largest prime even if it takes rather long.
I can't get the printed value from System.out.println. I could find it through the debugger but the value is too high to find fast just holding down step over.
It compiles as well so I am stumped about what's the issue here. I would be very happy to know what I did wrong.
Edit: The reason why I wrote this code in the first place is because in the site project euler it asked for the largest prime value that when divided with the value of primer gave a whole number.
Is there a way at least that would allow me to make it faster with the same value? this seems rather impractical.
package unit5;
public class Primefinder { public static void main(String[] args)
{
double primer = 600851475143d;
double largestprime = 0;
Boolean ifprime = false;
for(double x = 2d; x < primer; x++)
{
for(double z = 2d; z<x; z++)
{
if( (x%z == 0) && (z != x) )
{
ifprime = false;
break;
}
else {
ifprime = true;
}
}
if((ifprime != false) && (x > largestprime))
{
largestprime = x;
}
ifprime = false;
}
System.out.print(largestprime);
}
}
for other questions you might ask everywhere, please tell us that what is the purpose of your code. this way it is easier to get the fault.
the code you have written above runs completely but the numbers you have used are too big so you need to wait a lot, so that compiler be able to reach to this line:
System.out.print(largestprime);
use lower numbers (at least for test) or wait properly.
Your 'primer' Value is very big.
So, loop is taking very much time to reach at '600851475143' value.
Wait Sometime and it with show largest prime number
I'm trying to learn Java, I studied Pascal in high school and it has the repeat until..; instruction.
I want to solve an exercise where I'm supposed to keep entering numbers until the penultimate + antepenultimate numbers equal the last number I entered.(a[i-2]+a[i-1] = a[i]); I'm doing it without arrays but that doesn't really matter.
In Pascal it would be easy because repeat until is more easier to use
For ex it would be
repeat
...
until ((a[i-2]+a[i-1] = a[i]) and (n=3));
n is the number of values I entered
I can't figure out how to introduce it in Java, so far I did this but it doesn't work if I enter 2 2 4. It should stop but it keeps asking for numbers
int pen = 0, ant = 0, s = 0, n = 1;
int ult = input.nextInt();
s = s + ult;
do {
do {
ant = pen;
pen = ult;
ult = input.nextInt();
n++;
s = s + ult;
} while (ant + pen != ult);
System.out.println(n);
} while ((n == 3) || (n < 4));
ult is the last number I enter, s is the sum of the numbers entered.
Could anyone tell me how to set the conditions so it will stop if I enter the values 2 2 4?
A Do-While loop runs the code in the loop first. It evaluates the logic last, and then if it's true it repeats the code inside the loop, and so on until the logic is false.
The way to solve tricky problems like this is to get out a sheet of paper and record what each variable does. Step through each line like a debugger and record what's being stored in each variable as the program progresses.
It's the best way to do it. You'll find that you'll gain a deeper understanding of how your programs are working.
Java isn't any more magic than Pascal, the issue might be you've had a long break from programming :). Anyway, its been a while since I wrote anything in Java, but the issue I could spot in your code is just that n equals three after you've entered three ints, and so the outer loop continues.
int pen = 0, ant = 0, ult = 0, n = 0;
do {
ant = pen;
pen = ult;
ult = input.nextInt();
} while (++n < 3 || ant + pen != ult );
assert n >= 3;
assert ant + pen == ult;
Note that ever since Pascal everything has been zero indexed instead of one indexed.
Pascal uses the form:
repeat
doStuff();
until (boleanValue);
Java is basically the same, except for one important point:
do
doStuff();
while (~boleanValue);
The important difference is that "~" before booleanValue. The Pascal repeat ... until keeps running until the boolean evaluates to true. In Java the do ... while keeps running until the boolean evaluates to false. When converting from Pascal to Java you need to switch the boolean to work the other way.
The primary difference between while loop and a do-while loop is that while loop does eager condition check where as do-while loop does lazy condition check
while: Expression is evaluated at the top of the loop
syntax:
while (expression) {
statement(s)
}
(taken from http://www.w3resource.com/c-programming/c-while-loop.php)
Example:
public class WhileDemo{
public static void main(String args[]) {
boolean isSunday = false;
while(isSunday) {
System.out.println("Yayy.. Its Sunday!!");
}
}
}
Output: (nothing is printed on console)
Reason: Since isSunday is false, the body of loop is not executed
do-while: Expression is evaluated at the bottom of the loop. Therefore, the statements within the do block are always executed at least once.
syntax:
do {
statement(s)
} while (expression);
(taken from http://www.w3resource.com/c-programming/c-do-while-loop.php)
Example:
public class DoWhileDemo{
public static void main(String args[]) {
boolean isSunday = false;
do {
System.out.println("Yayy.. Its Sunday!!");
} while(isSunday);
}
}
Output: Yayy.. Its Sunday!!
Reason: The body of do is executed first, there by printing Yayy.. Its Sunday!! and then the condition while(isSunday); evaluates to false since isSunday is false and the loop terminates
You're only missing one thing from your problem. Your explanation of the Pascal code is almost correct, but wouldn't work without some modification.
In Java, use short-circuit logical operators to do the check.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
Not tested:
int n = 0;
int a[] = new a[3];
do {
n++;
a[0] = a[1];
a[1] = a[2];
a[2] = input.nextInt();
} while ((n < 3) || (a[0]+a[1] != a[2]));
System.out.println(a[2]);
I was trying to implement the coin change problem using recursion. I have written the following code and am facing a problem with the static class variable. 'answer' is a class variable and i am trying to add the return value to it in the loop. This works fine within the while loop but after the while loop ends the answer is reset to 0;
while (i * currentCoin <= sum) {
System.out.println("inside while; answer is " + answer);
answer = answer
+ findCombinations(
sum - i * currentCoin,
new ArrayList<Integer>(denominations.subList(1,
denominations.size())));
i++;
}
Below is all the code that I have written. You can copy and run it to check.
import java.util.ArrayList;
import java.util.Collections;
public class CoinChangeHashMap {
static int answer = 0;
public static void main(String[] args) {
int[] array = new int[] { 7, 3, 2 };
ArrayList<Integer> input = new ArrayList<Integer>();
getList(array, input);
findCombinations(12, input);
System.out.println(answer);
}
private static void getList(int[] array, ArrayList<Integer> input) {
for (int i : array) {
input.add(i);
}
}
public static int findCombinations(int sum, ArrayList<Integer> denominations) {
if (denominations.size() == 1) {
if (sum % denominations.get(0) == 0) {
return 1;
}
return 0;
}
int i = 0;
int currentCoin = denominations.get(0);
while (i * currentCoin <= sum) {
System.out.println("inside while; answer is " + answer);
answer = answer
+ findCombinations(
sum - i * currentCoin,
new ArrayList<Integer>(denominations.subList(1,
denominations.size())));
i++;
}
return 0;
}}
**The output that I get is 0. but the expected output is 4. While debugging the output that I got is **
inside while; answer is 0
inside while; answer is 0
inside while; answer is 1
inside while; answer is 1
inside while; answer is 2
inside while; answer is 2
inside while; answer is 0
inside while; answer is 0
inside while; answer is 0
0
Any Help is appreciated.
The problem is related to your odd code structure, in which you convey the outcome of your recursive call sometimes by modifying static variable answer, and sometimes via the method's return value.
If you analyzed the problem more closely, you would discover that it is not upon exit from the loop that the partial results are lost, but rather some time after return from the method. Therefore, consider carefully the way you update the answer:
answer = answer + findCombinations( /* ... */ );
At the top-most level of your recursion, answer is initially 0. When Java evaluates the above expression, it evaluates first the left operand and then the right operand, then it adds them. That is, it evaluates answer, getting the result 0, before it performs the recursive call. The value of answer may be updated in the course of the recursive call, but those changes come too late. Only the bottom-most level of the recursion ever returns a value different from zero, so if the recursive call itself recurses at least one level deeper then it will return zero. In that case, the sum is computed as 0 + 0, and assigned to answer, clobbering any update the method performed.
You could resolve the problem by swapping the order of the operands in your sum, but it would be better, and not much harder, to get rid of the static variable altogether. Use a local variable within the method to accumulate results, and in all cases convey the total back to the caller via the method's return value.