java - I am trying to check and see if some files exist. Why won't my program let the user enter a file? -
java - I am trying to check and see if some files exist. Why won't my program let the user enter a file? -
the code compiles, after prompting user file name says invalid input (which should if file name doesn't exist). did close file early? can explain went wrong? in advance help.
import java.util.scanner; import java.io.*; public class file { public static void main(string[] args) throws ioexception { system.out.println ("welcome weekly sales goal program!"); scanner keyboard = new scanner (system.in); int sales_goal; system.out.print ("\nplease come in sales goal (in dollars): "); sales_goal = keyboard.nextint(); system.out.println ("\nplease come in input file name: "); string filename = keyboard.nextline(); file file = new file(filename); scanner in = new scanner(filename); double sum = 0.0; if (file.exists()) { scanner inputfile = new scanner(file); while (inputfile.hasnext()) { double number = inputfile.nextdouble(); sum += sales_goal; } inputfile.close(); system.out.printf ("\nyour total sales week is: $", sum); if (sum >= sales_goal) { system.out.println ("\nyou reached goal!"); } else if (sum < sales_goal) { system.out.println("\nyou did not reach goal :("); } system.out.println ("goodbye!"); } else if (!file.exists()) { system.out.println("invalid input file name. please seek again."); system.exit(0); } } }
there still carriage return/line ffed in stdin stream after phone call nextint
, nextline
calls
sales_goal = keyboard.nextint(); //... string filename = keyboard.nextline();
this causing nextline
homecoming (cause found carriage return/line feed)
add phone call nextline
after nextint
call
sales_goal = keyboard.nextint(); keyboard.nextline(); // consume carriage homecoming //... string filename = keyboard.nextline();
java file-io input logic runtime-error
Comments
Post a Comment