-3

The method won't take the variable that I assigned in return.

public static String agregarMain() {
        Scanner in = new Scanner(System.in);
        for (int i = 0; i < 1; i++) {
            System.out.println("Ingresar nombre del software/topico");
            String mainSeleccion = in.nextLine();
        if (mainSeleccion == "") {
            System.out.println("Invalid Selection, please try again");
            i--;
            continue;
        }
        return mainSeleccion;
        }
    }

I'm expecting to save the input response in mainSeleccion variable.

  • 1
    you compare string with equals method https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#equals(java.lang.Object) and your method need a return statement after the for loop –  Dec 10 '22 at 22:19
  • Declare the variable before the if block – Hovercraft Full Of Eels Dec 10 '22 at 22:32
  • 1
    The central problem here is that not all paths lead to a return statement. Incidentally, yes, the string compare is _also_ wrong. Point is, reopen - that's not the pertinent problem here. Admittedly, OP, you really should include the compiler error message in your SO questions. – rzwitserloot Dec 10 '22 at 22:37
  • close -> missing debugging information, like, well, what the actual error is... – njzk2 Dec 10 '22 at 22:40

1 Answers1

2

All paths through the code must lead to a return statement. Some analysis of this code indicates that it should always do so, but this requires knowing that for (int i = 0; i < 1; i++) will loop at least once.

The compiler isn't going to go that far. Hence, this won't compile. Just reorder a few things and it will. Separately, you also have a second issue - == checks reference identity, it doesn't do value comparison. Unless the left and right hand side are primitives (i.e. not references, and thus 'reference identity' wouldnt apply in the first place). You use equals instead, or in this case, more idiomatic, .isEmpty(). Fixing both issues:

public static String agregarMain() {
    Scanner in = new Scanner(System.in);
    String mainSeleccion = "";
    for (int i = 0; i < 1; i++) {
        System.out.println("Ingresar nombre del software/topico");
        mainSeleccion = in.nextLine();
        if (mainSeleccion.isEmpty()) {
            System.out.println("Invalid Selection, please try again");
            i--;
        }
    }
    return mainSeleccion;
}

NB: When asking question on stack overflow, include all pertinent errors. You didnt which led to some confusion in the comments and got your question closed.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72