0

StackOverflow 社区。我正在尝试创建一个用于操作 X 和 Y 坐标的命令行应用程序。让我感到困惑的是,当它在案例 B 下询问 X 或 Y 时,它认为我输入了 X 或 Y 以外的其他内容,而我根本没有输入任何内容。是什么导致了这种情况发生?

public class OrderedPairTest {


    public static void main(String[] args) {
        OrderedPair op1 = new OrderedPair();
        OrderedPair op2 = new OrderedPair();
        OrderedPair op3 = new OrderedPair();
        EasyReader console = new EasyReader();
        System.out.println("Ordered Pairs 1, 2, and 3 are set to (0,0).\nWhat would you like to do?");
        System.out.println("Type A to display values, B for setting values, C for moving values,\nD for string conversion, E for printing, and F for other calculations.");         
        char one = console.readChar();
        switch(one){
            case 'A':
                System.out.print("Type the ordered pair's number: ");
                int onea = console.readInt();
                switch(onea){
                    case 1:
                        op1.getX();
                        op1.getY();
                        break;
                    case 2:
                        op2.getX();
                        op2.getY();
                        break;
                    case 3:
                        op3.getX();
                        op3.getY();
                        break;
                    default:
                        System.out.println("Invalid pair number. Returning to main menu.");
                        main(null);
                    }
                main(null);                                                                             
            case 'B':
                System.out.print("Type the ordered pair's number: ");
                int oneb = console.readInt();               
                switch(oneb){
                    case 1:
                        System.out.print("\nX or Y?");
                        char twoa = console.readChar();
                        switch(twoa){
                            case 'X':
                                System.out.print("\nValue? ");
                                int valx1 = console.readInt();  
                                op1.setX(valx1);
                                break;
                            case 'Y':
                                System.out.print("\nValue? ");
                                int valy1 = console.readInt();  
                                op1.setY(valy1);
                                break;
                            default:
                                System.out.println("\nInvalid axis. Returning to the main menu.");
                                main(null);
                        }           
                        break;
                    case 2:
                        System.out.println("X or Y?");
                        char twob = console.readChar();
                        switch(twob){
                            case 'X':
                                System.out.println("Value?");
                                int valx2 = console.readInt();  
                                op1.setX(valx2);
                                break;
                            case 'Y':
                                System.out.println("Value?");
                                int valy2 = console.readInt();  
                                op1.setY(valy2);
                                break;
                            default:
                                System.out.println("Invalid axis. Returning to the main menu.");
                                main(null);
                        }       
                        break;
                    case 3:
                        System.out.println("X or Y?");
                        char twoc = console.readChar();
                        switch(twoc){
                            case 'X':
                                System.out.println("Value?");
                                int valx3 = console.readInt();  
                                op1.setX(valx3);
                                break;
                            case 'Y':
                                System.out.println("Value?");
                                int valy3 = console.readInt();  
                                op1.setY(valy3);
                                break;
                            default:
                                System.out.println("Invalid axis. Returning to the main menu.");
                                main(null);     
                        }
                        break;
                    default:
                        System.out.println("Invalid pair number. Returning to main menu.");
                        main(null);
                    }
                main(null); 
            case 'C':
                System.out.print("Type the ordered pair's number: ");
                int onec = console.readInt();               
                switch(onec){
                    case 1:
                        System.out.println("X, Y or B (Both)?");
                        char twoa = console.readChar();
                        switch(twoa){
                            case 'X':
                                System.out.println("Value?");
                                int valx1 = console.readInt();  
                                op1.moveX(valx1);
                                break;
                            case 'Y':
                                System.out.println("Value?");
                                int valy1 = console.readInt();  
                                op1.moveY(valy1);
                                break;
                            case 'B':
                                System.out.println("Value of X?");
                                int valx4 = console.readInt();  
                                System.out.println("Value of Y?");
                                int valy4 = console.readInt();  
                                op1.moveXY(valx4,valy4);
                                break;
                            default:
                                System.out.println("Invalid axis. Returning to the main menu.");
                                main(null);
                        }           
                        break;
                    case 2:
                        System.out.println("X or Y?");
                        char twob = console.readChar();
                        switch(twob){
                            case 'X':
                                System.out.println("Value?");
                                int valx5 = console.readInt();  
                                op1.moveX(valx5);
                                break;
                            case 'Y':
                                System.out.println("Value?");
                                int valy5 = console.readInt();  
                                op1.moveY(valy5);
                                break;
                            case 'B':
                                System.out.println("Value of X?");
                                int valx2 = console.readInt();  
                                System.out.println("Value of Y?");
                                int valy2 = console.readInt();  
                                op1.moveXY(valx2,valy2);
                                break;                              
                            default:
                                System.out.println("Invalid axis. Returning to the main menu.");
                                main(null);
                        }       
                        break;
                    case 3:
                        System.out.println("X or Y?");
                        char twoc = console.readChar();
                        switch(twoc){
                            case 'X':
                                System.out.println("Value?");
                                int valx3 = console.readInt();  
                                op1.moveX(valx3);
                                break;
                            case 'Y':
                                System.out.println("Value?");
                                int valy3 = console.readInt();  
                                op1.moveY(valy3);
                                break;
                            case 'B':
                                System.out.println("Value of X?");
                                int valx6 = console.readInt();  
                                System.out.println("Value of Y?");
                                int valy6 = console.readInt();  
                                op1.moveXY(valx6,valy6);
                                break;
                            default:
                                System.out.println("Invalid axis. Returning to the main menu.");
                                main(null);     
                        }
                        break;
                    default:
                        System.out.println("Invalid pair number. Returning to main menu.");
                        main(null);
                    }
                main(null);     
            case 'D':
                System.out.print("Type the ordered pair's number: ");
                int oned = console.readInt();
                switch(oned){
                    case 1:
                        op1.toString();
                        break;
                    case 2:
                        op2.toString();
                        break;
                    case 3:
                        op3.toString();
                        break;
                    default:
                        System.out.println("Invalid pair number. Returning to main menu.");
                        main(null);
                    }
                main(null);
            case 'E':
                System.out.print("Type the ordered pair's number: ");
                int onee = console.readInt();
                switch(onee){
                    case 1:
                        op1.printOP();
                        break;
                    case 2:
                        op2.printOP();
                        break;
                    case 3:
                        op3.printOP();
                        break;
                    default:
                        System.out.println("Invalid pair number. Returning to main menu.");
                        main(null);
                    }
                main(null);
            case 'F':
                System.out.print("Type the first ordered pair's number: ");
                int onef = console.readInt();
                System.out.print("\nType the second ordered pair's number: ");
                int oneg = console.readInt();
                switch(onef){
                    case 1:
                        switch(oneg){
                            case 2:
                                op1.distance(op2);
                                op1.midpoint(op2);
                                break;
                            case 3:
                                op1.distance(op3);
                                op1.midpoint(op3);
                                break;                              
                            default:
                                System.out.println("Invalid pair number. Returning to main menu.");
                                main(null);                                 
                        }
                    case 2:
                        switch(oneg){
                            case 1:
                                op2.distance(op1);
                                op2.midpoint(op1);
                                break;
                            case 3:
                                op2.distance(op3);
                                op2.midpoint(op3);
                                break;
                            default:        
                                System.out.println("Invalid pair number. Returning to main menu.");
                                main(null);                                     
                        }
                    case 3: 
                        switch(oneg){
                            case 1:
                                op3.distance(op1);
                                op3.midpoint(op1);
                                break;
                            case 2:
                                op3.distance(op2);
                                op3.midpoint(op2);
                                break;
                            default:        
                                System.out.println("Invalid pair number. Returning to main menu.");
                                main(null);             
                        }
                    default:    
                        System.out.println("Invalid pair number. Returning to main menu.");
                        main(null);     
                    }
                main(null);
            default:
                System.out.println("Invalid option. Returning to main menu.");
                main(null);                                                                                                     
        }                           
    }
}

这是用于调试目的的 EasyReader 类。它不是我的,但它简化了字符串、整数和字符的读取:

public class EasyReader
{
  protected String myFileName;
  protected BufferedReader myInFile;
  protected int myErrorFlags = 0;
  protected static final int OPENERROR = 0x0001;
  protected static final int CLOSEERROR = 0x0002;
  protected static final int READERROR = 0x0004;
  protected static final int EOF = 0x0100;

  /**
   *  Constructor.  Prepares console (System.in) for reading
   */
  public EasyReader()
  {
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
                            new InputStreamReader(System.in), 128);
  }

  /**
   *  Constructor.  opens a file for reading
   *  @param fileName the name or pathname of the file
   */
  public EasyReader(String fileName)
  {
    myFileName = fileName;
    myErrorFlags = 0;
    try
    {
      myInFile = new BufferedReader(new FileReader(fileName), 1024);
    }
    catch (FileNotFoundException e)
    {
      myErrorFlags |= OPENERROR;
      myFileName = null;
    }
  }

  /**
   *  Closes the file
   */
  public void close()
  {
    if (myFileName == null)
      return;
    try
    {
      myInFile.close();
    }
    catch (IOException e)
    {
      System.err.println("Error closing " + myFileName + "\n");
      myErrorFlags |= CLOSEERROR;
    }
  }

  /**
   *  Checks the status of the file
   *  @return true if en error occurred opening or reading the file,
   *  false otherwise
   */
  public boolean bad()
  {
    return myErrorFlags != 0;
  }

  /**
   *  Checks the EOF status of the file
   *  @return true if EOF was encountered in the previous read
   *  operation, false otherwise
   */
  public boolean eof()
  {
    return (myErrorFlags & EOF) != 0;
  }

  private boolean ready() throws IOException
  {
    return myFileName == null || myInFile.ready();
  }

  /**
   *  Reads the next character from a file (any character including
   *  a space or a newline character).
   *  @return character read or <code>null</code> character
   *  (Unicode 0) if trying to read beyond the EOF
   */
  public char readChar()
  {
    char ch = '\u0000';

    try
    {
      if (ready())
      {
         ch = (char)myInFile.read();
      }
    }
    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    if (ch == '\u0000')
      myErrorFlags |= EOF;

    return ch;
  }

  /**
   *  Reads from the current position in the file up to and including
   *  the next newline character.  The newline character is thrown away
   *  @return the read string (excluding the newline character) or
   *  null if trying to read beyond the EOF
   */
  public String readLine()
  {
    String s = null;

    try
    {
      s = myInFile.readLine();
    }
    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    if (s == null)
      myErrorFlags |= EOF;
    return s;
  }

  /**
   *  Skips whitespace and reads the next word (a string of consecutive
   *  non-whitespace characters (up to but excluding the next space,
   *  newline, etc.)
   *  @return the read string or null if trying to read beyond the EOF
   */
  public String readWord()
  {
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;

    try
    {
      while (ready() && Character.isWhitespace(ch))
        ch = (char)myInFile.read();
      while (ready() && !Character.isWhitespace(ch))
      {
        count++;
        buffer.append(ch);
        myInFile.mark(1);
        ch = (char)myInFile.read();
      };

      if (count > 0)
      {
        myInFile.reset();
        s = buffer.toString();
      }
      else
      {
        myErrorFlags |= EOF;
      }
    }

    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    return s;
  }

  /**
   *  Reads the next integer (without validating its format)
   *  @return the integer read or 0 if trying to read beyond the EOF
   */
  public int readInt()
  {
    String s = readWord();
    if (s != null)
      return Integer.parseInt(s);
    else
      return 0;
  }

  /**
   *  Reads the next double (without validating its format)
   *  @return the number read or 0 if trying to read beyond the EOF
   */
  public double readDouble()
  {
    String s = readWord();
    if (s != null)
      return Double.parseDouble(s);
      // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
      return 0.0;
  }
}

最后,这是我的 OrderedPair 类:

public class OrderedPair {
    int a,b;
    String q = "";
    public int getX() {
        System.out.println("X is "+a);
        return a;
    }
    public int getY() {
        System.out.println("Y is "+b);
        return b;       
    }
    public void setX(int x) {
        a = x;
        System.out.println("X has been set to "+a);     
        if (b != 0) setQ();
        else;   
    }
    public void setY(int y) {
        b = y;
        System.out.println("Y has been set to "+b);     
        if (a != 0) setQ();
        else;   
    }        
    public String toString() {
        String msg = ("("+a+","+b+") Q"+q);
        System.out.println("Values have been converted into string.");
        return msg;     
    }
    public int moveX(int amt) {
        a+=amt;
        System.out.println("X has been moved "+amt+" units.");      
        if ((b != 0) && (a != 0)) setQ();
        else;   
        return a;   
    }
    public int moveY(int amt) {
        b+=amt;
        System.out.println("Y has been moved "+amt+" units.");  
        if ((b != 0) && (a != 0)) setQ();
        else;
        return b;           
    }
    public void moveXY(int amt1, int amt2){
        a+=amt1;
        b+=amt2;
        System.out.println("X has been moved "+amt1+" units.");
        System.out.println("Y has been moved "+amt2+" units.");
        if ((b != 0) && (a != 0)) setQ();
        else;
    }
    public void distance(OrderedPair other) {
        double d = Math.sqrt(Math.pow(other.b-this.b,2)+Math.pow(other.a-this.a,2));
        System.out.println("The distance between the two points is: "+d);
    }
    public void midpoint(OrderedPair other) {
        int x3 = (this.a+other.a)/2;
        int y3 = (this.b+other.b)/2;
        System.out.println("The midpoint is at: ("+x3+","+y3+")");          
    }
    public void printOP() {
        if (q!= "") System.out.println("("+a+","+b+") Q"+q);
        else System.out.println("Q has not been set.");
    } 
    private void setQ() {
        if ((a!=0)&&(b!=0)){
            if (a > 0){
                if (b > 0) q = "I";     
                else q = "IV";
            }
            else {
                if (b > 0) q = "II";
                else q = "III";
            }       
            System.out.println("The quadrant has been set.");
        }
        else System.out.println("X and/or Y are zero, please assign the variables a nonzero value.");   
    }            
}
4

2 回答 2

1

console.skipLine();在读取字符之前尝试添加。正如评论员所指出的,当您使用 readChar 时,您可能正在阅读 endOfLine 字符(但如果您发布了包含类定义的完整、可编译的代码,调试起来会更容易。)

于 2013-10-31T13:38:15.447 回答
0

它正在读取空白区域。如果你插入

console.readLine();

这会读取不需要的内容,然后您可以根据需要使用您的代码。为案例 1 修改您的代码如下(对于案例 2 和 3 类似),它可以工作:

case 1:
    System.out.print("\nX or Y?");
    console.readLine();
    char twoa = console.readChar();

我通过插入线发现了这一点

System.out.println("twoa: "+twoa);  

在代码的正确位置(见下文)

case 1:
    System.out.print("\nX or Y?");
    char twoa = console.readChar();
    System.out.println("twoa: "+twoa);

然后运行程序的结果如下:

Ordered Pairs 1, 2, and 3 are set to (0,0).
What would you like to do?
Type A to display values, B for setting values, C for moving values,
D for string conversion, E for printing, and F for other calculations.
B
Type the ordered pair's number: 1

X or Y?

twoa: 


Invalid axis. Returning to the main menu.
Ordered Pairs 1, 2, and 3 are set to (0,0).
What would you like to do?
Type A to display values, B for setting values, C for moving values,
D for string conversion, E for printing, and F for other calculations.

注意线

twoa: 

这表明 console.readChar() 读取空白,然后将其分配给行中的字符“twoa”

char twoa = console.readChar();

如果您想了解程序在做什么,插入这样的打印语句会有所帮助。

于 2013-10-31T13:26:08.403 回答