Reputation: 209
I have to retrieve three inputs an integer, a string and a double; here is how I thought i would do [Note:The String containing a space]
record.setAccountNumber(input.nextInt());
record.setName(input.nextLine());
record.setBalance(input.nextDouble());
I tried to replace input.nextLine() in
record.setName(input.nextLine());
with input input.next(), because of an InputMisMatchException but still the problem is not resolved. the error is thrown because a double value is probably assigned to a new line value[this is what I think not sure] is there a way to retrieve the string containing a space and be able to finish the three inputs I have to enter at the same time. thanks
NOTE: I couldn't find any relating problem to this one Let me just add the whole method within which the error occurs
public void addAccountRecords(){
AccountRecord record = new AccountRecord();
input = new Scanner (System.in);
try {
output = new Formatter("oldmast.txt");
} catch (FileNotFoundException e) {
System.err.println("Error creating or opening the file");
e.printStackTrace();
System.exit(1);
} catch (SecurityException e){
System.err.println("No write access to this file");
e.printStackTrace();
System.exit(1);
}
System.out.println("Enter respectively an account number\n"+
"a name of owner\n"+"the balance");
while ( input.hasNext()){
try{
record.setAccountNumber(input.nextInt());
record.setName(input.nextLine());
record.setBalance(input.nextDouble());
if (record.getBalance() >0){
output.format("%d\t%s\t%,.2f%n",record.getAccountNumber(),
record.getName(),record.getBalance());
record.setCount((record.getCount()+1));
}else
System.err.println("The balance should be greater than zero");
}catch (NoSuchElementException e){
System.err.println("Invalid input, please try again");
e.printStackTrace();
input.nextLine();
}catch (FormatterClosedException e){
System.err.println("Error writing to File");
e.printStackTrace();
return;
}
System.out.println("Enter respectively an account number\n"+
"a name of owner\n"+"the balance\n or End of file marker <ctrl> z");
}//end while
output.close();
input.close();
}//end AddAccountRecords
Upvotes: 0
Views: 1688
Reputation: 328598
nextLine
will read all the remaining data to the end of your string, including the double. You need to use next
instead. I'm not sure why you get an InputMisMatchException
- this works for example:
String s = "123 asd 123.2";
Scanner input = new Scanner(s);
System.out.println(input.nextInt()); //123
System.out.println(input.next()); //asd
System.out.println(input.nextDouble()); //123.2
So the issue is possibly in your input or somewhere else in your code.
Notes:
Scanner input = new Scanner(System.in);
and enter 123 asd 123.2
I get the same result.Upvotes: 1