I have been struggling with the break clause aspect of an exercise in the Java Headfirst book( CH5: p121 for reference). I understand how the below code works when the break clause isn't initiated but when it is, I don't get the results I expected.
Can someone please walk me through this?
I understand that the break clause should be activated when the input value is either x = x + 0 or x = x + 6
Below is the exercise code
class MixFor5 {
public static void main (String [] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 0; //input value
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println((x + " " + y));
}
}
My understanding would be that the inner loop would break if x == 6 and thus everything within the inner loop will discontinue including the additional x = x + 3
For x = x + 0. My expected result was x = 6 | y = 18 (actual result x = 6 | y = 14)
For x = x + 6. My expected result was x = 6 | y = 22 (actual result x = 60 | y = 10)
Thanks
For x = x + 0
outer = 0;
inner = 4;
x=x+0, x!=6;
x=x+3=3;
y=30-2=28;
inner = 3;
x=3;
y=28-2=26;
3 != 6;
x=3+3;
inner = 2;
x==6;
y=24;
break;
y=22;
outer=1;
inner=4;
x==6;
y=20;
break;
y=18;
outer=2;
inner=4;
x==6;
y=16;
break;
y=14;
for x=x+6
outer=0;
inner=4;
x=6;
y=28;
break;
y=26;
outer=1;
inner=4;
x=6+6+3;
y=24;
inner=3;
x=15+6+3;
y=22;
inner=2;
x=33;
y=20;
y=18;
outer=2;
inner=4;
x=42;
y=16;
inner=3;
x=51;
y=14;
inner=2;
x=60;
y=12;
y=10;
hope this would help.
Related
I'm trying to make a multiplication table which is as big as the user specifies. The problem I'm having is with the format. The output right now prints all the numbers to one line, whereas I want it all on multiple lines on a nice neat table. With it formatted as it is, I can't tell where the \n would go to do so, or if there is another way.
here's my code:
import java.util.*;
public class question2 {
public static void main(String [] args) {
Scanner keyb = new Scanner(System.in);
int i = 0;
while (i<=0 || i>=11) {
System.out.print("please enter an integer between 1 and 10: ");
i = keyb.nextInt();
}
for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
}
}
}
EDIT:
The output for integer 5, prints like this:
1 1 2 3 4 5 2 2 4 6 8 10 3 3 6 9 12 15 4 4 8 12 16 20 5 5 10 15 20 25
After the second for loop, add a new line \n:
for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
System.out.println();
}
You should add a newline after the second for loop, and since you print x don't print x * 1. So,
for (int x = 1; x <= i; x++) {
System.out.printf("%4d", x);
for (int y = 2; y <= i; y++) {
System.out.printf("%4d", x * y);
}
System.out.println();
}
or you could eliminate the first print like,
for (int x = 1; x <= i; x++) {
for (int y = 1; y <= i; y++) {
System.out.printf("%-4d", x * y); // and simply for variety, left-aligned
}
System.out.println();
}
or if you are using Java 8+, you might use IntStream like
IntStream.rangeClosed(1, i).forEachOrdered(x -> {
IntStream.rangeClosed(1, i).forEachOrdered(y -> System.out.printf(
"%-4d", x * y));
System.out.println();
});
Try the following. My screen only fits 14 numbers neatly. I make a list (it can house empty space '') and then I start to display the list neatly using the end='\t' argument keyword to create tabs.
n = int(input('Enter a number(max 14): '))
# n = 12
list_x = list(range(1,n + 1))
list_y = list(range(1,n + 1))
list_z = ['',] + list_x
for y in list_y:
list_z.append(y)
for x in list_x:
x = x*y
list_z.append(x)
count = 0
for i in list_z:
print(i, end='\t')
count += 1
if count == (n + 1):
count = 0
print('', end='\n',)
My Code :
class MixFor5 {
public static void main (String [] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 3;
y = y - 2;
if (x == 6) {
break; // *Useless break;*
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y);
}
}
My output:
54 6
Can someone explain to me. Why when I remove break; my output data don't change at all.
You are never fulfilling the if(x==6)
lets take a look at the first loop:
int x = 0;
//....
x = x + 3; // x = 3;
if( x == 6 ) //false
break;
x = x + 3; // x = 6
now the second loop
x = x + 3 // x = 9
if( x == 6 ) //false x = 9
break;
x = x + 3; //x = 12
so you never are equal to 6 when comparing.
I don't understand why the output is 25, from my wrong understanding obviously, i thought it is 20, because: first loop will be: i = 2; x = 5 and there will be 4 more loops since i <= m , therefor 5 x 4 = 20. I know i'm wrong but can't figure out where.
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
while (i<= m){
x = x + m;
i = i + 1;
}
System.out.println(x);
}
}
Let's try a dry-run for this:
x=0;i=1;m=5
while (1<=5) ? yes, so x=0+5; i=2,
while (2<=5) ? yes, so x=5+5; i=3,
while (3<=5) ? yes, so x=10+5; i=4,
while (4<=5) ? yes, so x=15+5; i=5,
while (5<=5) ? yes, so x=20+5; i=6,
while (6<=5) ? no, so exit from loop
And therefore the result is: x=25
Whenver face this type situation, try debugging and printing. Most of the time you'll find your answqer:
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
System.out.println("Initial : x = " + x + " and i = " + i);
while (i <= m) {
x = x + m;
i = i + 1;
System.out.println("x = " + x + " and i = " + i);
}
System.out.println(x);
}
}
Output:
Initial : x = 0 and i = 1
x = 5 and i = 2
x = 10 and i = 3
x = 15 and i = 4
x = 20 and i = 5
x = 25 and i = 6
25
Here is the code:
public class Driver06
{
public static void main(String[] args)
{
(int) (NUMITEMS = Math.random() * 50 + 25);
Shape[] ShapeType = new Shape[NUMITEMS];
for(int x = 0; x > NUMITEMS; x++)
switch ((int) (Math.random() * 3 + 1)) //
{
case 0:
ShapeType[x] = new Circle(Math.random());
break;
case 1:
ShapeType[x] = new Rectangle(Math.random(), Math.random());
break;
case 2:
ShapeType[x] = new Triangle(Math.random());
break;
case 3:
ShapeType[x] = new Square(Math.random());
break;
}
for(int i = 0; i > ShapeType.length; i++)
{
System.out.println("" + ShapeType[x].findArea());
}
}
}
Error:
Driver06.java:10: not a statement (int) (NUMITEMS = Math.random() * 50 + 25);
(int) (NUMITEMS = Math.random() * 50 + 25);
Instead of the above (which is syntactically invalid), I believe you want:
int NUMITEMS = (int)(Math.random() * 50 + 25);
int NUMITEMS declares the variable NUMITEMS of type int
= (int)(Math.random() * 50 + 25) assigns it to the result of Math.random() * 50 + 25 cast as an integer (i.e. with its fractional part truncated).
Thanks to #pennstatephil for pointing out that your loop conditions are incorrect in the comments, they should be:
for (int x = 0; x < NUMITEMS; x++)
and
for(int i = 0; i < ShapeType.length; i++)
i.e. you want to loop as long as the loop control variable is less than the number of items / array length.
Oh, and in your second loop you probably want to refer to ShapeType[i] instead of ShapeType[x].
When you type:
for(int x = 0; x > NUMITEMS; x++){
}
This for loop starts with x = 0, each time adds +1 at x value, and this loop works while x > NUMITEMS. The loop starts from x = 0, it'll stop instantly because x is not bigger than NUMITEMS.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Looping in a spiral
I'm creating a program to populate a 3 by 3 matrix. I want to result in something looking like this
5 4 3
6 1 2
7 8 9
As you have probably noticed it is a spiral.
Now the algorithm I'm using is this: I have a 2-d array where the values represent the coordinates of the number. First I assign that every number coordinate in this array will have a value of 10. Then starting at 9 I decrease my x coordinate and assign the value of the coordinate to currentnum - 1 until it reaches the end or its value is not 10; Then I do the same thing except I increase the value of Y; Then decrease the value of x; Then of Y;
The reason I assign 10 to every number is so like it acts as a road for my program. Since current num will never exceed 9. If the value of a square is 10 it is like a green light. If it is not 10 meaning a value has been assigned to that square it breaks out of it.
Here is my code, please note it is written in Java
public class spiral {
/**
* #param args
*/
public static void main(String[] args) {
int spiral [] [] = new int[3][3];
for(int i = 0; i <= 2; i++){
for(int j = 0; j <= 2; j++){
spiral[i][j] = 10;
}
}
//0 is x value, 1 is y value
spiral[0][0] = 9;
int x = 1;
int y = 1;
int counter = 1;
int currentnum = 9;
int gridsquare = 3;
for(int i = 0; i <= 8; i++){
if(counter == 5){
counter = 1;
}
if(counter == 1){
System.out.println(x + " " + y);
for(int j = 0;j <= 1;j++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
x += 1;
}
else{
y += 1;
break;
}
}
}
if(counter == 2){
for(int k = 0; k <= 0; k++){
System.out.print(x + " " + y);
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
y += 1;
}
else{
x -= 1;
break;
}
}
}
if(counter == 3){
for(int z = 0; z <= 0; z++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
x -= 1;
}
else{
y -= 1;
break;
}
}
}
if(counter == 4){
for(int b = 0; b <= 0; b++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
y -= 1;
}
else{
x += 1;
break;
}
}
}
counter++;
}
System.out.print(currentnum);
}
}
I'm getting this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at spiral.main(spiral.java:44)
Since I'm new to Java would someone please suggest a posible fix for this. Also if you see any problems with my algorithm please do inform me.
You do not need to pre-fill with 10: zero works just as well.
I think the best approach to solving the spiral is to think of how you do it manually: start in a corner, and go horizontally until you hit non-zero or an edge of the array. Then you turn right. Stop when the current number goes past N*N.
Now let's look at what each part of the algorithm means:
Starting in the corner means setting x=0 and y=0.
Going in a straight line means x=x+dx, y=y+dy, where either dx or dy is zero, and dy or dx is 1 or -1.
Turning right means assigning dx to dy and -dy to dx.
Here is how it looks in the code:
int current = 1;
// Start in the corner
int x = 0, y = 0, dx = 1, dy = 0;
while (current <= N*N) {
// Go in a straight line
spiral[x][y] = current++;
int nx = x + dx, ny = y + dy;
// When you hit the edge...
if (nx < 0 || nx == N || ny < 0 || ny == N || spiral[nx][ny] != 0) {
// ...turn right
int t = dy;
dy = dx;
dx = -t;
}
x += dx;
y += dy;
}
You've incremented x or y to 3 which is past the end of one of your arrays.
Step through your program with the debugger or add System.out.println statements before each if (counter) to find out where you're doing this.