2

I am writing a program and there is only one error left.

It says variable zahl might not have been initialized, but I did it:

public class Primzahltest1 { 
    public static void main (String[]argv) {
        int zahl;
        IO.readInt("...");
        if (zahl<=1) {
            IO.println ("...");
            return;
        }

Can someone please help me?

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
Chiara
  • 21
  • 1

5 Answers5

2

You need to initialize you int variable with the result of readInt

int zahl = IO.readInt("...");

otherwise, this means it is unitialized

int zahl;

and this means that what your input gets discarded

IO.readInt();
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
0

Whenever you declare a variable inside a method you should initialize it like

int zahl=0;

Rahman
  • 3,755
  • 3
  • 26
  • 43
  • Not necessarily, value can be inserted with entered values. – Am_I_Helpful Oct 31 '15 at 18:19
  • Can you please elaborate what is wrong in my comment and example? – Rahman Oct 31 '15 at 18:24
  • @Rehman, you answer is perfectly correct, local variables should be initialised, http://stackoverflow.com/questions/1560685/why-must-local-variables-including-primitives-always-be-initialized-in-java otherwise if `IO.readInt("...")` will throw an error, for example somebody pass string or not integer char it will remain not initialised. – Anatoly Oct 31 '15 at 18:31
0

You didn't initialize the variable zahl you only defined it. Instead of int zahl; type int zahl=0 and the variable will be initialized Or if you wish to make zahl inputted from the user write: int zahl = IO.readInt("...");

Josh A
  • 51
  • 6
0

You did not initialize the variable zahl, so you cannot test its value. That, in combination with the fact that you're reading an int but ignoring it makes me assume you intended to assign the int you read to zahl:

int zahl = IO.readInt("...");
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

In your program you have not initialised zahl. You have only declared it.

For you to initialise it just equate zahl to the readInt.

int zahl = IO.readInt("...");

This would solve your problem.

In Java it is necessary to initialise all local variables so that you wont accidentally read something you didn't intend to.

Adarsh Bhat
  • 159
  • 1
  • 12