How to pass a NumberFormat object to a method? - java

I'm trying to use a NumberFormat object to display a price. I'm very new to programming, my book isn't very helpful, nor is my teacher. I have a class called Product and a class called MyProduct, which is a subclass of Product. In the Product class there is a method called getPrice() that has no parameters. All it does is return the value for price. My task is to create a method in MyProduct called getPrice(NumberFormat nf) that returns the price, but formatted as currency. In the main method, if I use myproduct.getPrice(); I get the price, but unformatted (I know this is because it's calling getPrice() from Product, not getPrice(NumberFormat nf) from MyProduct. My question is what do I put in as an argument to stop getting a compile time error? I've tried getPrice(nf), getPrice(this), getPrice(price), just about anything I can think of and nothing works. Any help would be greatly appreciated and all relevant lines of code are posted below. Thanks in advance.
Below is the MyProduct class
public class MyProduct extends Product{
public MyProduct()
{
super();
}
NumberFormat nf;
public String getPrice(NumberFormat nf) {
this.nf = NumberFormat.getCurrencyInstance();
String priceFormatted = nf.format(price);
return priceFormatted;
}
And here is ProductApp class
public class ProductApp {
public static void main(String args[]) {
// display a welcome message
System.out.println("Welcome to the Product Viewer");
System.out.println();
// create 1 or more line items
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get input from user
System.out.print("Enter product code: ");
String productCode = sc.nextLine();
// Use a ProductReader object to get the Product object
ProductDB db = new ProductDB();
MyProduct myproduct = db.getProduct(productCode);
// display the output
String message = "\nPRODUCT\n" +
"Code: " + myproduct.getCode() + "\n" +
"Description: " + myproduct.getDescription() + "\n" +
"Price: " + myproduct.getPrice()+ "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
System.out.println("Bye!");
The line I need help with is
"Price: " + myproduct.getPrice()+ "\n";

As you are instantiating nf within your getPrice method then I would not bother passing it. Maybe change the method name to something like getPriceAsString defined as
public String getPriceAsString() {
NumberFormat nf = NumberFormat.getCurrencyInstance(); // keep local
String priceFormatted = nf.format(price);
return priceFormatted;
}
Then you can call it as myProduct.getPriceAsString ()
edit
As per you comment
In main do
"Price: " + myproduct.getPrice(NumberFormat.getCurrencyInstance())+ "\n";
And declare the method as
public String getPrice(NumberFormat nf) {
return nf.format(price);
}
I assume that price is correctly set

Related

Payment and print receipt part of a bus ticket system

I have to do the last part of my project which is the payment and receipt part. I'm still clueless of how to do the payment part, but I did try to do the print receipt part. I'm using Netbeans 8.2. The coding below is my print receipt code, it builds successfully but doesn't bear any output. Maybe it's because I have to compile all the other codes like the seat numbers, date, time and all before this could print? Not sure if the reason was because i left the main part empty but I don't know what to put in there tbh.
I'm a beginner coder btw and still have a long long long way to go. I will try my best to understand your explanations. Thank you in advance.
import java.util.Date;
import java.util.Scanner;
public class BusPaymentDetails {
public static void main(String[] args) {
}
class Printpaymentdetails {
public void Printpaymentdetails () {
Date timenow = new Date();
Scanner ticket = new Scanner(System.in);
System.out.println("Your Bus E-Ticket: ");
String date = ticket.nextLine();
System.out.println("Date: " + timenow.toString());
String deptime = ticket.nextLine();
System.out.println("Time of departure: " + deptime);
String arrtime = ticket.nextLine();
System.out.println("Time of arrival: " + arrtime);
String place = ticket.nextLine();
System.out.println("Trip to: " + place);
String buscompany = ticket.nextLine();
System.out.println("Bus Company: " + buscompany);
int seatnumber = ticket.nextInt();
System.out.println("Seat number: " + seatnumber);
double price = ticket.nextDouble();
System.out.println("Price: " + price);
System.out.println("This ticket is non-refundable.");
System.out.println("Please be courteous and do not smoke. Enjoy your trip.");
}
}
}
When running java code, you're invoking a main method, here it is empty, so nothing is run. You would have to add something to the body of this method:
public static void main(String[] args) {
new Printpaymentdetails();
}

Java how to pass and return string, method?

import java.util.Scanner;
import javax.swing.JOptionPane;
public class StarWars {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String firstName = "";
String lastName = "";
String maidenName = "";
String town = "";
System.out.print("What is your first name? ");
firstName = reader.nextLine();
System.out.print("What is your last name? ");
lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
maidenName = reader.nextLine();
System.out.print("What town were you born? ");
town = reader.nextLine();
String Sfirstname = firstName.substring(0,2);
String Slastname = lastName.substring(0,3);
String SmaidenName = maidenName.substring(0,2);
String Stown = town.substring(0,3);
String Star = Sfirstname + Slastname;
String War = SmaidenName + Stown;
String StarWar = Star + War;
System.out.print("Your Star Wars name is: " + StarWar);
}
public static String StarWar (String Star, String War) {
String name;
name = Star + " " + War;
return War;
}
}
So this is my code about my project. While I'm doing my project I have some problem about the returning method and passing method.
I set up the main method perfectly to print out thing that what I want to see.
The problem is I also have to use passing method and returning method. My teacher want me to do two things with passing/returning method.
Pass all this data to your method, and the method should generate and return the users Star Wars name.
Get the return value of the method, and display it to the screen.
I have no idea what should I do with this problems (took 5 hrs to do everything I learn but wrong..).
Can someone give a hint or teach me what actually my teacher want me to do and How I can do this?
I really need help from you guys.
Additional, if I run a program it should be like this.
first name? user input: Alice last name? user input:Smith mothers maiden name? user input: Mata town were you born? user input: Sacramento
Your Star Wars name is: SmiAl MaSac
There are a few things we can improve here, lets start with the method - the method name looks like a constructor and doesn't perform the logic itself, lets describe what it does and move the logic into the method - we don't need all of those temporary variables (we can use a StringBuilder) like
public static String buildStarWarsName(String firstName, String lastName,
String maidenName, String town)
{
return new StringBuilder(lastName.substring(0, 3)) //
.append(firstName.substring(0, 2)) //
.append(" ") // <-- for the space between first and last
.append(maidenName.substring(0, 2)) //
.append(town.substring(0, 3)) //
.toString();
}
Then you can initialize your variables when you read them and finally call the method
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("What is your first name? ");
String firstName = reader.nextLine();
System.out.print("What is your last name? ");
String lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
String maidenName = reader.nextLine();
System.out.print("What town were you born? ");
String town = reader.nextLine();
System.out.print("Your Star Wars name is: " + //
buildStarWarsName(firstName, lastName, maidenName, town));
}
You should return what you evaluated instead :
return name;
and then call this defined method while you want to read the value.
The changes highlighted in the comments as well:
String StarWar = Star + War; // this would not be required, as handled by your method 'starWarName'
System.out.print("Your Star Wars name is: " + starWarName()); // calling the method defined
}
public static String starWarName (String Star, String War) { //renamed method to break the similarity with other variables
String name;
name = Star + " " + War;
return name; //returning the complete star war name
}
Your method is returning the 'war' parameter. Based on what your trying to do it looks like it should be returning 'name'. That's what the method built.

Java GetstringMethod

The assignment:
Write a program (Greetings) that prompts the user to enter the first name, the last name, and year of birth, then it returns a greetings message
in proper format (see the example below).
Create a method(s) that accept the scanner and a prompt as parameters and return the user input. A separate method should accept the user input results as parameters, format and print the results. No print statement or scanner input should happen inside main(). Here is an example dialogue with the user:
Please enter your first name:
tom
Please enter your last name:
cruise
Please enter your year of birth:
1962
Greetings, T. Cruise! You are about 53 years old.
I finished the code, but right now it is giving me a compilation error. How do i fix it?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
Scanner newscanner = new Scanner(System.in);
String ask = ("Please enter your first name: ");
String ask2 = ("Please enter your last name: ");
String ask3 = ("Please enter your year of birth: ");
public static String getString(Scanner newscanner, String ask, String ask2, String ask3){
System.out.println(ask);
String first = newscanner.next();
String firstletter = first.substring(0,1).toUpperCase() ;
return firstletter;
System.out.println(ask2);
String second = newscanner.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
String lastname = y.substring(0,1).toUpperCase();
return lastname;
System.out.println(ask3);
int third = newscanner.nextInt();
int age = (2015 - third);
return age
System.out.println("Greetings, "+ firstletter + ". " + lastname+"!" +" You are about " + age + " years old");
}
}
}
Hard to read, but I think you actually have the getString() method inside your main() method - it needs to be after it, and only be called from inside main(), not defined there.

Get the Class Name of a Field from reflection

Im going round in circles on this.
I have a class Person, eg
public class Person {
String name = "";
}
Now, I would like to introspect this class instance & figure out what Class is name declared as.
So, name = String or java.lang.String
This is my Code:
'this' is an instance of Person.
try {
String className = this.getClass().getName();
Class cls = Class.forName(className);
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
int mod = fld.getModifiers();
System.out.println("1. " + fld.toGenericString());
System.out.println("2. " + fld.getName());
System.out.println("3. " + fld.getGenericType() + "]");
Object oj = fld.getType();
// Says that 4: class java.lang.String
System.out.println("4: " + oj.toString());
Class c1 = oj.getClass();
// Should throw Exception
String stype = c1.getDeclaringClass().toString();
System.out.println("5. " + stype);
}
}
catch (Throwable e) {
System.err.println(e);
}
I managed to get to a part that states:
class java.lang.String
but I need it to be "java.lang.String"
Any ideas?
Try.. getType() and then getName()
fld.getType().getName()
Edit:(Aften Green Days' comment) -- Note that
fld.getType().getCanonicalName() will give same output in most cases. The output is different when innerclasses are used. Here is link came from search. Depending what you need to do with classname you may choose one of getName() or getCanonicalName()
System.out.println("3. " + fld.getType().getCanonicalName());
results in:
3. java.lang.String
I guess I solved it,
Should have done this:
String stype = fld.getType().getName();
I got the class name of a field by calling this
f.getDeclaringClass().getSimpleName()

Java Exception printing twice

I know the exception is kind of pointless, but I was trying to learn how to use / create exceptions so I used this. The only problem is for some reason my error message generated by my exception is printing to console twice.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class Project3
{
public static void main(String[] args)
{
try
{
String inputFileName = null;
if (args.length > 0)
inputFileName = args[0];
File inputFile = FileGetter.getFile(
"Please enter the full path of the input file: ", inputFileName);
String outputFileName = null;
if (args.length > 1)
outputFileName = args[1];
File outputFile = FileGetter.getFile(
"Please enter the full path of the output file: ", outputFileName);
Scanner in = new Scanner(inputFile);
PrintStream out = new PrintStream(outputFile);
Person person = null;
// Read records from input file, get an object from the factory,
// output the class to the output file.
while(in.hasNext())
{
String personRecord = in.nextLine();
person = PersonFactory.getPerson(personRecord);
person.display();
person.output(out);
}
} catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
import java.util.Scanner;
class Student extends Person
{
private double gpa;
public Student()
{
super();
gpa = 0.0;
}
public Student(String firstName, String lastName, double gpa)
{
super(firstName, lastName);
this.gpa = gpa;
}
public String toString(){
try{
if (gpa >= 0.0 && gpa <= 4.0){
return super.toString() + "\n\tGPA: " + gpa;
}
else {
throw new InvalidGpaException();
}
}
catch (InvalidGpaException e){
System.out.println(e);
return super.toString() + "\n\tGPA: " + gpa;
}
}
public void display()
{
System.out.println("<<Student>>" + this);
}
#Override
public void input(Scanner in)
{
super.input(in);
if (in.hasNextDouble())
{
this.gpa = in.nextDouble();
}
}
class InvalidGpaException extends Exception {
public InvalidGpaException() {
super("Invalid GPA: " + gpa);
}
}
}
This is my console readout. Not sure what's causing the exception to print twice.
project3.Student$InvalidGpaException: Invalid GPA: -4.0
<< Student>>
Id: 2 Doe, Junior
GPA: -4.0
project3.Student$InvalidGpaException: Invalid GPA: -4.0
edit: The main code is on the top. The input is a file designated by the user. What I shown right here is my console printout, not what is returned to the output file. The output file shows the exact same thing minus the error message. The Error message from the exception (which I know is not necessary) is only printed to the console. I don't see where I'm printing it twice.
My guess is that your Person.output() method has a call to toString() in it, which will print the exception before returning the proper string, which doesn't show up because you're outputting it to out.
E: If you want my deduction, here it is: The first error message and normal message are printed out within the call to display(), as it should be. Immediately after that is the output() call, which by the name I guess is meant to do what display() does, except to a file. However, you forgot that the exception is printed directly to System.out, so it appears in the console, while the string that toString() actually returns is written to the file.
What is your main ? what is your INPUT..
Change your exception to something different.
Where are you printing this data ?
<< Student>>
Id: 2 Doe, Junior
GPA: -4.0
Are you sure you aren't calling person.toString() twice ?
My guess is that you are calling toString somewhere in the code you have not shown to us.
Putting in a Thread.dumpStack(); in the toString implementation should tell you from where.
Try changing this:
System.out.println(e);
return super.toString() + "\n\tGPA: " + gpa;
to
System.out.println(e);
(Or something similar)

Categories