Java扫描器无法正常工作

时间:2019-01-03 15:38:49

标签: java

我正在编写一个程序,用于从制表符分隔的输入表中删除该字段之一。并且我需要用户给我他们想要删除的字段的位置。

我想一直询问这个数字,直到它有效为止,所以我写了以下代码(我认为是引起问题的代码):

  boolean validPos = false;
  int pos = -1;
  while(!validPos){
    System.out.print(
    "Please enter the postion of the field you want to delete: ");
    try{
      //index is 1 less than the number so - 1
      pos = ask.nextInt() - 1;
    }catch(InputMismatchException imE){
      System.err.println(imE);
      System.out.println("Please enter a valid positive integer");
    }
    if(pos <= 0){
      System.out.println("Enter number is less than 1");
    }else{
      validPos = true;
    }//ifelse
  }//while

当我询问时输入无效的输入时, 它会不停地打印相同的内容:

$ java DeleteField
Leave empty if you want to manually enter input
Please enter the name of input file: 
Leave empty if you want to show the output here
Please enter the name of the output file: 
Please enter the postion of the field you want to delete: q
java.util.InputMismatchException
Please enter a valid positive integer
Enter number is less than 1
Please enter the postion of the field you want to delete:     java.util.InputMismatchException
Please enter a valid positive integer
Enter number is less than 1
Please enter the postion of the field you want to delete:    java.util.InputMismatchException
Please enter a valid positive integer
Enter number is less than 1
Please enter the postion of the field you want to delete:  java.util.InputMismatchException
Please enter a valid positive integer
Enter number is less than 1
Please enter the postion of the field you want to delete:   java.util.InputMismatchException

....等永远打印... 看起来像代码

pos = ask.nextInt() - 1;  

没有停止并要求输入, 我可以知道发生了什么吗?非常感谢

而且,如果您想查看完整的代码:

//this program input a tab separated table
//and delete one of the field according to input number
//note: if input number is more than integer range it wont work

import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.File;
import java.io.InputStreamReader;
import java.util.InputMismatchException;

public class DeleteField{
  public static void main(String[] args) {
    BufferedReader reader = null;
    PrintWriter writer = null;
    Scanner ask = new Scanner(System.in);
    boolean standardInput = false;
    boolean standardOutput = false;
    File inFile = null;
    File outFile = null;

try{
  boolean validInFile = false;
  while(!validInFile){
    System.out.println("Leave empty if you want to manually enter input");
    System.out.print("Please enter the name of input file: ");
    String inFileString = ask.nextLine();
    inFile = new File(inFileString);
    if(inFileString.equals("")){
      standardInput = validInFile = true;
    }else if(!inFile.exists()){
      System.out.println("This file does not exists, please enter again");
    }else{
      validInFile = true;
    }//ifelse
  }//while

  boolean validOutFile = false;
  while(!validOutFile){
    System.out.println("Leave empty if you want to show the output here");
    System.out.print("Please enter the name of the output file: ");
    String outFileString = ask.nextLine();
    outFile = new File(outFileString);
    if(outFileString.equals("")){
      standardOutput = validOutFile = true;
    }else if(outFile.exists()){
      boolean validAns = false;
      while(!validAns){
        System.out.print("File already exists, override it? (y/n): ");
        String ans = ask.nextLine();
        if(ans.equals("y")){
          validAns = validOutFile = true;
        }else if(ans.equals("n")){
          standardOutput = validAns = true;
        }else{
          System.out.println("Please supply valid answer");
        }//else
      }//while
    }else{
      validOutFile = true;
    }//else
  }//while
  /////////////////////////////////////////////////////////////////
  //The code I think with problem: 
  boolean validPos = false;
  int pos = -1;
  while(!validPos){
    System.out.print(
    "Please enter the postion of the field you want to delete: ");
    try{
      pos = ask.nextInt() - 1;
    }catch(InputMismatchException imE){
      System.err.println(imE);
      System.out.println("Please enter a valid positive integer");
    }
    if(pos <= 0){
      System.out.println("Enter number is less than 1");
    }else{
      validPos = true;
    }//ifelse
  }//while

  /////////////////////////////////////////////////////////////////
  if(standardInput){
    reader = new BufferedReader(new InputStreamReader(System.in));
  }else{
    reader = new BufferedReader(new FileReader(inFile));
  }

  if(!standardOutput){
    writer = new PrintWriter(new FileWriter(outFile));
  }

  String currLine;
  String res = "";//result
  boolean deleted = false;
  final String NLS = System.getProperty("line.separator");
  //read linebyline from input
  //if pos == index then skip
  //else paste each words of the line into result
  while((currLine = reader.readLine()) != null){
    String[] currLineArray = currLine.split("\t");
    for(int index = 0; index < currLineArray.length; index++){
      if(index != pos){
        res += currLineArray[index] + "\t";
      }else{//if we deleted something
        deleted = true;
      }//if
    }//for
    res += NLS;
  }//while

  //output result
  if(standardOutput){
    System.out.println(res);
  }else{
    writer.write(res);
  }
  if(!deleted){
    writer.write("Note: You did not delete any field");
  }//if

}catch(IllegalArgumentException illE){
  System.err.println("Error: " + illE.getMessage());
  System.out.println(
  "Please try again with argument as inFile outFile integer");
// }catch(IOException ioE){
//   System.err.println("Error: " + ioE.getMessage());
}catch(Exception e){
  System.err.println(e);
  System.err.println("Something unforseen happened...");
}finally{
  try{
    if(reader != null) reader.close();
  }catch(IOException ioe){
    System.out.println("Error while closing file");
    System.err.println(ioe);
  }catch(Exception e){
    System.out.println(
          "Something unforeseen happened during closing file");
    System.err.println(e);
  }
  if(writer != null){
    writer.close();
    if(writer.checkError())
      System.err.println("Something went wrong with the output");
  }
}//trycatchfinally
}//main
}//class

1 个答案:

答案 0 :(得分:0)

尝试使用Integer.parseInt(ask.nextLine())代替ask.nextInt()。当您按Enter键时,Scanner.nextInt方法不会读取换行符