user4134594
user4134594

Reputation:

Multiples of 7 between 98 and 266

The statement says:

Write a list of multiples of 7 between 98 and 266, both including

I put this code:

import java.util.*;

public class Multiples7 {

  public static void main (String[] args) {
    Scanner entrada;

    int x;

    entrada = new Scanner(System.in);

    while (x >= 98 && x <= 266) {
      if (x % 7 == 0){
        System.out.println(x);
      }
    }
  }
}

and I get this error that I don't understand: variable x might not have been initialized

Why x not start?

Upvotes: 1

Views: 127

Answers (7)

Elliott Frisch
Elliott Frisch

Reputation: 201497

It could be a single for loop. Initialize x at 98, increment by 7 and stop when x is greater then 266. Something like,

for (int x = 98; x <= 266; x += 7)
    System.out.printf("%d = 7 * %d%n", x, x / 7);

Upvotes: 0

Colin D
Colin D

Reputation: 5661

To solve the question asked: you simply need to initialize x, which is currently uninitialized. To initialize a variable, you have to assign it a value. For example x = 0;.

However, that still is not going to cause your program to print the correct result.

One way to accomplish what you actually want to do is iterate the numbers between 98 and 266 print them when they are divisible by 7.

for(int y = 98; y <= 266; ++y) if (y % 7 == 0) System.out.println(y);

alternately, you can start at 98 (14 * 7) and then increment it by 7, printing as you go.

int y = 98;
while(y <= 266) {
  System.out.println(y);
  y+=7 
}

Upvotes: 3

Simulant
Simulant

Reputation: 20122

you need to initialize x so it has a starting value and is not empty when your programm starts(int x = 98;). Also you should increment x inside your while loop (x++; or you will have an infinity loop always printing the same line.

int x = 98;

entrada = new Scanner (System.in);

while ( x >= 98 && x <= 266) {
  if (x % 7 == 0){
    System.out.println(x);
  }
  x++;
}

Upvotes: 0

Tetramputechture
Tetramputechture

Reputation: 2921

Alternatively, you could use a for loop, which includes initialization.

for (int x = 98; x <= 266; x++) {
    if (x % 7 == 0) {
        System.out.println(x);
    }
}

Upvotes: 2

Fyre
Fyre

Reputation: 1180

You need to read the value of x or initialize it yourself. This error is shown because there is a chance that the program might get over without x being initialized.

Just initialize it :

int x = 0;

or read from scanner

x = entrada.nextInt();

Upvotes: 2

sealz
sealz

Reputation: 5408

You need to give X a starting value or it might as well not exist.

For example if X should start at 0 then use:

int x = 0;

Upvotes: 1

Robin Ellerkmann
Robin Ellerkmann

Reputation: 2113

You have only declared x but did not initialize it. Insted of int x do int x = 0;. Replace 0 with the desired value.

Upvotes: 1

Related Questions