For loop doesn't get finished - java

int length = Math.max(userOne.userName.length(), userTwo.userName.length());
length = Math.max(length, 5);
System.out.println("\nCurrent board:");
for (int i=0; i<3; i++) {
for (int s=0; s<3; s++) {
String box = "empty";
if (boxes[i][s] == 1)
box = userOne.userName;
else if (boxes[i][s] == 10)
box = userTwo.userName;
if (box.length() < length) {
for (int j=0; j<(length-box.length()); j++) {
box += " ";
}
}
System.out.printf("[%s]",box);
}
System.out.print("\n");
}
The third loop for (int j=0; j<(length-box.length()); j++) loops incorrect number of time!!
For example, when it's supposed to loop 3 times, it only loops 2 times; and when it's supposed to loop 8 times, it only loops 4 times. I tried to print j and it seems that the loop never gets finished.
I assume this has something to do with Java's synchronization, but I have no idea how to solve it!

With each iteration, you are both incrementing j and decreasing length-box.length() since you are adding to box, so the loop will only run half as many times as you want it to (rounded up).
A while loop makes more sense here:
while (box.length() < length) {
box += " ";
}

You increase the length of box inside your code - making your loop condition dynamic:
for (int j=0; j<(length-box.length()); j++) {
box += " "; //makes box.length() increase!
}
If you wanted to target the box length as it was before the loop, calculate it before the loop:
int targetLength = length - box.length();
for (int j=0; j< targetLength; j++) {
box += " ";
}

The box length changes during the loop and so your test changes.
Probably you need to save the initial box length in a variable and loop using that variable
int innerLength = length - box.length();
for (int j=0; j < innerLength; j++) {
box += " ";
}

Related

How can I print a certain string i times in a for loop?

i'm trying to print out a shape that looks something like this:
*
**
***
****
*****
To do that i'm using a for loop:
for (int i = 1; i <= 5; i++) {
System.out.print("*");
System.out.println;
}
but how do I get the line 2 to print i asterisks, instead of just the one asterisk as i have so far?
The logic you want to articulate here is that, for each row, print as many asterisks as the current row number. Nested loops can be used here:
for (int i=0; i < 5; i++) { // the row
for (int j=0; j <= i; ++j) { // the column
System.out.print("*");
}
System.out.println();
}
If you are using java 11 or greater you can use public String repeat​(int count).
for (int i = 1; i <= 5; i++) {
System.out.println("*".repeat(i));
}
You can use
for (int i = 1; i <= 5; i++ ){
System.out.println(new String(new char[i]).replace('\0', '*'));
}
to print * according to the value i contains each time it loops
It basically creates a new char array of size i and replaces all the nulls , i.e.('\0'), with * of that char array, and then it converts the char array into one single string and prints it.

Coding this pyramid pattern with user input and spaces in Java?

I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this!
I've made lots of pyramid patterns before, but this is one I can't figure out.
I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.
I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:
*
**
***
****
*****
So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.
This is the code (which gives a completely inaccurate output):
System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20.");
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
for (int j = 1; j == (num -= counter); j++)
{
System.out.print(" ");
}
for (int k = 1; k == counter; k++)
{
System.out.print("*");
}
System.out.println("");
counter++;
}
Please help! I feel so stupid.
I doubt your teacher will accept this. But it is just a one liner for fun
int num = 20;
IntStream.range(0, num).forEach(i -> System.out.println(String.format("%" + num + "s", new String(new char[i+1]).replace("\0", "x"))));
It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.
for (int i = 0; i < num; i++) {
for (int j = 0; j <= (num - counter); j++) {
System.out.print(" ");
}
for (int k = 0; k < counter; k++) {
System.out.print("*");
}
System.out.println("");
counter++;
}
it's pretty close mostly the for loop is wrong.
for(initialization;condition;increment)
the for loop only executes when the condition is true. In your case the conditions don't really make sense. Try changing it. also your counter and i are the same thing :)
Interesting coding exercise. You got it almost right anyway as others pointed out.
There are hundred ways to solve the problem.
Here is just a variation that saves a loop...
int lines=5;
for (int i=0; i<lines; i++) {
for (int k=0; k<lines; k++) {
System.out.print( (k < lines - i - 1) ? " " : "*");
}
System.out.println();
}
Another solution using a single (explicit) loop:
for (int i = 1; i <= num; i++) {
int expectedSpaces = num - i;
String spaces = repeat(" ", expectedSpaces);
String asterisks = repeat("*", i);
System.out.println(spaces + asterisks);
}
}
private static final String repeat(String toBeRepeated, int length) {
return new String(new char[length]).replace("\0", toBeRepeated);
}
As mentioned elsewhere, loop variables such as i usually start at 0 since such variables can be used as an array/List index. However, in this case there is no related array or List so sarting at 1 simplifies the logic.
I worked on something similar, this is what I did, you could give it a try. It takes a user input and displays spaces and "#"...
int size = n;
for (int i = 0; i <= size-1; i++){
for(int j = size -1; j > i; j-){
System.out.print(" ");
}
for(int j = 0; j <= i; j++){
System.out.print("#");
}
System.out.println();
}
The output would be:
#
##
###
####
#####
######

How to loop this statement with 3 changing values to setText for 40 textfields?

Here is the code when I haven't stored in a list. This gets what I want to display in different textfields but I want it to be shorter so I want to loop it.
//"answerStoration.retrieveDataChoices(i,TB)" is a function from other class that returns an arraylist;
quizAnswer1store.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswer2store.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswer3store.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswer4store.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswer1store2.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswer2store2.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswer3store2.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswer4store2.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswer1store3.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswer2store3.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswer3store3.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswer4store3.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
I stored it in a List "quizAnswerSTORE" and I tried to loop but doesnt work.
int k = 0;
for(int i = 0; i<quizAnswerSTORE.size(); i++){
for(int j = 1; j < 11; j++){
while(k<4){
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
The expected result is to diplay different values from a database in different 40 txtfields. Because each time the loop values increments, it rolls through my database with different values. J variable represents the id in my database. And the K is an index in the values taken in the arrayList returned by retrieveDataAnswers function from a four columned database.
There you go. I hope you can solve this.
You can use mod to control maximun int values, for example i % 10 can't take values more than 10.
Example:
public class Main {
public static void main(String[] args) {
int j = 1;
int k = 0;
for(int i = 0; i < 40; i++) {
System.out.println("quizAnswerSTORE"+i+".setText(answerStoration.retrieveDataChoices("+j+",TB).get("+k+"));");
k = (k + 1)%4;
if( k == 0) {
j = (j+1) % 11;
}
}
}
}
output:
quizAnswerSTORE0.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswerSTORE1.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswerSTORE2.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswerSTORE3.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswerSTORE4.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswerSTORE5.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswerSTORE6.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswerSTORE7.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswerSTORE8.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswerSTORE9.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswerSTORE10.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswerSTORE11.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
...
quizAnswerSTORE38.setText(answerStoration.retrieveDataChoices(10,TB).get(2));
quizAnswerSTORE39.setText(answerStoration.retrieveDataChoices(10,TB).get(3));
Try to be consistent with your indentation and line up closing brackets '}' with their corresponding statement.
The first problem I see with this code is that k is never incremented inside the while loop so it will always have the same value and loop forever. The second problem I see is that k is not reset after the while loop so when it goes through the loop the first time (and is correctly incremented) it will stay at a value of 4 and the loop will be skipped every time after that.
I'm not sure what you're trying to achieve (I could use some more information or a sample output) but to begin with you can correct the loop error by changing the while loop to a for loop like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
for (int k = 0; k < 4; k++) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
Alternatively, if you wanted to keep the while loop, you could so it like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
int k = 0; // Set k inside the 2nd loop and it will reset to 0 after the while loop
while(k < 4) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
k++; // Shorthand for k += 1 which is shorthand for k = k + 1
}
}
}

Printing star and character triangle in java

Here is a screenshot of my Output and the desired output is located below as wellI have to create program that outputs a star and the letter o. I have gotten it working for the most part but the output is not 100% correct, minor things really. Here is my code so far:
for(int i = 1; i <=numRows; i++){
System.out.print("\n");
for(int j = 0; j<=numRows; j++){
if(i+j >= numRows){
System.out.print('*');
System.out.print("o");
}else {
System.out.print(" ");
}
}
System.out.println();
And here is a screenshot of what the output is supposed to look like
This is similar to what I had to do for class a long time ago. Here is the code:
for(int i = 0; i <= userInput/2; i++)
{
for(int j = 0; j < (userInput/2 - i); j++)
{
printDiamond = printDiamond + " ";
}
for(int k = 0; k <= (i*2); k++)
{
printDiamond = printDiamond + "*";
}
printDiamond = printDiamond + "\n";
}
**Reason it is userInput/2 is because the other half of the code prints the diamond in reverse, thus actually making a diamond and not a triangle. **
So what do we have: First inner loop is responsible for printing the white spaces that help give our diamond its shape. The next inner loop prints the top of the diamond; *2 because we want it to print the whole top of the diamond, and not just half of the diamond if we were to split it top to bottom.
I will leave the addition of the extra o's to you.

Displaying reverse numbers array

So I have to write a program that accepts 10 numbers (ints) from the keyboard. Each number is to be stored in a different element of an array.
Then my program must then display the contents of the array in reverse order.
int [] array = new int [10];
for(int i = array.length - 1;i >= 0; i--)
{
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
array[i] = number;
}
JOptionPane.showMessageDialog(null, array[i]);
}
I tried to put the JOPtionPane.showMessageDialog outside of the loop but then the program can't find the integer "i". I don't know what to do here :/ Please help :P
You need to enter your data first, then display it thereafter in the order you desire...
int [] array = new int[10];
for (int i = 0; i < array.length - 1; i++) {
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i + 1)));
array[i] = number;
}
for (int i = array.length - 1; i >= 0; i--) {
JOptionPane.showMessageDialog(null, array[i]);
}
I'd also be tempted to simply construct a StringBuilder for your final results and then just show the message dialog once only, rather than for every element of the array, but that's up to yourself :)
i belongs to the loop scope, that's why you can't use it outside of the loop.
To print the reversed array use another loop
// insert the data to the array
int [] array = new int [10];
for(int i = array.length - 1 ; i >= 0 ; i--) {
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
array[i] = number;
}
// print the array
for (int i = 0 ; i < array.length ; ++i) {
JOptionPane.showMessageDialog(null, array[i]);
}
That's because you've declared in in for loop, so it has loop scope. Declare it before loop to reuse it after loop finishes
int i;
for(i = array.length - 1;i >= 0; i--)
After that, you can make another loop:
for(i = 0; i < array.length; i++)
to print it in reverse order.
You need two for loops. The first iterates from 0 to 9 and asks for the number and puts it in the array. The second iterates from 9 to 0 and prints the numbers in the array

Categories

Resources