Cody Harrison
Cody Harrison

Reputation: 33

While loop issue for a beginner programmer

please do keep in mind I am a brand new computer programmer and I am very stuck on this program I have to write. I already had asked a question earlier and got some great feedback and it's almost complete. The problem I am having is that in the program I am using a for a loop but technically I am only supposed to use while loops and am having major compile issues when trying to revert it to a while loop. Here is an example of the code.

import java.util.Scanner;

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

         int integerx;
        System.out.print("Enter an even integer x: ");
        integerx = input.nextInt();

        while (integerx % 2 != 0) 
        {
            System.out.print("Try again, enter an even integer x: ");
            integerx = input.nextInt();
        }

        for (int x = 4; x <= integerx; x += 4) 
        {
            System.out.println("4 is a multiple of " + x);
        }
    }
}

Upvotes: 0

Views: 106

Answers (2)

Chris Sharp
Chris Sharp

Reputation: 1995

Your original requirements, posted 2 days ago where you got the code you're now trying to fix, are as follows: Your program will do the following:

  1. Prompt the user to enter an even integer x
  2. Continue to prompt the user for x until the user enters an even integer
  3. The program will then print all the even integers between 2 and x that are multiples of four.

None of the code above will accomplish step 3. I suggest you read step 3 very closely, figure out how you would accomplish it without code (on a piece of paper, for example) and only then try to code it. You also need to read your text book and actually understand what these loops are doing instead of asking people to write them for you. You're in school, presumably, to learn how to code. Come back and ask a reasonable question after you have actually tried to do it and looked at your text book and some other examples.

Upvotes: 0

Hallow
Hallow

Reputation: 1070

if all you want is to transform the last loop (for loop) into a while then all you need is

int x = 4; // the for loop initialization 
while(x <= integerx){ // for loop evaluation (done every iteration)
    System.out.println("4 is a multiple of " + x); // whatever you want
    x += 4; // for loop update 
}

This does the exact same thing as a foor loop, and every for loop can be turned into a while loop and vice-versa, it can be more readable or not but that is up to the programmer.

EDIT I have tested it on Online Compiler Java and it works as you intend (if i perceived your requirements in the comments rightfully).

Upvotes: 2

Related Questions