CodingIsAwesome
CodingIsAwesome

Reputation: 1966

Java simple program using the same variable for input - not working

All I want to do is use the string variable for all my scanner input.

public static void main(String[] args){
Scanner getInput = new Scanner(System.in);

String defaultInFile = "fileContainingEmails.txt";
String defaultOutFile = "copyPasteMyEmails.txt";

String myInFile;
String myOutFile;

    System.out.print("Enter input filename [default: " + defaultInFile + "]: ");
    //CRUD applications oh yea
    String myInputNom = getInput.nextLine();
    if (myInputNom.equals(""))
    {
        myInFile = defaultInFile;
    }
    else
    {   
        myInFile = myInputNom;
    }

    //System.out.println(defaultOutFile); THIS WORKS

    if (myInputNom.equals(""))
    {
        System.out.print("Enter output filename [default: " + defaultOutFile + "]: ");
    }
    else
    {
        System.out.print("Enter output filename [default: " + myInFile + "]: ");
    }

    //System.out.println("'" + myInputNom + "'");        

    myInputNom = getInput.nextLine();

    System.out.println("'" + myInputNom + "'"); 

    if (myInputNom.equals(""))
    {
        myOutFile = defaultOutFile;
    }
    else
    {
        myOutFile = myInputNom;
    }

    System.out.println("Input file: " + myInFile);
    System.out.println("Output file: " + myOutFile);
    }

So what am I doing wrong? The second getInput.nextLine(); acts like it ignores all input.

I expect something in myOutFile, but I get nothing.

Thanks!

Upvotes: 0

Views: 506

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285402

Your comment:

I don't want to write it anywhere, just display the default file name on the screen if the input is blank

is in error as your input file name will never be blank. If the user enters no text for the input file, it will be given the default value:

  if (myInputNom.equals("")) {
     System.out.print("Enter output filename [default: " + defaultOutFile + "]: ");
  } else {
     System.out.print("Enter output filename [default: " + myInFile + "]: ");
  }

So the if condition here:

  if (myInputNom.equals("")) {
     myOutFile = defaultOutFile;
  } else {
     myOutFile = myInputNom;
  }

will never be true.

Upvotes: 1

Borealid
Borealid

Reputation: 98469

Your code works fine here.

% java -cp . foo
Enter input filename [default: fileContainingEmails.txt]: df
Enter output filename [default: df]: dfee
'dfee'
Input file: df
Output file: dfee

It's actually a relief to try to help, only to discover that nothing is broken.

Upvotes: 1

Related Questions