confusion with For Loop Java - java

Sorry i'm new to java, just need help with my school project.
I'm trying to implement a For loop for a deck of cards. I want my loop to keep adding cards till it has reached 5.
The count increases using the following URL: https://deckofcardsapi.com/api/deck/new/draw/?count=1
count=1 needs to keep going up from 1 to 5. I think what i have below is correct but is this the right way to do it? and can i enhance it so there is an output at the end of it?
int counter = 5;
for(int i = 1; i <= counter; i++) {
String uriString = "https://deckofcardsapi.com/api/deck/new/draw/?count="+i;

If you want to deal cards from 1 to 5, then yes it works correctly.
"can i enhance it so there is an output at the end of it?"
It depends on what do exactly you want. If you want to parse the result, then check this out: http://unirest.io/java.html

Related

Java: Recursive sudoku solutions counting algorithm

I made Sudoku checker/solver with ease, but I need one that can tell wheter there is more than one solution, and couldn't wrap my head around it. I found a working algorithm, but I'm trying to understand why it's working. It's the answer from this question, provided by #fabian
Copied below:
// returns 0, 1 or more than 1 depending on whether 0, 1 or more than 1 solutions are found
static byte solve(int i, int j, int[][] cells, byte count /*initailly called with 0*/) {
if (i == 9) {
i = 0;
if (++j == 9)
return 1+count;
}
if (cells[i][j] != 0) // skip filled cells
return solve(i+1,j,cells, count);
// search for 2 solutions instead of 1
// break, if 2 solutions are found
for (int val = 1; val <= 9 && count < 2; ++val) {
if (legal(i,j,val,cells)) {
cells[i][j] = val;
// add additional solutions
count = solve(i+1,j,cells, count));
}
}
cells[i][j] = 0; // reset on backtrack
return count;
}
I tried implementing it, and as it should, it works. However though I think I understand what each part of the code does, I cannot get why it works.
First: The first if statement stops the method once the final number in the 2d array is reached. I get this in finding a single solution, but why does it work in finding more than one solution? Shouldn't the method just return 0+1=1 after solution is found?
Second: after if (cells[i][j] != 0) why does the recursive solve(...) call need return statement in front of it? I have made several recursive algorithms, but always by just calling the method again.
Third: If none suitable numbers are found the for loop stops and 0 is inputted to the cell place. Since it should already have 0, shouldn't the backtracking put 0 to the last place instead of current? At least that is how I made the solver that I made myself.
Fourth: After the backtrack set, there is just return count. Why is the program still working? Shouldn't it just return count = 0 and stop after facing first place that doesn't allow any numbers? Howcome there isn't a recursive call at the end?
If you made it this far on this rampling question, it is clear that I'm understanding some things completely wrong. I'd highly appreciate assistance/explanation, since using code one doesn't understand is a complete failure as far as learning to code goes.
Ok, so Google gracefully provided an Powerpoint lecture from Harvard:
http://www.fas.harvard.edu/~cscie119/lectures/recursion.pdf
If someone else is having problems getting recursive backtracking, I recommend checking it out. Very short but informative.
My problem seemed to be only that I stupidly (at least on hindsight) assumed for the method to stop after it calls itself recursively. I forgot that after it gets results from the recursive call it makes, it executes itself to the end. Funny how you can use umphteen hours solving something just because your initial thought process was flawed. Well, live and learn I guess.

Using a WHILE statement to check against duplicates in Java

I am trying to write a program containing 3 String ArrayLists, where 1 item may be included in all 3 ArrayLists. However, the output must insure that the randomly selected items are all different. As I work through this issue, I am just using numbers so it will be easier to catch. I have been trying to solve this problem for a few days now, and figure there must be something I am overlooking. Here is the code for the method that must have the fault:
private void generateThree() {
// Find the maximum number the random can be.
index = thirdNumberArray.size();
// Initiate the random function.
Random rand = new Random();
// Generate a random number from 1 to the maximum.
randomInt = rand.nextInt(index);
// Access the item in the ArrayList using the random number as the index.
thirdDrawn = thirdNumberArray.get(randomInt);
// Check that the number is different than any previously set numbers.
while ((thirdDrawn.equals(secondDrawn)) || (thirdDrawn.equals(firstDrawn))) {
randomInt = rand.nextInt(index);
thirdDrawn = thirdNumberArray.get(randomInt);
}
// Set the output.
thirdNumberLabel.setText((thirdDrawn));
// Reset the index.
index = 0;
}
So far, the IF statement I use to check the secondDrawn against the firstDrawn has worked perfectly. But the above code still allows the thirdDrawn to display a duplicate of both the firstDrawn and secondDrawn. I know this problem has to be in my loop logic, but I just can't grasp what it is. I have tried multiple different IF statements, but they didn't solve the whole problem. Can anyone give me some feedback or corrections? Thanks in advance.
Any time you generate a number you want to draw, add it to a HashSet<String>. Then, have your if statement conditional check !myHashset.contains(thirdDrawn).

Java bar chart method

I need to print out a bar chart, via a call from a method barChartPrinter. I.e. barChartPrinter(5, 6, 2); would print: a vertical column of 5 XX's followed by
a space then a vertical column of 6 XX's and a vertical column of 2 XX's.
The numbers are based on user input, so I'm thinking I need to gather the numbers and store those in an array. And I'm thinking a for loop will be involved,
but I'm not sure how I'd do it.
public class BarChart {
public static void main(String args[]) {
int[] list = new int[4];
Scanner input = new Scanner(System.in);
System.out.println("Enter four integers: ");
for(int i = 0; i < list.length; i++)
list[i] = input.nextInt();
System.out.println();
barChartPrinter(list);
}
public static void barChartPrinter(int[] numbers) {
int max = numbers[0];
for (int i = 0; i < numbers.length; i++)
if(numbers[i] > max)
max = numbers[i];
}
}
This is where I get stuck: defining the method that will print out the bar chart; given the user input values. The method needs to print out in this format, i.e.
barChartPrinter(1, 2, 3, 4) =
For some reason, it won't display how the bar chart should be constructed on here so I'll just describe it:
There would first be a column of XX, then a column of XX (two of these vertically to represent 2), then another column of XX (but this time three of these on top of each other, to represent the number 3) and finally another column of XX * 4 vertically.
Any pointers?
OK, by now I'm sure that you know that it would be trivially easy to create horizontal bar graphs:
2 6 4
**
******
****
Since the print and println methods of the console's PrintStream (the out of System.out) prints things horizontally. The trick for your assignment is how to print this graph vertically. And for that you're going to have to use a little logic. Since this is obviously homework, I'm not going to give you a solution but rather will suggest options.
You know that you'll need to use a loop of some sort to print lines in a row.
One possible solution has you figuring out how many times to loop in advance of the loop by first finding the maximal value held by the array. If you do this, then use a for loop.
Another possible solution you don't find max, but rather just loop til done. Here use a while loop. This would be the option I'd use, and I'd use a boolean variable, say named keepGoing to help tell the while loop when to keep looping and when to stop.
If you go with this latter option, you'll use an int counter in the loop to check what row you're on, and you'll advance this counter inside of the loop.
You will need to nest a for loop inside of your while loop to go through each array item.
You'd use this counter and the array items (in the for loop within the while loop) to see if the String that you will eventually print should have an "* " added to it.
After the inner for loop, you'll print the String you've created.
If no "* " are present (you could call myString.trim().isEmpty()), then keepGoing = false; and the while loop should stop.
Edit: your posted code is a bit off in that it tells the user to enter four numbers but only accepts three. You'll want to fix this.
Edit 2 You state:
Hey, sorry yeah I've sorted the code out. I've coded the way to find the max value within the method. I'm stuck on the step of actually producing the chart now. I know that it will print the XX's each row horizontally, but I'm still stumped as to how I can achieve this- I know it will involve a for loop, but I can't see how I can print the XX's for each column; apologies if I'm missing something obvious
Again, break up your problem by splitting up the big problem into little steps, the smallest you can think of, and then solve each small step. You know that you're going to have to construct a String to be printed, and so you should focus on that, on how to construct this String so that an asterisk is present where need be, and a space is present when the column should show no asterisk. Try to come up with a solution, even a partial solution and post it as an edit to your question, much like how I'm posting this edit to my answer.

In a Logic When to use For loop and When to use while loop [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am beginner for the programming language , I am bit confused in the basic of looping concept can any one please tell me clearly when to use the concept of For loop and when to use the while loop so that it would be very grace full for me to my future programming,
Thanks in advance
Generally, you use a for loop if you know (Or the program can know at the time of the loop) how many times you want to run a piece of code, and while loops if you do not.
However, it is possible to use them interchangably, so while it may be a bit less elegant to use one than the other, it doesn't matter too much.
Ex:
for(int i = 0; i < 100; i++){
do stuff
}
is the same as
int i = 0;
while(i < 100){
do stuff
i++;
}
, but the former looks more elegant.
Similarly,
bool condition = false;
while(condition){
do stuff
}
and
for(bool condition = false; condition;){
do stuff
}
are the same, but generally, the while loop is considered more elegant here.
In almost all cases you could use either for or while loops. You are provided with two ways of looping to help reduce the complexity of your code across different use cases.
When to use for loops
For loops are best when you know how many iterations you want to loop before you begin. For example, if you knew you wanted to print the numbers 1 through 10 in order you know you want to loop 10 times.
for(int i = 1; i <= 10; i++)
{
System.out.println(i);
}
When to use while loops
While loops are best when you want to continue looping until a specific event occurs or a condition is met. For example, let's say you wanted to print random numbers between 1 and 10 until you came across the number 5. This may take one iteration or hundreds depending on your luck.
Random rand = new Random();
int value = 0;
while(value != 5)
{
value = rand.nextInt(10);
System.out.println(value);
}
Basically you should use a for loop if you know the number of iterations this loop has to do. Even if that number is a variable (like the length of a list) it is know at runtime.
A while loop is used when you don't know the number of iteration. You mostly check a condition that can evaluate to false after any number.
You also have the do-while and the for-each loops at your disposal. The do-while is used when you know that you have at least one iteration but the number is otherwise unkown. The for-each is used to iterate over arrays and collections. It can do something for each element contained.
A for loop will give you the option to perform any or all of these three things:
Instantiate a starting iteration value (int i = 0)
Define a boolean condition on which iteration may continue (i < 10)
Provide an incrementation step (i += 2)
A valid for loop can look like this:
for(; ;) {
System.out.println("This will run forever!!!");
}
A while loop only gives you the boolean condition, which is mandatory.
You typically use the for loop when:
You know the size of the elements you must iterate over
You typically use the while loop when:
You don't know the size of the elements you must iterate over
You want to busy-wait on some value or variable
For loops are used when you know how many times you need to loop. While loops are used to loop until an event occurs.
Also, note that whatever you can do with a for loop, you can do it with a while loop (just add a variable that increments in the while loop and uses it to break out of the loop when the variable reaches a certain value).
This is one of those things that folks typically pick up by experience. First thing to realise is that any for loop can be decomposed into a while loop
for ( initialise; test ; go on to next )
can be expressed as
initialise;
while(test) {
go on to next
}
I'd suggest trying for a little while to use only while loops. What you will then find is that some of your while loops start to feel a little clumsy.
initialise;
while(test) {
my really interesting code here
go on to next
}
and you find that
for ( initialise ; test; go on to next ) {
my really interesting code here
}
reads more clearly. One common example being working your way through an array.
for ( int i; i < array.length; i++ ){
something with array[i];
}

Value (not index) greater than 3 in array causes java.lang.ArrayIndexOutOfBoundsException

I'm a novice programmer. This may be a simple problem but I've never seen this before. First of all, let me clarify that I'm not even trying to manipulate the index. Here's the part of the code that is causing the exception:
int[] bumpercatcher = new int[4];
//time variable that helps control events
int time = 0;
public void setup()
{
bumpercatcher[0]=4;
bumpercatcher[1]=4;
bumpercatcher[2]=4;
bumpercatcher[3]=4;
As you can see I'm trying to set them all equal to 4 at the start of the program. This causes the arrayindexoutofbounds exception. If I set them all equal to 0~3 then there is no problem (until I set them to a value greater than 3 later in the program). I don't understand it.
-it doesn't matter if I set the array size to 10, I still get the same exception
-it doesn't matter if I set only one of the values (i.e. at index 1, which is definitely within bounds of the array). same exception
Is there something I'm doing wrong? Thanks.
well, here' the entire code if you want to take a look(not too long, 1 class, bad programming practies): http://dl.dropbox.com/u/33501308/Pong.java
Here's the html from which you can see the program from (not much to see. it just freezes instantly.): http://dl.dropbox.com/u/33501308/bin.zip
by the way I'm using eclipse.
I don't really know what SSCEE is. sorry
Your posted code file includes loops along the lines of
for(int j: bumpercatcher) {
if(bumpercatcher[j]>5)
...
}
This is an issue. This is a different kind of loop than a traditional for loop. It is an extended or enhanced for, also called a foreach. It reads "for each integer j in array bumpercatcher do x." You are taking your element j (a value) and using it as an index to the array. When your value exceeds the maximum index, you will get an exception.
Write your code with a proper for loop if you want to access by index, or try simply restructuring your logic like
for (int j : bumpercatcher) {
if (j > 5) // j is the value!
...
}
I'm not sure what the problem is, but a far more readable way of doing this would be with a for loop:
for(int i = 0; i < bumpercatcher.length; i++) {
bumpercatcher[i] = 4;
}

Categories