1

Ok, I posted once earlier but it was locked due to not demonstrating a basic understanding, and the answers I did get before it was locked didn't help me. I'm at a super beginner level of java and this is what I want my program to do (will post code at end). I want the user to input anything they want. Then, if it is not a number, I want it to display that they need to input a number. Then, after they input a number, I want it to display whether or not that number is even or odd. I read about parseInt and parseDouble but i can't figure out how to get it to work how I want. I am not sure any more if parsing is what i want to do. I dont want to instantly convert it to numbers, just to check if it IS a number. then i can proceed to do things after the program has determined if it is a character or number. thanks for any help and let me know if you need more information!

ok i changed some things and used a lot of code from no_answer_not_upvoted. here is what i have now. it runs fine and works with negative and positive whole numbers as specified in the directions. the only thing that bugs me is after all is said and done, i get this error in the compile box at the bottom of eclipse. the program does what is intended and stops appropriately but i dont understand why i am getting this error.

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at monty.firsttry2.main(firsttry2.java:21)


public static void main(String[] args) {

    System.out.print("Enter a character or number. This program will run until you enter a whole number, then it will"
            + "tell you if it was even or odd.");

    while (true) {
    Scanner in=new Scanner(System.in);     

    int num;
    while(true)   {
        String input=in.nextLine();
    try {

        num=Integer.parseInt(input);

        break;
        }
    catch (NumberFormatException e) {System.out.print("That wasn't a whole number. Program continuing.");}



    }
    if (num==0) {System.out.print("Your number is zero, so not really even or odd?");} 
    else if (num%2!=0){System.out.print("Your number is odd.");}
    else {System.out.print("Your number is even");}
    in.close();






  } 

} }

14
  • 1
    I would try matching it against some regular expression that expresses what it means to be a number. So, for example, can it have a negative sign? A decimal point? Commas separating every three digits? How about an E for exponential notation? Is it a number if it starts with zero, then another digit? And so on. Work out exactly what you think it means to say "this String is a number". Then design the regular expression for it. Oct 15, 2013 at 2:30
  • +1 For the RegEx, OP is going to have a bunch of exceptions using most of the answers below.
    – JNYRanger
    Oct 15, 2013 at 2:34
  • @DavidWallace "regular expression" doesn't match "super beginner" ;-) user2833276 your answer is below. +1 question for persisting in the face of locked question :) Oct 15, 2013 at 2:43
  • 1
    @DavidWallace that's a reasonable perspective given that exceptions indeed are indeed non-intuitive. i shouldn't have dismissed regex that quickly. Oct 15, 2013 at 3:29
  • 2
    Yes, as you say, it will be blocked. But the OP doesn't want this. The required behaviour is that a message is shown, saying that what was entered is not a number. The program can't do that if it's blocked waiting for an integer. Oct 15, 2013 at 6:59

4 Answers 4

2

Assumption

A String is to be considered a number if it consists of a sequence of digits (0-9), and no other characters, except possibly an initial - sign. Whereas I understand that this allows Strings such as "-0" and "007", which we might not want to consider as numbers, I needed some assumptions to start with. This solution is here to demonstrate a technique.

Solution

import java.util.Scanner;

public class EvensAndOdds {
    public static final String NUMBER_REGEXP = "-?\\d+";
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for(;;) {   // Loop forever
            System.out.println("Enter a number, some text, or type quit");
            String response = input.nextLine();
            if (response.equals("quit")) {
                input.close();
                return;
            }
            if (response.matches(NUMBER_REGEXP)) {   // If response is a number
                String lastDigit = response.substring(response.length() - 1);
                if ("02468".contains(lastDigit)) {
                    System.out.println("That is an even number");
                } else {
                    System.out.println("That is an odd number");
                }
            } else {
                System.out.println("That is not a number");
            }
        }
    }
}

Justification

This solution will match a number of ANY length, not just one that will fit into an int or a long; so it is superior to using Integer.parseInt or Long.parseLong, which both fail if the number is too long. This approach can also be adapted to more complicated rules about what constitutes a number; for example, if we decided to allow numbers with comma separators (such as "12,345" which currently will be treated as not a number); or if we decided to disallow numbers with leading zeroes (such as "0123", which currently will be treated as a number). This makes the approach more versatile than using Integer.parseInt or Long.parseLong, which both come with a fixed set of rules.

Regular expression explanation

A regular expression is a pattern that can be used to match part of, or all of a String. The regular expression used here is -?\d+ and this warrants some explanation. The symbol ? means "maybe". So -? means "maybe a hyphen". The symbol \d means "a digit". The symbol + means "any number of these (one or more)". So \d+ means "any number of digits". The expression -?\d+ therefore means "an optional hyphen, and then any number of digits afterwards". When we write it in a Java program, we need to double the \ character, because the Java compiler treats \ as an escape character.

There are lots of different symbols that can be used in a regular expression. Refer to http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html for them all.

0

this shows you how to do it

import java.util.Scanner;

public class EvenOdd {
  public static void main(String[] args) {
    System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
    try (Scanner in = new Scanner(System.in)) {
      int n;
      while (true) {
        String input=in.nextLine();
        try {
          n = Integer.parseInt(input);
          break;
        } catch (NumberFormatException e) {
          System.out.println("you did not enter just an integer, please try again");
        }
      }
      if (n % 2 == 0) {
        System.out.println(n + " is even");
      } else {
        System.out.println(n + " is odd");
      }
    }
  }
}
0

As is already mentioned in other answers, you will need to call parseDouble statically with

Double theNumber = Double.parseDouble(numberString);

Next you will want to look at wrapping this in a try/catch so that you can do the even/odd check if theNumber is created or set the error message if an exception is caught.

0

Since you are a beginner, you need to understand the difference between numbers (integers, double, strings, characters), so the following will guide you.

First, read input one line at a time, Java read line from file)

Then scan line looking for characters that form what you consider to be an integer (allow leading spaces?, then '+' or '-', then digits 0-9, and then trailing spaces.

Here are the rules (for integers)

Anything other than this pattern violates the test for 'is this an integer'. Btw, Double is an extended precision real number.

import java.lang.*;
import java.util.Scanner;

public class read_int
{
    public static boolean isa_digit(char ch) {
        //left as exercise for OP
        if( ch >= '0' && ch <= '9' ) return true;
        return false;
    }
    public static boolean isa_space(char ch) {
        //left as exercise for OP
        if( ch == ' ' || ch == '\t' || ch == '\n' ) return true;
        return false;
    }
    public static boolean isa_integer(String input) {
        //spaces, then +/-, then digits, then spaces, then done
        boolean result=false;
        int index=0;
        while( index<input.length() ) {
            if( isa_space(input.charAt(index)) ) { index++; } //skip space
            else break;
        }
        if( index<input.length() ) {
            if( input.charAt(index) == '+' ) { index++; }
            else if( input.charAt(index) == '-' ) { index++; }
        }
        if( index<input.length() ) {
            if( isa_digit(input.charAt(index)) ) {
                result=true;
                index++;
                while ( isa_digit(input.charAt(index)) ) { index++; }
            }
        }
        //do you want to examine rest?
        while( index<input.length() ) {
            if( !isa_space(input.charAt(index)) ) { result=false; break; }
            index++;
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");

        Scanner in=new Scanner(System.in);
        String input=in.nextLine();
        if( isa_integer(input) ) {
            System.out.print("Isa number.");
        }
        else {
            System.out.print("Not a number.");
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.