I need this for an array, but basically the idea is that a for loop will run, and whatever number you tell it to skip, it won't do. So for(int x=0; x<50; x++) if I want 1-50 except 22, how would I write that?
This would give me the ability to skip a certain number in my array.
Sorry if this is an extremely simple question, I am not too familiar with Java.
Make use of continue, something like this:
for(int x=0; x<50; x++) {
if(x == 22)
continue;
// do work
}
Suggested reading: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
public static final void doSkippedIteration(final int[] pArray, final int pSkipIndex) {
for(int i = 0; i < pSkipindex; i++) {
// Do something.
}
for(int i = pSkipIndex + 1; i < pArray.length; i++) {
// Do something.
}
}
You would have to do some basic check to see whether pIndex lies within the confines of the array. This saves you from having to perform a check for every single iteration, but does require you to duplicate your code in this specific example. You could of course avoid this by wrapping the code in a wider control block which handles the two iterations in a cleaner manner.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
LeetCode 485
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
---------Solution:-------
public int findMaxConsecutiveOnes(int[] nums) {
int maxConsSize = Integer.MIN_VALUE;
int i = -1, j=-1, k=0;
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
return maxConsSize;
}
Warning: This is not direct answer (for this "do my homework" question)
You should use (or learn to use) debugger in your IDE (trust me, IDE, e.g. Eclipse will help you a lot in your beginnings).
The easiest (I'm not saying smartest) way, how to know what the program is doing (when you need to know, like in this case) is to add some print statements, e.g. add System.out.println("k=" + k) into your program (in a while loop).
You might want to watch this youtube video.
You have an infinity loop. Try run this:
public class Test {
public static void main(String[] args) {
int maxConsSize = Integer.MIN_VALUE;
int[] nums = {1,1,0,1,1,1};
int i = -1, j=-1, k=0;
System.out.println(nums.length);
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
System.out.println("k = " + k);
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
System.out.println(maxConsSize);
}
}
Output:
6
k = 1
k = 2
After reading the first 0 you are in infinite loop. You have made this task very complicated :)
It's probably not the best solution, but it should be faster
public int findMaxConsecutiveOnes(int[] nums) {
int maxCons = 0;
int currentCons = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
if (currentCons > maxCons) {
maxCons = currentCons;
}
currentCons = 0;
} else {
currentCons++;
}
}
if (currentCons > maxCons) {
maxCons = currentCons;
}
return maxCons;
}
}
There are two basic forms of loops:
for-each, for-i or sometimes called ranged for
Use that for a countable number of iterations.
For example having an array or collection to loop through.
while and do-while (like until-loops in other programming languages)
Use that for something that has a dynamic exit-condition. Bears the risk for infinite-loops!
Your issue: infinite loop
You used the second form of a while for a typical use-case of the first. When iterating over an array, you would be better to use any kind of for loop.
The second bears always the risk of infinite-loops, without having a proper exit-condition, or when the exit-condition is not fulfilled (logical bug). The first is risk-free in that regard.
Recommendation to solve
Would recommend to start with a for-i here:
// called for-i because the first iterator-variable is usually i
for(int i=0; i < nums.length, i++) {
// do something with num[i]
System.out.println(num[i]):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no counting, etc. inside the loop-body
Even simpler and idiomatic pattern is actually to use a for each:
for(int n : nums) {
// do something with n
System.out.println(n):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no index required, suitable for arrays or lists
no counting at all
See also:
Java For Loop, For-Each Loop, While, Do-While Loop (ULTIMATE GUIDE), an in-depth tutorial covering all about loops in Java, including concepts, terminology, examples, risks
What I am trying to do is create an array that pulls even numbers from another array. I'm not sure if I have gone about it the right way. I've look for ways of returning from statements like you would functions/methods and I can't find anything, not even sure if it is possible.
Anyway, the issue I am having here is the 'return evenArray' below 'cannot find symbol.' I am not sure what this means?
public static int[] getEvenArray(int[] array)
{
int dividedBy = 2;
int evenElement;
int evenCount = 0;
for(int i = 0; i < array.length; i++)
{
int[] evenArray;
evenElement = array[i] % dividedBy;
if(evenElement == 0)
{
evenCount++;
}
else
{
array[i] = 0;
}
evenArray = new int[evenCount];
for(int x = 0; x < evenArray.length; x++)
{
if(array[i] != 0)
{
evenArray[x] = array[i];
}
}
}
return evenArray;
}
This is for a tutorial from one of my lectures, it's a little bit challenging to say the least :-)0
evenArray is defined within the scope of the for loop. (Actually a little worse than that; you're redeclaring it on each iteration so discarding the previous contents).
So once you're outside the for loop you can't refer to it.
Quickest fix is to use a std::vector<int> for this type, and declare it at the start of the function. Also change the return type of the function to the same. Don't forget to size the vector appropriately.
(Moving on, a smart lecturer will ask you about returning a std::vector which could potentially take a deep copy of that vector. Pre C++11 you'd mention return value optimisation, now you can talk about r-value references. No deep copy will be taken since the move constructor will be used).
Variable declared inside a block is not visible outside of it; move this int[] evenArray; to very start of function.
I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print.
Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel
Your for loop condition is wrong. You want the condition to be true to continue looping, and false to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for loops.
#rgettman gave the reason your code didn't work above.
The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.
rgettman is completely correct. A for loop should be used as so:
for is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable such as int i = 0; to create a simple integer at 0.
The second parameter will take a condition such as i < 10, to say while the i integer is less than
The third and final parameter will take an incrementing value like, i++, i--, i +=5, or something to that effect.
This part should like like for(int i = 0; i < 10; i++) so far.
Now you need the brackets { and }. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!
Is this going to cause unpredictable behavior?
ArrayList<X> x = new ArrayList<>();
//x.add(new X())...
f:
for(int i = 0; i < x.size() -1;)
{
X y = x.get(i);
for(int j = i + 1; j < x.size();)
{
if(a) {
x.remove(j);
continue;
}
if(b) {
x.remove(i);
continue f;
}
j++;
}
i++;
}
I don't think it will be unpredictable, but your style seems wrong to me, so your approach is suspect.
Using a label is a bad idea, and deciding to use it shows that your approach is flawed.
You may want to look at this discussion about deleting on ArrayList, but basically, LinkedList would be fsster:
http://www.velocityreviews.com/forums/t587893-best-way-to-loop-through-arraylist-and-remove-elements-on-the-way.html
But, removing this way will work.
UPDATE:
Oops, just saw a couple of bugs:
if(a) {
x.remove(j);
continue;
}
OK, in this one, you will go back through the loop for j, but you didn't increment j.
if(b) {
x.remove(i);
continue f;
}
This is the same for i.
So, you need a similar change to fix it:
for(int i = 0; i < x.size() -1; i++)
This way, when you hit continue then it will still go to the next element.
It would be better to create an array which contains indexes to remove.
And fill it with indexes in the main for cycle. Than you can do something like this:
Collections.sort(indexesToRemoveArr);
Collections.reverse(indexesToRemoveArr);
for (int indexToRemove : indexesToRemoveArr) {
arr.remove((int) indexToRemove );
}
In that code I remove indexes from end to start. That's why it won't do any problems.
Yes. Compiler will optimize and call x.size() only once. So your terminatin condition becomes incorrect as soon as you remove element.
Hi I have been given a task for my course and it is to create an algorithm to make a 5 by 5 square like below:
*****
*****
*****
*****
*****
I've spent hours attempting to do it and read tutorials and books. It's so frustrating as I know it must be so easy if you know what you are doing. Can anyone give me any guidance as to where to start?
You probably know and understand how to create a "Hello World" style program in Java.
Now think - how would you go about having that same program print 5 times "Hello World"?
After that, think about how you would make it write N times "Hello World".
After that, think about how you would output a series of N stars.
Good luck!
Seems like you should have a variable x equal to the dimension (5). A for loop i that loops from 1-x. In it a for loop j that loops from 1-x. The j loops outputs *, or appends * to a string. After the j loop, the i loop does a new line.
This solution will allow for a square grid of any size.
int size = input;
for (i=0; i<size; i++){
for (j=0; j<size; j++){
// output a single "*" here
}
// output a new line here
}
If I got you right, then it's about a NxN square with a given N. Your question is just about N := 5, but your comments let me assume that you've to program a more general solution.
Split the work that have to be done into more basic and smaller problems:
create a String that contains * N times.
call System.out.println() with the generated String N times
This will work for you as well, but the professor will frown that you found the answer online and did not think of it yourself.
System.out.println("*****\n*****\n*****\n*****\n*****");
Here's how I did it:
class Main {
public static void main(String[] args) {
int size = 25;
int pos = 0;
for(int i = 0; i<size; i++){
if(pos % 5 == 0){
System.out.println();
}
System.out.print("*");
pos++;
}
}
}
If I understood correctly, what you need is a console output with 5 lines of stars.
You can outpt text to console with System.out.print() or System.out.println() with the second option making a line break.
As you have to repeat the output, it is advisable to do enclose the output statement in a loop. Better in a nested loop to separate the x and the y axis.
In order to make the output modifiable - for the case you will need to output a 6x6 or 12x15 square tomorrow without any code modification, I would make the limits of the loop parametrized.
All in all, something like this :
public void printStartSquare(int width, int height){
for(int i = 0; i < height;i++){
for(int j = 0; j < width;j++){
System.out.print("*");
}
System.out.println("");
}
}