0

Maybe I'm making this more complicated than it needs to, but, when I try write the code, I get firstone cannot be resolved to a variable.

import java.util.Scanner;

import Diag.Prompts

public class app extends Prompts{

    public static void main(String[] args) {
        
        Prompts.Intro();

        Scanner uinput = new Scanner(System.in);
            System.out.print(firstone);
        String a = uinput.nextLine();
            System.out.print(secondone);
            
    }
    
}

I've tried making a object of the prompts class, but no joy.

public class Prompts {

    Protected static void Intro() {

        System.out.println("text");
    }
    
        protected void promptOne(){

            String firstone = "some text to be printed";

                String secondone = "some more text to be printed";

        }
}

Apologies if I haven't explained very clearly, I am still new to Java/coding in general.

Hopefully you can see I am trying to access and print the two variables from another protected class individually, without having to create multiple methods just to print one variable. I know I could just do that or simple create methods with a single System.out, but I wanted to know if this would work.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • The String `firstone` is local to the method `Prompts#promptOne`. Try declaring it in the class scope. – venkatvb Jan 28 '21 at 13:02
  • So i declared `firstone` as you said, the it then complained it wasn't static so i changed it to `protected static String firstone;` and took the data types off the variable within the `promptOne` method. now it doesnt complain about the code but when i run it, it prints null. – Sovereign Jan 28 '21 at 14:09
  • You never call promptOne()! – ecerer Jan 28 '21 at 14:16
  • Ok so i have called `promptOne()` as `Prompts.promptOne();` before the System.out and it works!! however im not sure why? i understand if `promptOne()` held a System.out within it, i could just call the method as is, but for some reason with variables i have to call the method before i can use the variables within it? – Sovereign Jan 28 '21 at 15:56

0 Answers0