Printwriter output not accepting .printf formatters to file? - java

When outputting to an already established file using the following code:
import java.util.Scanner;
import java.io.*;
public class BarakProductOrder
{
public static void main(String[] args) throws IOException
{
//Establish scanner object
Scanner input = new Scanner (System.in);
//Declare variables
String name, product, street, city, state, zip;
int qty;
double price;
//Collect data
System.out.println("Welcome to Matt's Dog Food Emporium!\n\nWhat is your name?");
name = input.nextLine();
System.out.println("Which product would you like to order today?");
product = input.nextLine();
System.out.println("How many would you like?");
qty = input.nextInt();
price = 4.56*qty;
input.nextLine(); //Must be placed to not skip over "address" line
System.out.println("Enter your street address:");
street = input.nextLine();
System.out.println("Enter the City:");
city = input.nextLine();
System.out.println("Enter the State (ex.: NY):");
state = input.nextLine();
System.out.println("Enter the Zip:");
zip = input.nextLine();
System.out.println("Thank you for your order, " + name);
//Output data to file "BarakOrder.txt"
PrintWriter outputFile = new PrintWriter("C:\\Users\\fbara\\Desktop\\CISS 110\\BarakOrder.txt");
outputFile.println("Order Number: 001");
outputFile.println("Product: " + product);
outputFile.println("Quantity: " + qty);
outputFile.printf("Price = 4.56*" + qty + " = $" + "%.2f" + price);
outputFile.println("Customer Contact Info: " + name);
outputFile.println("Address: " + street);
outputFile.println(city + ", " + state + " " + zip);
//Close scanner and file object
input.close();
outputFile.close();
System.out.println("Data has been written.");
}
}
Using the "%.2f" modifier at line 45 gives me the following error message:
java.util.MissingFormatArgumentException: Format specifier '%.2f' at
java.util.Formatter.format(Unknown Source) at
java.io.PrintWriter.format(Unknown Source) at
java.io.PrintWriter.printf(Unknown Source) at
BarakProductOrder.main(BarakProductOrder.java:45) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
Am I using the wrong modifier at the outputFile.printf? Or wrong ".print()" line?

That's not how printf works; you give it a format then the things to print.
You're not passing anything to format with the %.2f, you're trying to add it. The docs provide info on how to use it (and there are many examples in the world).
Roughly:
outputFile.printf("Price = 4.56*" + qty + " = $" + "%.2f", price);
Although I'm not sure why you wouldn't do the same formatting for qty.

Related

Can i take userinput in a method java class?

public static void userinput() {
System.out.print("Enter your name : ");
Scanner d = new Scanner(System.in);
String username = d.next();
System.out.print("\nEnter your Age : ");
Scanner a = new Scanner(System.in);
int Age = a.nextInt();
System.out.print("\nEnter your roll number : ");
Scanner b = new Scanner(System.in);
int rollno = b.nextInt();
System.out.print("\nEnter your city : ");
Scanner c = new Scanner(System.in);
String city = c.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
return (0);
}
Is this the correct way to take input from a user in the method?
Here is the corrected version :
public static void userinput() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name : ");
String username = sanner.nextLine();//as next() reads only a word
System.out.print("\nEnter your Age : ");
int age = Integer.parseInt(scanner.nextLine());//as nextInt() does not read the \n which may cause next string inputs to be null
System.out.print("\nEnter your roll number : ");
int rollno = Integer.parseInt(scanner.nextLine());
System.out.print("\nEnter your city : ");
String city = scanner.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
//a void function doesn't compulsorily need a return statement
}
Also only one Scanner is enough!

Displaying an output decimal with 2 places in java

I'm trying to find out why the %.2f declaration when outputting a decimal isn't working in my code, I've checked other similar questions but I can't seem to locate the issue in the specific logic error I'm receiving. When I go to compile my program it compiles fine, I go to run it and everything outputs fine until I get to the final cost where I'm trying to only display that decimal value with 2 decimal places.
I get an exception in thread "main"
Java.util.illegalformatconversionexception f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)
Here is my code:
import java.util.Scanner;
public class Cars
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int carYear, currentYear, carAge;
double costOfCar, salesTaxRate;
double totalCost;
String carModel;
System.out.println("Please enter your favorite car model.");
carModel = input.nextLine();
System.out.println("Please enter the year of the car");
carYear = input.nextInt();
System.out.println("Please enter the current year.");
currentYear = input.nextInt();
carAge = currentYear - carYear;
System.out.println("How much does the car cost?");
costOfCar = input.nextDouble();
System.out.println("What is the sales tax rate?");
salesTaxRate = input.nextDouble();
totalCost = (costOfCar + (costOfCar * salesTaxRate));
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars.");
}
}
I'm not exactly sure what's causing the issue.
Try:
System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);
Or the more readable:
System.out.printf("The model of your favorite car is %s," +
" the car is %d years old," +
" the total of the car is %.2f dollars.",
carModel, carAge, totalCost);
It's because %.2f is replaced with the entire second argument in that method call. The problem is that by specifying f in %.2f, you are saying that the second argument is a float or double. The second argument in this case is totalCost + " " + " dollars." which evaluates to a string.
To fix this problem, you need to make the second argument be a float or double. This can be achieved by moving + " " + " dollars." from the end of the second argument to the end of the first argument, like so:
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f" + " " + " dollars.",totalCost);
You can also remove many of the unnecessary concatenations from that line, resulting in this:
System.out.printf("The model of your favorite car is" + carModel + ", the car is " + carAge + " years old, the total of the car is %.2f dollars.", totalCost);
The variable has to go as a parameter to the System.out.printf() function. The "%.2f" will be replaced by the double value that is passed as the second parameter.
For Example:
System.out.printf("The value is %.2f", value);
The same thing is true for other variable types and for multiple variables,
String str = "The value is: ";
double value = .568;
System.out.printf("%s %.2f", str, value);
This will output: "The value is: .57"

Java scanner.nextInt throws NoSuchElement second time around

So I have a loop that runs which takes input from the user via a scanner and System.in. The scanner is just called s. I use s.nextInt to get an int for my switch, where I have a lot of cases, so the user has some choices. Now in one of those cases, I use another scanner, and when I close it and the function terminates (which takes me back to my while loop) I want to take a new int from the user, to choose the next thing they want to do. This time around it throws an NoSuchElementException. I used the "I'm before" and "I'm after" and the userrequest = s.nextInt is where I get the error. Any ideas? My function is way too long to post, but it doesn't really do anything that should interfere, except open a new scanner, but I have other functions which does that, but doesn't break it.
while (on) {
System.out.println("What may I do for you today? ");
System.out.println("I'm before");
int userrequest = s.nextInt();
System.out.println("I'm after");
switch (userrequest) {
case 1:
System.out.println("");........
EDIT: Okay, I edited out some non important stuff from the function. This is the function it runs, before returning to my while loop:
public static void buysystem(Connection con, Scanner sysbuy) {
System.out.println("What system do you want to buy?");
String sysreq = sysbuy.next().toUpperCase();
try {
Statement st = con.createStatement();
String query = "SQL";
ResultSet rs = st.executeQuery(query);
rs.next();
String nome = rs.getString("noob");
int price = rs.getInt("cpuprice") + rs.getInt("ramprice") + rs.getInt("mainboardprice") + rs.getInt("casesprice") + rs.getInt("gfxprice");
System.out.println("How many systems do you want to buy?");
int sysamount = sysbuy.nextInt();
//NEED TO MAKE CHECK AMOUNT FUNCTION
int realprice;
if (sysamount>10){
realprice = (price*130/100)-((price*130/100*120/100)-(price*130/100));
System.out.println("You want to buy " + sysamount + " of the system: " + sysreq + " for the price of " + realprice + "?");
System.out.println("Yes/No?");
String yesno = sysbuy.next();
if (yesno.toUpperCase().equals("YES")){
System.out.println("You just bought " + sysamount + " of the system " + sysreq + " for the price of " + realprice);
//UPDATE DB
}
}
else{
realprice = (price*130/100)-((price*130/100*(sysamount*2+100-2)/100)-(price*130/100));
System.out.println("You want to buy " + sysamount + " of the system: " + sysreq + " for the price of " + realprice + "?");
System.out.println("Yes/No?");
String yesno = sysbuy.next();
if (yesno.toUpperCase().equals("YES")){
System.out.println("You just bought " + sysamount + " of the system " + sysreq + " for the price of " + realprice);
//UPDATE DB
}
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Print me");
}
I get this error now:
You just bought 1 of the system SERVER1 for the price of 7540
Print me
What may I do for you today?
I'm before
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at DBtest.requestHandler(DBtest.java:43)
at DBtest.main(DBtest.java:24)
Do not create multiple Scanners, instead use one scanner and use it inside your function or pass it to it if it is out of scope.
You created multiple Scanners, which you should not do, but also closed the second scanner. When you closed that scanner you closed the input stream which both scanners are using (the System's inputstream). This is what caused your crash.

Java string not showing when run [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I can't seem to figure out why the string college doesn't show when I run this. There are no errors when I compile it. What am I doing wrong? Everything else is working. It's probably an easy fix, but I'm new and just starting to learn Java.
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String college;
String profession;
String animal;
String petname;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}
Call keyboard.nextLine() after age = keyboard.nextInt();.
Currently int value is read as age and college = keyboard.nextLine(); reads the remainder of the line which container your int, which is empty. So the correct form should be:
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
Other possible solution to avoid the extra call to nextLine() is reading the whole line as a String and then parsing that String to an integer, for example:
age = Integer.parseInt(keyboard.nextLine());
Put keyboard.nextLine() after this line:
int age=keyboard.nextInt();
This is a common problem that usually happens when you use nextLine() method after nextInt() method of Scanner class.
What actually happens is that when the user enters an integer at int age = keyboard.nextInt();, the scanner will take the digits only and leave the new-line character \n. So you need to do a trick by calling keyboard.nextLine(); just to discard that new-line character and then you can call String college = keyboard.nextLine(); without any problem.
this is taken from Reading Strings next() and nextLine() Java
The problem with your code is using nextLine() after nextInt() & you have an additional nextLine()
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine(); --> this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
What you should do is :
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine(); -->add this line
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// keyboard.nextLine(); --> remove this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
A better way of doing it would be : (read about Integer.pasrseInt(String))
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String profession;
String animal;
String petname;
String college;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println(college);
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}

java.util.InputMismatchException error

Hey everyone I'am working on a project and am having a little trouble I am receiving a java.util.InputMismatchException any help would be greatly appreciated. I am really new to programming in java so forgive me if I've made a obvious dumb mistake. The object of the program is to read a file acquire the first three lines to use for 6 different variables(three integers and three strings) then read the rest of the file, format it,and do some math then put it into a new file. The file I am taking data from is formatted as follows.
Court 50
Box 10
Club 25
Rascal Conway 10 Box
Loretta Barrett 3 Court
Loras Tyrell 5 Club
Margaery Tyrell 8 Box.
Here is the code:
public class ProjectTicket {
public static void main(String[] args) throws IOException {
/////////////////////// amount of tickets person would buy
int amount;
/////////////////////// the tickets prices
int tprice1 = 0;
int tprice2 = 0;
int tprice3 = 0;
//////////////////////the ticket types
String ticket1 = null;
String ticket2 = null;
String ticket3 = null;
////////////////////// the total price
int price = 0;
////////////////////// customers name
String firstName;
String lastName;
////////////////////// name of seat type
String seat;
PrintWriter outputFile = new PrintWriter("portland2out.txt");
File file = new File("portlandvip2.txt");
Scanner inputFile = new Scanner(file);
////////////////////// getting ticket name and ticket price
for (int i = 0; i < 2; i++) {
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
ticket2 = inputFile.next();
tprice2 = inputFile.nextInt();
ticket3 = inputFile.next();
tprice3 = inputFile.nextInt();
outputFile.println(ticket1 + " " + "$" + tprice1);
outputFile.println(ticket2 + " " + "$" + tprice2);
outputFile.println(ticket3 + " " + "$" + tprice3);
}
////////////////////// getting customer name,number of tickets, type of ticket
while (inputFile.hasNext()) {
firstName = inputFile.next();
lastName = inputFile.next();
amount = inputFile.nextInt();
seat = inputFile.next();
////////////////////////////////// doing math for final billing.
if (seat.equals(ticket1))
price = tprice1 * amount;
else if (seat.equals(ticket2))
price = tprice2 * amount;
else if (seat.equals(ticket3))
price = tprice3 * amount;
///////////////////////////////// printing in format to file
outputFile.printf("%-10s%-10s$%,.2f\n", firstName, lastName, price);
}
inputFile.close();
}
}
Here is the error:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at BlancovichProject2.main(BlancovichProject2.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I'am not to sure what the problem can be. I've been looking around and it seems that type of error is given when the retrieved information is not exactly what it was looking for. Thanks again in advance for any help!
You are trying to use
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
on data which look like Rascal Conway 10 Box so you are trying to read Conway as integer which throws InputMismatchException.
It works but you just need to iterate only once or take off the forloop
change:
for (int i = 0; i < 2; i++) {
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
ticket2 = inputFile.next();
tprice2 = inputFile.nextInt();
ticket3 = inputFile.next();
tprice3 = inputFile.nextInt();
outputFile.println(ticket1 + " " + "$" + tprice1);
outputFile.println(ticket2 + " " + "$" + tprice2);
outputFile.println(ticket3 + " " + "$" + tprice3);
}
to this:
ticket1 = inputFile.next();
tprice1 = inputFile.nextInt();
ticket2 = inputFile.next();
tprice2 = inputFile.nextInt();
ticket3 = inputFile.next();
tprice3 = inputFile.nextInt();
outputFile.println(ticket1 + " " + "$" + tprice1);
outputFile.println(ticket2 + " " + "$" + tprice2);
outputFile.println(ticket3 + " " + "$" + tprice3);
Also you have a wrong formating for the printf.To verify the results comment out the
//outputFile.printf("%-10s%-10s$%,.2f\n", firstName, lastName, price);
and add this to verify that you have the right output:
System.out.printf("%-10s%-10s$%,d\n", firstName, lastName, price);
then if they are right... you can output it to your file..

Categories