1

好的,我之前发布过一次,但是由于没有表现出基本的理解而被锁定,并且在锁定之前我得到的答案对我没有帮助。我处于 Java 的超级初学者水平,这就是我想要我的程序做的事情(将在最后发布代码)。我希望用户输入他们想要的任何内容。然后,如果它不是数字,我希望它显示他们需要输入数字。然后,在他们输入一个数字后,我希望它显示该数字是偶数还是奇数。我阅读了有关 parseInt 和 parseDouble 的信息,但我不知道如何让它按我想要的方式工作。如果解析是我想要做的,我不再确定。我不想立即将其转换为数字,只是为了检查它是否是数字。然后我可以在程序确定它是字符还是数字后继续做事情。

好的,我更改了一些东西并使用了很多来自 no_answer_not_upvoted 的代码。这就是我现在所拥有的。它运行良好,可以使用说明中指定的负整数和正整数。毕竟,唯一让我烦恼的是,我在 Eclipse 底部的编译框中得到了这个错误。该程序按预期执行并适当停止,但我不明白为什么会出现此错误。

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






  } 

} }

4

4 回答 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.

于 2013-10-15T05:32:52.620 回答
0

正如其他答案中已经提到的那样,您需要使用 parseDouble 静态调用

Double theNumber = Double.parseDouble(numberString);

接下来,您将要查看将其包装在try/catch中,以便您可以执行偶数/奇数检查是否创建了 theNumber,或者如果捕获到异常,则设置错误消息。

于 2013-10-15T02:34:17.850 回答
0

这告诉你怎么做

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");
      }
    }
  }
}
于 2013-10-15T02:29:25.107 回答
0

由于您是初学者,因此需要了解数字(整数、双精度、字符串、字符)之间的区别,所以下面将指导您。

首先,一次读取一行输入, Java 从文件中读取一行

然后扫描行查找构成您认为是整数的字符(允许前导空格?,然后是“+”或“-”,然后是数字 0-9,然后是尾随空格。

这是规则(对于整数)

除了这个模式之外的任何东西都违反了“这是一个整数”的测试。 顺便说一句,Double 是扩展精度实数。

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.");
        }
    }
}
于 2013-10-15T04:04:57.097 回答