Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a Java Expert!

Join 307,220 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,683 people online right now. Registration is fast and FREE... Join Now!




Understanding 'for' & 'while'

 

Understanding 'for' & 'while', combining for & while statments

jv44heinzbar

29 Mar, 2009 - 12:58 PM
Post #1

New D.I.C Head
*

Joined: 24 Feb, 2009
Posts: 22

Hi,
I'm having trouble grasping 'for' & 'while' statements. While I understand the general concept, practical use in combining the two eludes me.

I have some code that I've written for 3 end of the chapter problems. While they work to some extent, they don't work as I expect them to. I would appreciate any help as to what I'm doing wrong and why it's wrong.

Problem1

CODE

/*

Write a Java program to create the following grid of numbers, using for statements:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

*/

import java.util.Scanner;

public class Chap8_Prob1 {
  public static void main (String []args){
    Scanner input = new Scanner(System.in);

    int howMany;
    char y;
    
    System.out.println("Drawing program 1");
    System.out.print("Do you want to start? (Y/N) ");
    y = input.next().charAt(0);
    
    while (y =='Y' || y == 'y'){
          System.out.print("How many rows/columns? (5-21) ");
          howMany = input.nextInt();
          
          while(howMany < 5 || howMany > 21) {
            System.out.print("ERROR! OUT OF RANGE (5-21). Reenter: ");
            howMany = input.nextInt();
          }
    
      for (int row = 1; row <= howMany; row++) {
              for (int column = 1; column <= howMany; column++) {
                if(column == row)
                  System.out.print(+row);
                else
                  System.out.print(+column);
              }
              System.out.println();}
    }
  }
}

/*My results:
12345
12345
12345
12345
12345

How do I subtract 1 from the beginning while adding 1 to the end? Additionally, the loop does not come back to the question, "Do you wish to continue (Y/N)?"


*/



Problem 2

CODE

/*
Use nested for loops statements to generate the following output.
Sample output:

Do you want to start(Y/N): y
Enter an integer (1 - 9) 12
ERROR! Should be positive. REENTER: 4
      1
    22
  333
4444

Do you want to continue(Y/N): y
Enter an integer (1 - 9) 6
          1
        22
      333
    4444
  55555
666666  

*/

import java.util.Scanner;

public class Chap8_Prob2 {
  public static void main (String []args){
    Scanner input = new Scanner(System.in);
    
    int howMany;
    char y;

    System.out.print("Drawing Program 2");
    System.out.print("Do you want to start? (Y/N) ");
    y = input.next().charAt(0);
    
    while (y =='Y' || y == 'y'){
          System.out.print("Enter an integer (1-9) ");
          howMany = input.nextInt();
          
          while(howMany < 1 || howMany > 9) {
            System.out.print("ERROR! OUT OF RANGE (5-21). Reenter: ");
            howMany = input.nextInt();
          }

          for (int row = 1; row <= 9; row++) {
            for (int col = 1; col <= row; col++) {
              System.out.print(row);
            }
            System.out.println();
          }
    }
  }
}
/*
My results:

1
22
333
4444
55555
666666
7777777
88888888
999999999

As you can see, my numbers are backwards...grr! Additionally, I'm having the same issue in Problem1. The loop does not come back to the question, "Do you wish to continue (Y/N)?"

*/


Problem 3

CODE


/*Write a Java program that prompts for integers and dispays them in binary.
Sample output:

Do you want to start(Y/N): y
Enter an integer and I will convert it to binary code: 16
You entered 16.
16 in binary is 10000.

Do you want to continue(Y/N): y
Enter an integer and I will convert it to binary code: 123
You entered 123.
123 in binary is 1111011. */

import java.util.Scanner;

public class Chap8_Prob3 {
  public static void main (String []args){
    Scanner input = new Scanner(System.in);
    
    int num;
    char y;
    
    System.out.print("Do you want to start? (Y/N) ");
    y = input.next().charAt(0);
    
    while (y =='Y' || y == 'y'){
          System.out.print("Enter an integer and I will convert it to binary code: ");
          num = input.nextInt();

//Honestly, I don't have a clue about how to convert an integer to binary code. HELP, please!
          

    }
  }
}


As you can see, I can do a little in each problem, but I can't seem to finish the job. Any type of help is appreciated. I must say I'm struggling to one degree or another because I'm very much a visual type of learner. I do much better when I see practical examples of code rather than theoretical pieces of code.

Thanks,
Heinz







User is offlineProfile CardPM
+Quote Post


BetaWar

RE: Understanding 'for' & 'while'

29 Mar, 2009 - 02:17 PM
Post #2

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 4,779



Thanked: 277 times
Dream Kudos: 1400
My Contributions
For the first one your problem with the output if you aren't adding the necessary number for each time through the loop. Here is an example that works:

CODE
for(int i = 1; i <= howMany; i++){
    for(int j = i; j < howMany+i; j++){
        System.out.print(j+"\t");
    }
    System.out.println();
}


Notice that you have to add i to howMany to get it to work properly in the second loop.

HTH
User is offlineProfile CardPM
+Quote Post

William_Wilson

RE: Understanding 'for' & 'while'

29 Mar, 2009 - 02:21 PM
Post #3

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,668



Thanked: 97 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
EDIT: bah, you beat me again BetaWar!

I won't do them all, but here's a breakdown of the first one, hopefully you can figure out how to do the rest. Feel free to ask more questions if you can't smile.gif

your first for loop is perfect, but the second is where it breaks down:
Say howMany = 5
CODE

for (int column = 1; column <= howMany; column++)

your loop says to loop from 1 to 5 each time, thus why the output stays the same. What you are trying to do is loop a number of times equal to howMany and start at the value of row, so it should look something like:
CODE

for (int column = row; column <= row+howMany; column++)

There are of course other ways you could do this, but I think this might help you understand how the for loop works more.
User is offlineProfile CardPM
+Quote Post

jv44heinzbar

RE: Understanding 'for' & 'while'

29 Mar, 2009 - 06:55 PM
Post #4

New D.I.C Head
*

Joined: 24 Feb, 2009
Posts: 22

Hi,
Thanks for the tips gents. I think I can see see the point of adding "i" to howMany. This will cure the loop only making it through 5 repetitions and will correspond to user input.

One of the issues I'm up against is the ability to make the numbers in the column progress.
EX.
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

The 2nd issue is in problem 2. You can see that I can get the output to write from left to right, but I can't get it to write from right to left.

EX.
1
22
333
4444
55555

vs the correct answer:
1
22
333
4444
55555

Problem 3:
Still having issues with this. I haven't found a way to convert an integer into a binary number. It's getting late here and I need to study other chapters for my test. However, I'll check back tomorrow morning. I hope you Java masters can help me.

TIA,
Heinz
User is offlineProfile CardPM
+Quote Post

pbl

RE: Understanding 'for' & 'while'

29 Mar, 2009 - 07:01 PM
Post #5

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,967



Thanked: 1188 times
Dream Kudos: 450
My Contributions
QUOTE(jv44heinzbar @ 29 Mar, 2009 - 06:55 PM) *

Problem 3:
Still having issues with this. I haven't found a way to convert an integer into a binary number. It's getting late here and I need to study other chapters for my test. However, I'll check back tomorrow morning. I hope you Java masters can help me.

Integer has a method that returns the String representation of the int passed as first paramter into the base passed as second parameter

String binary = Integer.toString(123456789, 2);



User is online!Profile CardPM
+Quote Post

jv44heinzbar

RE: Understanding 'for' & 'while'

30 Mar, 2009 - 06:17 AM
Post #6

New D.I.C Head
*

Joined: 24 Feb, 2009
Posts: 22

Thanks PBL. I'll try playing w/ that method.

As for the other two pieces of code. I've tried the suggestions and I couldn't get them to work. The suggestions allow the program to run, but the results are not correct. Well, I'm running out of time. I still don't get how I can use a for statement to create a block of numbers as required in problems 1 & 2. I've tried playing w/ my code this morning for a couple of hours. Still no luck. It's gotta to the point where I'm just guessing w/o understanding. I guess I need to be spoon fed.

Heinz
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 10:31PM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month