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();






  } 

} }

  • 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. – Dawood ibn Kareem Oct 15 '13 at 02:30
  • +1 For the RegEx, OP is going to have a bunch of exceptions using most of the answers below. – JNYRanger Oct 15 '13 at 02:34
  • @DavidWallace "regular expression" doesn't match "super beginner" ;-) user2833276 your answer is below. +1 question for persisting in the face of locked question :) – necromancer Oct 15 '13 at 02:43
  • i want to go simple, i.e. just an integer, with a positive or negative value. im not sure how to do regular expressions , ill have to look that up because that sounds very handy, thanks :) – Geneticwarrior Oct 15 '13 at 02:52
  • read input using readline, 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? anything other than that pattern would violate your test for 'is this an integer'. Double is an extended precision real number, btw. – ChuckCottrill Oct 15 '13 at 03:06
  • Do you want it to accept 9876543210 as a number? If so, you can't use `Integer.parseInt`. – Dawood ibn Kareem Oct 15 '13 at 03:06
  • @no_answer_not_upvoted Although you can write some horrendously complicated regular expressions when you put your mind to it, you don't need to here. The concept of what a regular expression is and does is a MUCH easier thing for a beginner to grasp than what an Exception is, and what "try" and "catch" do. – Dawood ibn Kareem Oct 15 '13 at 03:16
  • 1
    @DavidWallace that's a reasonable perspective given that exceptions indeed are indeed non-intuitive. i shouldn't have dismissed regex that quickly. – necromancer Oct 15 '13 at 03:29
  • Yeah. I plan to post an answer that uses the regular expression approach, later when I have some time. – Dawood ibn Kareem Oct 15 '13 at 03:55
  • you can use scanner.hasNextInt() http://stackoverflow.com/questions/303913/java-reading-integers-from-a-file-into-an-array – Kanagavelu Sugumar Oct 15 '13 at 05:40
  • @KanagaveluSugumar Why would you want to do that? You don't want the program to stop working as soon as the user enters something that isn't an integer. – Dawood ibn Kareem Oct 15 '13 at 06:16
  • @DavidWallace Hi David, I didn't get your point, I think hasNextInt() will be blocked un till user enters int Value. So while(hasNextInt()) is fine i guess. Could you please elaborate in your answer why we should not use "hasNextInt()" ?? It will be helpful. – Kanagavelu Sugumar Oct 15 '13 at 06:26
  • 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. – Dawood ibn Kareem Oct 15 '13 at 06:59
  • @DavidWallace ooh that's Great!. I missed that error handling part... – Kanagavelu Sugumar Oct 15 '13 at 11:03

4 Answers4

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
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");
      }
    }
  }
}
necromancer
  • 23,916
  • 22
  • 68
  • 115
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.

GregA100k
  • 1,385
  • 1
  • 11
  • 16
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.");
        }
    }
}
Community
  • 1
  • 1
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42