-2

I am trying to take an input from the user and validate it to make sure it is not a null value. I will also have to convert a string to an integer. I have been trying to use scanner to get this result but with limited success. What am I doing wrong? FYI I am brand new to Java (~two weeks). So please forgive any ignorance that my question may contain.

import java.util.Scanner;

public class NumbersTest {

    public static void main(String[] args) {

        Scanner userInput = new Scanner(System.in);

        String Num = args[0];
        int i = Integer.parseInt(Num);

        if (userInput == null){
                printError();
                return;
               }

                else if (i % 2 == 0){ 
                    System.out.println("even");
                }

                    else if (i % 2 != 0){ 
                        System.out.println("odd");
                    }
            }   

            private static void printError() {
                    System.out.println("Please enter a number.");
                }
      }
Part_Time_Nerd
  • 994
  • 7
  • 26
  • 56
  • Can you please tell why are you using `input` variable that you are checking for null, it had not even declared anywhere. – Soven K Rout Jun 20 '16 at 04:17
  • Where are you using userInput variable ? I think input should be userInput.nextline()?? – CrazyJavaLearner Jun 20 '16 at 04:18
  • 1
    Your code formatting is not good, especially your code indentation. Understand that code formatting isn't there to make code "look good" but rather the rules are there to help you quickly see what code belongs to what scope, something that helps you debug and understand your code. You will want to put in the effort to format well, for *your* benefit, so you can more easily debug problems, and for *ours* so we can more easily understand your code and help you. This isn't a trivial request. – Hovercraft Full Of Eels Jun 20 '16 at 04:23
  • when you want to take input from command line then why you are using scanner, and if you want to use scanner then why taking args from command line ? – Vickyexpert Jun 20 '16 at 04:28

3 Answers3

1

I suppose you are new to Java. Though the question isn't a valid one as you didn't get the basics and the program won't even compile in first place, I put forth basic points below.

userInput variable is a Scanner reference and not the input as your naming convention says. For your reference, modify it as below to understand better.

Scanner inputScanner = new Scanner(System.in);

The null check for inputScanner thus becomes unnecessary as it's newly initialized above.

For you to check if input is not null, first get the input using, inputScanner.nextLine() and proceed forward.

Happy learning.

Karthik R
  • 5,523
  • 2
  • 18
  • 30
1

Well, based on the code you have provided above here is what I notice:

  1. It does not compile because the variable input is not defined.
  2. It is parsing the first command line argument instead of the input from the System.in stream when you do this:

    String Num = args[0];

    int i = Integer.parseInt(Num);

  3. It does not catch NumberFormatException that could be thrown by calling Integer.parseInt

  4. It does not close the Scanner.

Here is the code with these issues corrected:

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

        String input = userInput.next();
        if (input == null) {
            printError();
            userInput.close();
            return;
        }

        try {
            int i = Integer.parseInt(input);
            if (i % 2 == 0) {
                System.out.println("even");
            }

            else if (i % 2 != 0) {
                System.out.println("odd");
            }
        } catch (NumberFormatException e) {
            printError();
        }

        userInput.close();

    }

    private static void printError() {
        System.out.println("Please enter a number.");
    }

One last thought - I doubt that Scanner, when used this way, will ever return a null because it defaults to using whitespace as its delimiter - see this page. So, it's probably not necessary to check for null but it certainly won't hurt anything and as general good practice you're better off handling potential errors than not.

D.B.
  • 4,523
  • 2
  • 19
  • 39
  • why is it necessary to close System.in ? – Scary Wombat Jun 20 '16 at 04:37
  • You're not closing System.in, you're closing the Scanner reading from System.in. You can find answers to that question on this site, here's [one that's pretty good](http://stackoverflow.com/questions/7652050/why-do-i-need-to-use-finally-to-close-resources). – D.B. Jun 20 '16 at 04:39
  • I think this addresses it better http://stackoverflow.com/questions/14142853/close-a-scanner-linked-to-system-in – Scary Wombat Jun 20 '16 at 04:47
  • You say that Scanner will never return a null. Would creating a Boolean and setting it too false, as an exit condition for a loop be better? When it’s successful, set it to true and exit the loop and if it is unsuccessful, ask for the user's input. I have just seen Scanner used for a similar program and thought it might be useful here. – Part_Time_Nerd Jun 20 '16 at 05:50
  • @BWMustang13 actually, to be precise, I said I didn't think that when it's used in this way it would ever return null. There may be times when a `Scanner` could return a null from one or more of its methods, but I don't think this use case will see that happen. Regarding your question I don't quite understand what you're asking. It sounds like you want to create a loop that will continue asking for valid input as long as invalid input is given. I think that's a great idea, but I didn't implement it as it wasn't part of the question. – D.B. Jun 20 '16 at 14:47
0

In this code you have 4 variables

Scanner userInput = new Scanner(System.in);  // this is OK
String Num = args[0];               // args are command line parameters - not needed
int i = Integer.parseInt(Num);  // Should be parsing the userInput e.g. nextLine() ?
if (input == null){             // where on earth has input come from

so try something like

public static void main(String[] args) {

    Scanner userInput = new Scanner(System.in);
    String input = userInput.nextLine();

    if (input == null || input.length() == 0){
            printError();
            return;
    }

    int i = Integer.parseInt(input);
    if (i % 2 == 0){ 
         System.out.println("even");
    }
    else {                           // no else if needed, as there are only two choices
         System.out.println("odd");
    }
}

private static void printError() {
    System.out.println("Please enter a number.");
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • I was essentially trying to write the code so that the user could enter a number on the same command line (ex.java Test_2 5234) and it would print "odd", "even", or the error message. That is why I was trying to reference args and I assumed I had to declare that string first. – Part_Time_Nerd Jun 20 '16 at 05:40
  • well do you want to use command line arguments OR a Scanner - they are not the same thing – Scary Wombat Jun 20 '16 at 05:42
  • Really I want the command line inputs but I could not get it to work (that was my attempt with args[0]) so I tried to use the Scanner function. I have only been working with Java for about two weeks so I am not very familiar with it. Thank you in advance for any help and suggestions. – Part_Time_Nerd Jun 21 '16 at 04:28
  • If you want to use the command line then forget about scanner and use `args[0]` – Scary Wombat Jun 21 '16 at 05:29