I
I
Ivan the Terrible2015-09-23 18:40:21
Java
Ivan the Terrible, 2015-09-23 18:40:21

Why is this happening?

package rhymeCounter;
import java.util.*;
import java.io.*;
public class rhymeCounter {
Scanner myConsoleScanner = new Scanner(System.in);
PrintWriter myPrinter = new PrintWriter(System.out);
public static void rhyme() throws IOException {
String a1 = "Twenty-one, Thirty-one, Forty-one, Fifty-one";
String a2 = "Twenty-two, Thirty-two, Forty-two, Fifty-two";
for(int i = 1; i <= 100; i++) {
switch(i) {
case 1:
String j = a1;
break;
case 2:
j = a2; break;
}
System.out.println("The number " + i + "has these rhymes: " + j );
}
}
}
Gives an error : " j cannot be resolved to a variable "
Where did I go wrong ? What's wrong ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton, 2015-09-23
@warriorkg

The problem is in the scope of the variable j. The point is that your variable is only visible in case 1 and nowhere else. Therefore, the compiler swears that it is impossible to assign a value. Declare j at the beginning of the loop, or make it static, and you'll be fine. For example like this

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Apply {

    Scanner myConsoleScanner = new Scanner (System.in);
    PrintWriter myPrinter = new PrintWriter (System.out);
    static String j;

    public static void main(String[] args) {
        try{
            Apply.rhyme ();
        }
        catch (IOException ex){
            ex.printStackTrace ();
        }
    }

    public static void rhyme() throws IOException {
        String a1 = "Двадцать один, Тридцать один, Сорок один, Пятьдесят один";
        String a2 = "Двадцать два, Тридцать два, Сорок два, Пятьдесят два";

        for(int i = 1; i <= 100; i++) {
            switch(i) {
                case 1:
                    j = a1;
                    break;
                case 2:
                    j = a2; break;
            }
            System.out.println("У числа " + i + "эти рифмы : " + j );
        }
    }
}

D
DVamp1r3, 2015-09-23
@DVamp1r3

j inside case. must be declared before switch

M
Maxim Moseychuk, 2015-09-23
@fshp

Because j is defined in the case 1 block, and is only available there. And you are trying to use it in other scopes. Move the declaration before the switch, and leave only the assignment in case 1. These are elementary things that are covered in the first 2-3 chapters of any book on Java.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question