-1

I use Eclipse for programming and it tells me if want to output the "Input String"

Cannot make a static reference to the non-static field Input

Why has the variable to be static in the finally-block?

import java.util.Scanner;

public class NameSort {
    String Input;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            System.out.println("Inupt some Text");
            while (sc.hasNextLine()){

                String Input = sc.nextLine();
                System.out.println(Input);
                if (Input.toLowerCase().equals("ende")) {
                    System.exit(0);
                    sc.close();
                }
            }

        } finally {
            if (sc != null)
            sc.close();
            System.out.print(Input);
        }
    }
}
Destro
  • 27
  • 6
  • 1
    Because the method is `static`. --- *FYI:* The `Input` local variable inside the `while` loop is entirely distinct from the `Input` field, since means that the field is never assigned, so will always be `null` in he `finally` block. – Andreas Mar 25 '20 at 20:44
  • 1
    You have defined `Input` twice in two different scopes. Start by renaming either of those variables, and then maybe the answer will be clearer. – Kenneth K. Mar 25 '20 at 20:44
  • 1
    *FYI:* It's impossible for `sc` to be `null` in the `finally` block. – Andreas Mar 25 '20 at 20:45
  • 1
    You shouldn't close a `Scanner` whose `InputStream` is `System.in`, even though the IDE tells you that you should. – Abra Mar 25 '20 at 20:50

2 Answers2

1

In Java, you can not use/call a non-static variable/method from a static method. Also, other than the following code, the rest of your code is useless:

import java.util.Scanner;

public class NameSort {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input;
        System.out.println("Inupt some Text");
        while (!(input = sc.nextLine()).equals("ende")) {
            System.out.println(input);
        }
    }
}

A sample run:

Inupt some Text
hello
hello
hi
hi
ende
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

This has nothing to do the finally block, in Java you can't access non-static members or methods from static methods.

You should make Input static if you want to access it from main.

Adwait Kumar
  • 1,552
  • 10
  • 25