Java Programming Help

I'm new to Java programming, and I have a pretty basic question. I'm writing a simple loan calculator, and I need to know how to format the output of my variables to two decimal places. I've been doing this for about a week, so be nice, please.
Thanks in advance,
Wayne

NumberFormat nf = NumberFormat.getCurrencyInstance();
double cash = 123.45;
System.out.println(nf.format(cash));
Your First Cup of Java
Essentials, Part 1, Lesson 1: Compiling & Running a Simple Program
The Java Tutorial - A practical guide for programmers
New to Java Center
How To Think Like A Computer Scientist
Introduction to Computer Science using Java
The Java Developers Almanac 1.4
JavaRanch: a friendly place for Java greenhorns
jGuru
Object-Oriented Programming Concepts
Object-oriented language basics
Don't Fear the OOP
Books:
Bert Bates and Kathy Sierra's Head First Java
Bruce Eckel's Thinking in Java (Free online)
Joshua Bloch's Effective Java
Java Design: Building Better Apps and Applets (2nd Edition)

Similar Messages

  • Basic Java Program help needed urgently.

    I have posted the instructions to my project assignment on here that is due tomorrow. I have spent an extremely large amount of time trying to get the basics of programming and am having some difficulty off of the bat. Someone who has more experience with this and could walk me through the steps is what I am hoping for. Any Help however will be greatly appreciated. I am putting in a lot of effort, but I am not getting the results I need. Thank you for the consideration of assisting me with my issues. If you have any questions please feel free to ask. I would love to open up a dialogue.
    CIS 120
    Mathematical Operators
    Project-1
    Max possible pts 100
    Write a program “MathOperators” that reads two integers, displays user’s name, sum, product,
    difference, quotients and modulus of the two numbers.
    1. Create a header for your project as follows:
    * Prgrammer: Your Name (1 pt) *
    * Class: CIS 120 (1 pt) *
    * Section: (1 pt) *
    * Instructor: (1 pt) *
    * Program Name: Mathematical Operators (1 pt) *
    * Description: This java program will ask the user to enter two integers and *
    display sum, product, difference, quotients and modulus of the two numbers
    * (5 pts) *
    2. Display a friendly message e.g. Good Morning!! (2 pts)
    3. Explain your program to the user e.g. This java program can add, subtract, multiply,
    divide and calculate remainder of any two integer numbers entered by you. Let’s get
    started…. (5 pts)
    4. Prompt the user- Please enter your first name, store the value entered by user in a
    string variable name. Use input.next() instead of input.nextLine(). (8 pts)
    5. Prompt the user- name, enter first integer number , store the value entered by user in
    an integer variable num1.(5 pts)
    6. Prompt the user- name, enter second integer number , store the value entered by user in
    an integer variable num2.(5 pts)
    7. Display the numbers entered by the user as: name has entered the numbers num1and
    num2.(5 pts)
    8. Calculate sum, product, difference, quotients and modulus of the two numbers. ( 30 pts)
    9. Display sum, product, difference, quotients and modulus of the two numbers. ( 10 pts)
    10. Terminate your program with a friendly message like- Thanks for using my program,
    have a nice day!!(2 pts)

    Nice try. You have not demonstrated that you've at least TRIED to do something. No one is going to do your homework for you. Your "urgency" is yours alone.

  • ONe more time - Java program Help -

    HI. I need to know what the code would be to print the Nodes. I simply can't figure it out.I'm not allowed to change anything or add anything. I just have to fill in the methods and make the ListSort work as it is. I can't figure out how to print each node so the out put looks like this:
    *12 2 10 5*
    *12 2 10 5*
    Eventually I have to have to program sort them but I can probably figure it out if I can just print them. ANy help? I have posted before but with no luck. GOod advice its just i can't find out the code to write in the printLIst and insertNodeAtBeginning that will get the nodes to print.
    * implements various methods related to manipulating a singly-linked list
    public class LinkedList
    private Node firstNode = null;
    * prints all the elements of the list in order on one line, separated by s
    paces
    * puts a line of dashes above and below the printed list
    public void printList()
    System.out.println("----------");
    Node currentNode = firstNode;
    System.out.println("----------");
    * inserts a new node into the list at the beginning of the list
    public void insertNodeAtBeginning(Node newNode)
    // quick error checking
    if (newNode == null)
    return;
    // TODO: insert newNode into the beginning of the list
    * inserts the newNode into the list just before the first node that
    * has a larger value than newNode; if the list is empty or if newNode
    * has the smallest value, then newNode will be inserted at the beginning
    * of the list; if newNode has the largest value in the list, then it
    * should be inserted at the end of the list
    public void insertNodeInAscendingOrder(Node newNode)
    // quick error checking
    if (newNode == null)
    return;
    // TODO: insert newNode in the right place in the list
    * remove the first node in the list and return it. if there are no
    * elements in the list, then return null
    public Node removeFirstNode()
    return firstNode;// TODO: remove the first element in the list and return
    it, or
    // return null if the list is empty
    * use recursion to sort the given list in ascending order
    public static void recursiveListSort(LinkedList list)
    // quick error checking
    if (list == null)
    return;
    // TODO: use recursion to sort the list
    Next file:
    public class ListSort {
    * @param args
    public static void main(String[] args) {
    LinkedList list = new LinkedList();
    list.insertNodeAtBeginning(new Node(5));
    list.insertNodeAtBeginning(new Node(10));
    list.insertNodeAtBeginning(new Node(2));
    list.insertNodeAtBeginning(new Node(12));
    list.printList();
    LinkedList.recursiveListSort(list);
    list.printList();
    Next File:
    public class Node
    private int value;
    public Node next = null;
    public Node(int newValue)
    value = newValue;
    public int getValue()
    return value;
    }

    You did receive good advice previously and would do well to study it and search the forum as well. One other thing to help you get advice is to post your code so it is readable without hurting the eyes. So please use code tags so that your code will be well-formatted and readable. To do this, place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
    [code]
    // your code block goes here.
    [/code]

  • Need help in creating a java program

    Hi everyone.
    I'd like to say before i start about my problem, that i've only begun learning java and my teacher hasn't explained anything at all. He only showed us by doing it himself and then showing us the final version. I've searched a little on how to program but i get little success in finding a good tutorial.
    I need help creating a program which has been assigned to me due in a few days in which i can't contact my teacher for help.
    I need to write a java program which inputs 3 items. The number of kilometres you drove, the number of litres of gas you used and the price you paid for the gas. Then, the program must calculate the number of litres used per 100km driven, which is litres divided by kilometres times 100, how much it costs to drive 100km, which is the result (a) times the price per litre and the number of miles per American gallon of gas ( one American gallon = 3.785 litres, and one mile = 1.609 km.
    The program has to output my name, the inputs given, the results computed and a message saying "Program Complete".
    To give you what i've done to begin with, from what i understood, is:
    import javax.swing.JOptionPane;
    public class prog1
         public static void main(String args[])
              final double americanGallon = 3.785;
              final double mile = 1.609;
              kilometresDriven,
              gasUsed;
              priceOfLiterGas;
              System.out.println("My Name");
              System.out.println("Number of kilometres driven:");
              kilometresDriven = JOptionPane.showInputDialog ("Kilometres Driven");
              System.out.println("Number of Litres of gas used:");
              gasUsed = JOptionPane.showInputDialog ("Litres of gas used");
              System.out.println("Price of a liter of gas:");
              priceOfLiterGas = JoptionPane.showInputDialog("Price per liter");
    Up to now, that's all i've got. i know i'm wrong, but i'm not sure how to do this. Could someone give me an outline of what this program is suppose to look like?
    Thanks in advance.

    Here's an update on my program. I've worked on certain details and would need your comments whether it contains errors. I'd also want to know if it would work or not because i don't know how to check it on my computer.
    Here's the update:
    import javax.swing.JOptionPane;
    public class Prog1
    public static void main(String args[])
    String name;
    double kmDriven;
    double litresUsed;
    double pricePaidForGas;
    double priceOfALiter;
    name = JOptionPane.showInputDialog("Name");
    input = JOptionPane.showInputDialog("Number of km driven");
    kmDriven = Double.parseDouble (input);
    input = JOptionPane.showInputDialog("Number of litres of gas used");
    litresUsed = Double.parseDouble (input);
    input = JOptionPane.showInputDialog("Price paid for gas");
    pricePaidForGas = Double.parseDouble (input);
    input = JOptionPane.showInputDialog("Price of a litre of gas");
    priceOfALiter = Double.parseDouble (input);
    a = (litresUsed/kmDriven)*100;
    b = ((litresUsed/kmDriven)*100)*priceOfALiter);
    c = (kmDriven/1.609)
    System.out.println("Name:" + name);
    System.out.println("Number of litres used per 100km:" + a);
    System.out.println("Cost of driving 100km" + b);
    System.out.println("Number of miles per American Gallon of Gas:" + c);
    System.out.println("Program Complete");
    System.exit(0);
    Comments please.
    Thanks in advance

  • I did write a simple java program but it is not working please help me.....

    This is the program I wrote LineRect just to draw a line a rectangle etc...... Y it is not working How can i used the same program to run without using applet that is by using awt and swing.........Pls Help me.............
    import java.awt.*;
    import java.io.*;
    public class LineRect
    {public void paint(Graphics g)
         {g.drawLine(10,10, 50,50);
         g.drawRect(10, 60, 40,30);
         g.fillRect(60,10,30,80);
         g.drawRoundRect(10,100,80,50,10,10);
         g.fillRoundRect(20,110,60,30,5,5);
         g.drawLine(100,10,230,140);
         g.drawLine(100,140,230,10);
    <APPLET
    CODE =LineRect.class
    WIDTH=250
    HEIGHT=200>
    </APPLET>

    There are many significant errors here for instance you are using a class file as if it were an applet yet you do not subclass applet. Your code has no init method (if it is to be an applet). Your best bet is to go through the tutorials one step at a time. One thing to consider is to subclass a JPanel and draw on the jpanel overriding the paintComponent method. This can then be added to a JFrame or a JApplet's contentPane and would allow the same graphics in both. But again, please study the tutorials on all of this, otherwise you will be doing hit-or-miss programming, and that is no way to learn.
    Much luck!
    Addendum: Also, if you are just beginning in Java programming, I suggest you start with the basics and not with Swing / AWT / graphics programming. Otherwise you will just end up bruised and disappointed. You have to learn to walk before you can run.
    Edited by: Encephalopathic on Dec 26, 2007 5:09 AM

  • Challange for you, help for me! java program

    I am a beginning java student and desparately (again) in help of someone who will check my java program. See below what they want from me, and try to make a program of it that works in all the ways that are asked. Thank you for helping me, i am running out of time.
    Prem Pradeep
    [email protected]
    Catalogue Manager II
    Specification:
    1.     Develop an object to represent to encapsulate an item in a catalogue. Each CatalogueItem has three pieces of information: an alphanumeric catalogue code, a name, and a price (in dollars and cents), that excludes sales tax. The object should also be able to report the price, inclusive of a 15% sales tax, and the taxed component of the price.
    2.     Data input will come from a text file, whose name is passed in as the first command-line argument to the program. This data file may include up to 30 data items (the program will need to be able to support a variable number of actual items in the array without any errors).
    3.     The data lines will be in the format: CatNo:Description:Price Use a StringTokenizer object to separate these data lines into their components.
    4.     A menu should appear, prompting the user for an action:
    a.     Display all goods: this will display a summary (in tabulated form) of all goods currently stored in the catalogue: per item the category, description, price excluding tax, payable tax and price including tax.
    b.     Dispfay cheapest/dearest goods: this will display a summary of all the cheapest and most expensive item(s) in the catalogue. In the case of more than one item being the cheapest (or most expensive), they should all be listed.
    c.     Sort the list: this will use a selection sort algorithm to sort the list in ascending order, using the catalogue number as the key.
    d.     Search the list: this will prompt the user for a catalogue number, and use a binary search to find the data. If the data has not yet been sorted, this menu option should not operate, and instead display a message to the user to sort the data before attempting a search
    5.     Work out a way to be able to support the inc tax/ex tax price accessors, and the tax component accessor, without needing to store any additional information in the object.
    6.     Use modifiers where appropriate to:
    a.     Ensure that data is properly protected;
    b.     Ensure that the accessors and mutators are most visible;
    c.     The accessors and mutators for the catalogue number and description cannot be overridden.
    d.     The constant for the tax rate is publicly accessible, and does not need an instance of the class present in order to be accessible.
    7.     The program should handle all exceptions wherever they may occur (i.e. file 1/0 problems, number formatting issues, etc.) A correct and comprehensive exception handling strategy (leading to a completely robust program) will be necessary and not an incomplete strategy (i.e. handling incorrect data formats, but not critical errors),
    Sample Execution
    C:\> java AssignmentSix mydata.txt
    Loading file data from mydata.txt ...17 item(s) OK
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    The goods cannot be searched, as the list is not yet sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: b
    CHEAPEST GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    BA023      Headphones      23.00      3.45      26.45
    JW289      Tape Recorder     23.00      3.45      26.45
    MOST EXPENSIVE GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    ZZ338      Wristwatch      295.00 44.25      339.25
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: c
    The data is now sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    Enter the catalogue number to find: ZJ282
    Cat Description ExTax Tax IncTax
    ZJ282 Pine Table 98.00 14.70 112.70
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: e
    Here you have the program as far as I could get. Please try to help me make it compact and implement a sorting method.
    Prem.
    By the way: you can get 8 Duke dollars (I have this topic also in the beginnersforum)
    //CatalogueManager.java
    import java.io.*;
    import java.text.DecimalFormat;
    import java.util.StringTokenizer;
    public class CatalogueManager {
    // private static final double TAXABLE_PERCENTAGE = 0.15;
    // Require it to be publicly accessible
    // static means it is class variable, not an object instance variable.
    public static final double TAXABLE_PERCENTAGE = 0.15;
    private String catalogNumber;
    private String description;
    private double price;
    /** Creates a new instance of CatalogueManager */
    public CatalogueManager() {
    catalogNumber = null;
    description = null;
    price = 0;
    public CatalogueManager(String pCatalogNumber, String pDescription, double pPrice) {
    catalogNumber = pCatalogNumber;
    description = pDescription;
    price = pPrice;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setCatalogNumnber(String pCatalogNumber) {
    catalogNumber = pCatalogNumber;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final String getCatalogNumber() {
    String str = catalogNumber;
    return str;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setDescription(String pDescription) {
    description = pDescription;
    // the accessors must be most visible
    // the final keyword prevents overridden
    public final String getDescription() {
    String str = description;
    return str;
    // If the parameter is not a double type, set the price = 0;
    // the mutators must be most visible
    public boolean setPrice(String pPrice) {
    try {
    price = Double.parseDouble(pPrice);
    return true;
    catch (NumberFormatException nfe) {
    price = 0;
    return false;
    // the accessors must be most visible
    public double getPrice() {
    double rprice = price;
    return formatDouble(rprice);
    double getTaxAmount(){
    double rTaxAmount = price * TAXABLE_PERCENTAGE;
    return formatDouble(rTaxAmount);
    double getIncTaxAmount() {
    double rTaxAmount = price * (1 + TAXABLE_PERCENTAGE);
    return formatDouble(rTaxAmount);
    double formatDouble(double value) {
    DecimalFormat myFormatter = new DecimalFormat("###.##");
    String str1 = myFormatter.format(value);
    return Double.parseDouble(str1);
    public static void main(String[] args) throws IOException {
    final int MAX_INPUT_ALLOW = 30;
    int MAX_CURRENT_INPUT = 0;
    FileReader fr;
    BufferedReader br;
    CatalogueManager[] catalogList = new CatalogueManager[MAX_INPUT_ALLOW];
    String str;
    char chr;
    boolean bolSort = false;
    double cheapest = 0;
    double mostExpensive = 0;
    String header = "Cat\tDescription\tExTax\tTax\tInc Tax";
    String lines = "---\t-----------\t------\t---\t-------";
    if (args.length != 1) {
    System.out.println("The application expects one parameter only.");
    System.exit(0);
    try {
    fr = new FileReader(args[0]);
    br = new BufferedReader(fr);
    int i = 0;
    while ((str = br.readLine()) != null) {
    catalogList[i] = new CatalogueManager();
    StringTokenizer tokenizer = new StringTokenizer(str, ":" );
    catalogList.setCatalogNumnber(tokenizer.nextToken().trim());
    catalogList[i].setDescription(tokenizer.nextToken().trim());
    if (! catalogList[i].setPrice(tokenizer.nextToken())){
    System.out.println("The price column cannot be formatted as dobule type");
    System.out.println("Application will convert the price to 0.00 and continue with the rest of the line");
    System.out.println("Please check line " + i);
    if (catalogList[i].getPrice() < cheapest) {
    cheapest = catalogList[i].getPrice();
    if (catalogList[i].getPrice() > mostExpensive) {
    mostExpensive = catalogList[i].getPrice();
    i++;
    fr.close();
    MAX_CURRENT_INPUT = i;
    catch (FileNotFoundException fnfe) {
    System.out.println("Input file cannot be located, please make sure the file exists!");
    System.exit(0);
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    System.out.println("Application cannot read the data from the file!");
    System.exit(0);
    boolean bolLoop = true;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    do {
    System.out.println("");
    System.out.println("CATALOGUE MANAGER: MAIN MENU");
    System.out.println("============================");
    System.out.println("a) display all goods b) display cheapest/dearest goods");
    System.out.println("c) sort the goods list d) search the good list");
    System.out.println("e) quit");
    System.out.print("Option:");
    try {
    str = stdin.readLine();
    if (str.length() == 1){
    str.toLowerCase();
    chr = str.charAt(0);
    switch (chr){
    case 'a':
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'b':
    System.out.println("");
    System.out.println("CHEAPEST GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == cheapest){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    System.out.println("MOST EXPENSIVE GODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == mostExpensive) {
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'c':
    if (bolSort == true){
    System.out.println("The data has already been sorted");
    else {
    System.out.println("The data is not sorted");
    break;
    case 'd':
    break;
    case 'e':
    bolLoop = false;
    break;
    default:
    System.out.println("Invalid choice, please re-enter");
    break;
    catch (IOException ioe) {
    System.out.println("ERROR:" + ioe.getMessage());
    System.out.println("Application exits now");
    System.exit(0);
    } while (bolLoop);

    One thing you're missing totally is CatalogueItem!! A CatalogueManager manages the CatalogueItem's, and is not an CatalogueItem itself. So at least you have to have this one more class CatalogueItem.
    public class CatalogueItem {
    private String catalogNumber;
    private String description;
    private double price;
    //with all proper getters, setters.
    Then CatalogueManager has a member variable:
    CatalogueItem[] items;
    Get this straight and other things are pretty obvious...

  • Need help with running a Java program on Linux

    I am trying to get a Java program to run on a Linux machine. The program is actually meant for a Mac computer. I want to see if someone with Java experience can help me determine what is causing the program to stall. I was successful in getting it installed on my Linux machine and to partially run.
    The program is an interface to a database. I get the login screen to appear, but then once I enter my information and hit enter the rest of the program never shows, however, it does appear to connect in the background.
    Here is the error when I launch the .jar file from the command screen:
    Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    I am not a programmer and I am hoping this will make some sense to someone. Any help in resolving this is greatly appreciated!

    Well, without knowing a little bit about programming, and how to run your debugger, I don't think you're going to fix it. The IllegalArgumentException is saying that some call does not like what it's getting. So you'll have to go in an refactor at least that part of the code.

  • Please help with Java program

    Errors driving me crazy! although compiles fine
    I am working on a project for an online class - I am teaching myself really! My last assignment I cannot get to work. I had a friend who "knows" what he is doing help me. Well that didn't work out too well, my class is a beginner and he put stuff in that I never used yet. I am using Jgrasp and Eclipse. I really am trying but, there really is no teacher with this online class. I can't get questions answered in time and stuff goes past due. I am getting this error:
    Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader .java:55)
    at java.util.Scanner.<init>(Scanner.java:590)
    at ttest.main(ttest.java:54)
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    This is my code:
    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    The assignment is:
    Create a Java program to read in an unknown number of lines from a data file. You will need to create the data file. The contents of the file can be found at the bottom of this document. This file contains a football team's name, the number of games they have won, and the number of games they have lost.
    Your program should accomplish the following tasks:
    1. Process all data until it reaches the end-of-file. Calculate the win percentage for each team.
    2. Output to a file ("top.txt") a listing of all teams with a win percentage greater than .500. This file should contain the team name and the win percentage.
    3. Output to a file ("bottom.txt") a listing of all teams with a win percentage of .500 or lower. This file should contain the team name and the win percentage.
    4. Count and print to the screen the number of teams with a record greater then .500 and the number of teams with a record of .500 and below, each appropriately labeled.
    5. Output in a message box: the team with the highest win percentage and the team with the lowest win percentage, each appropriately labeled. If there is a tie for the highest win percentage or a tie for the lowest win percentage, you must output all of the teams.
    Dallas 5 2
    Philadelphia 4 3
    Washington 3 4
    NY_Giants 3 4
    Minnesota 6 1
    Green_Bay 3 4

    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    }

  • My first java programming - Need some help please!!!

    I have to create a simple java program which i am not good at i am ok in C but my java is quite bad. The program need to define a class called Student and with a string called StudentNAme, a integer StudentID(key), An array of 8 integers called Marks that holds the students marks for 8 modules. It also says Include appropriate accessors, mutators and constructor(s) as well as a method to update the student�s marks. Anybody please help me in this question. I prefer an simple example of this program so I can learn faster, I dont even know how to declare a class.. So sorry but please help me out and thanks in advance

    I would also suggest you try using an IDE like
    eclipse (free)
    www.eclipse.org
    This will help you get a working program much faster.But please do also tell them that if they have troubles using it, they're supposed to read the IDE manual instead of posting here.

  • Need Help with a JAVA programming assignment

    How do I write a JAVA program that could be used as the start of an MS-DOS/Windows simulation of the IEEE 802.3 protocol? I am to only code the parts necessary to build the 802.3 frame. For the initial implementation, the Checksum function need not be a CRC function, and the Destination and Source addresses wil be in input, stored, and output, and in dotted-decimal format.
    I need:
    1. A record to describe the frame, with each field being a (byte-) string of the required size, except that the Data field is of variable size. Although the "Source address" and "Destination address" would be 6 bytes for a real implementation, for this first implementation you can either assume they'll be text strings in the usual "dotted decimal" form (e.g. "14.04.05.18.01.25" as a typical example--from Tanenbaum, p. 429), or 6 hex digits.
    2. Suitable constant declarations for values such as the standard "Preamble" and "Start of Frame" values.
    3. Suitable functions to Get the three variable values "Destination address", "Source address", and "Data" from the standard input device.
    4. A suitable function to display each of the fields of a given frame in a format such as:
    Preamble: ...
    StartofFrame: ...
    Destination: ...
    etc.
    5. A suitable function to generate a "Pad" field if necessary.
    6. A "dummy" Checksum-generating function which just takes the first 32 bits (4 bytes) of the Data (or Data+Pad, if necessary) rather than an actual CRC algorithm.
    I have no experience with Java. Can you help me or start me in the right direction?
    Thanks...........TK

    If you have no experience with Java, then it seems to me your first step should be to start learning the language. But it's difficult to advise how, since we don't know anything about your background. There are many good books available on Java, some are for beginners and some are for advanced programmers, so I'd suggest you go somewhere that has a large selection and start looking for something that doesn't seem completely over your head.

  • Need Help with a Java program

    Hey
    I am doing a bachelor of Multimedia and for some reason I was forced to do Programming 1 which is just Java programing.I have been doing pretty well but we have the final exam coming up on Thursday and they told us to learn how to do this question but I have no idea how to do it, could someone please help me?
    Write a program that reads a file containing a list of students' student numbers and names, and then writes out another file in which the students have been formed into project groups.
    Sample input file:
    96439530 Naranek, Kosh
    08532109 Ivanova, Susan
    87642078 Sheridan, John
    44327889 Varner, Dell
    98100023 Kotto, Vir
    66345689 Sinclair, Jeffrey
    77421009 Garibaldi, Michael
    88775544 Winters, Talia
    54321098 Alexander, Lyta
    12345098 Mollari, Londo
    03465499 Takashima, Laurel
    88765432 Kyle, Benjamin
    08876500 Keffer, Warren
    07687878 Cole, Marcus
    For the project course: no group should have more than 5 members; and it is desireable that all groups have as close to 5 members as possible; and that students be allocated to groups alphabetically by family name, as in this sample output file:
    Group 1:
    Lyta Alexander (54321098)
    Susan Ivanova (08532109)
    Benjamin Kyle (88765432)
    John Sheridan (87642078)
    Dell Varner (44327889)
    Group 2:
    Marcus Cole (07687878)
    Warren Keffer (08876500)
    Londo Mollari (12345098)
    Jeffrey Sinclair (66345689)
    Talia Winters (88775544)
    Group 3:
    Michael Garibaldi (77421009)
    Vir Kotto (98100023)
    Kosh Naranek (96439530)
    Laurel Takashima (03465499)
    Students' names are first sorted (Alexander, Cole, Garibaldi, Ivanova, ...), then allocated to the tutes in rotation (Alexander to 1, Cole to 2, Garibaldi to 3, Ivanova to 1, ...).
    Note also that the student's details are written in a different format from the input. You may make the (usually wrong!) assumption that each student has a simple one-word family name and one other name.

    I'm sorry too annoy you again but I don't know how to implement what you told me. Here is my current code:
    import java.io.*;
    import java.util.*;
    class DetailSortTest {
         public void run() {
              try {
                   BufferedReader in = new
                   BufferedReader(new FileReader ("Data.txt"));
                   String line = in.readLine();
                   String[] names = new String [10];
                   int i = 0;
                   PrintWriter FileOut = new
                   PrintWriter(new FileWriter ("Data 2.txt"));
                   processFilesTest(in, FileOut);
                   in.close();
                   FileOut.close();
              } catch (FileNotFoundException f) {
                   System.out.println("Could Not Open The File");
              } catch (IOException i){
                   System.out.println(i.getMessage());
         public void processFilesTest (BufferedReader in, PrintWriter FileOut)
         throws IOException {
              String data[] = new String[100];
              List dList = new ArrayList();
              String NLine = in.readLine();
              FileOut.println(NLine);
         public static void main(String[] args) {
              DetailSortTest anObject = new
              DetailSortTest();
              anObject.run();
    How would I do it I tried:
    NLine.split(data[2]+""+data[1]+""+data[0]);
    But all that displays is null, null, null
    I know I am probably so stupid but I really appreciate the help

  • Need help in my assignment, Java programing?

    Need help in my assignment, Java programing?
    It is said that there is only one natural number n such that n-1 is a square and
    n + 1 is a cube, that is, n - 1 = x2 and n + 1 = y3 for some natural numbers x and y. Please implement a program in Java.
    plz help!!
    and this is my code
    but I don't no how to finsh it with the right condition!
    plz heelp!!
    and I don't know if it right or wrong!
    PLZ help me!!
    import javax.swing.JOptionPane;
    public class eiman {
    public static void main( String [] args){
    String a,b;
    double n,x,y,z;
    boolean q= true;
    boolean w= false;
    a=JOptionPane.showInputDialog("Please enter a number for n");
    n=Double.parseDouble(a);
    System.out.println(n);
    x=Math.sqrt(n-1);
    y=Math.cbrt(n+1);
    }

    OK I'll bite.
    I assume that this is some kind of assignment.
    What is the program supposed to do?
    1. Figure out the value of N
    2. Given an N determine if it is the correct value
    I would expect #1, but then again this seem to be a strange programming assignment to me.
    // additions followI see by the simulpostings that it is indeed #1.
    So I will give the tried and true advice at the risk of copyright infringement.
    get out a paper and pencil and think about how you would figure this out by hand.
    The structure of a program will emerge from the mists.
    Now that I think about it that advice must be in public domain by now.
    Edited by: johndjr on Oct 14, 2008 3:31 PM
    added additional info

  • Pls Help--- URGENT... Combining XML file and HTML file Using java program.

    Hi, I need to implemnt this for my project....
    I need to combine XML and HTML file and generate a new HTML file
    Sample XML File:
    <user>
    <txtName>sun</txtName>
    <txtAge>21 </txtAge>
    </user>
    Sample HTML File:
    <body>
    Name: <input type="text" name="txtName" value=""
    Age : <input type="text" Age="txtAge" value=""
    </body>
    I need a java program to combine the above xml and html files and generate the output in HTML.
    Any kind of help is sincerely Appreciated.
    Thanks.

    toucansam wrote:
    So you want us to write it for you? It's pretty straight forward, first parse the xml file with the *[best java xml parser|http://www.google.com/search?&q=parsing+xml+in+java]* and then go through the nodes and construct the html with strings and concatination. Then write the file using *[the best java file writer|http://www.google.com/search?hl=en&q=writing+to+a+file+in+java]*.
    He would do better to use existing tools that make this easy [http://www.ling.helsinki.fi/kit/2004k/ctl257/JavaXSLT/Ch05.html|http://www.ling.helsinki.fi/kit/2004k/ctl257/JavaXSLT/Ch05.html]

  • Help with Java programming project

    Hi,
    I need help in writing this Java program. The purpose of this program is to read a variable-length stream of 0, 1 characters from an input text file (call it input.txt) one character at a time, and generate the corresponding B8ZS output stream consisting of the +, - , and 0 characters (with appropriate substitutions) one-character-at-a-time into a text file (called output.txt).
    The program must use a class called AMIConverter with an object called AMI . Class AMIConverter must have a method called convert which converts an individual input character 0 or 1 into the appropriate character 0 or + or - of AMI.
    It first copy the line to file output.txt. Then read the line one character at a time and pass only valid characters (0 or 1) to AMI.convert, which assumes only valid characters. The first 1 in each new 'Example' should be converted to a +.
    This is what is read in, but this is just a test case.
    0101<1000
    1100a1000b00
    1201g101
    should now produce two lines of output for each 'Example', as shown below:
    This should be the output of the output.txt file
    Example 1
    in :0101<1000
    out:0+0-+000
    Example 2
    in :1100a1000b00
    out:+-00+00000
    Example 3
    in :1201g101
    out:+0-+0-
    To elaborate more, only 1 and 0 are passed to "convert" method. All others are ignored. 0 become 0 and 1 become either + or - and the first "1" in each new example should be a +.
    This is what I have so far. So far I am not able to get the "in" part, the characters (e.g. : 0101<1000 ) out to the output.txt file. I am only able to get the "out" part. And I also can't get it to display a + for the first "1" in each new examples.
    import java.io.*;
    public class AMIConverter
         public static void main (String [] args) throws IOException
              AMI ami = new AMI();
              try
                   int ch = ' ';
                   int lineNum = 1;
         int THE_CHAR_0 = '0';
         int THE_CHAR_1 = '1';
                   BufferedReader infile = new BufferedReader(new FileReader("input.txt"));
         PrintWriter outfile = new PrintWriter("output.txt");
         outfile.write("Example " + lineNum);//prints Example 1
         outfile.println();
         outfile.write("in :");
    outfile.println();
    outfile.write("out:");
         while ((ch = infile.read()) != -1)
         if (ch == '\r' || ch == '\n')
              lineNum++;
              outfile.println();
              outfile.println();
              outfile.write("Example " + lineNum);
              outfile.println();
              outfile.write("in :");
              outfile.println();
              outfile.write("out:");
         else
         if (ch == THE_CHAR_0)
              int output = ami.convert(ch);
              outfile.write(output);
         else     
         if (ch == THE_CHAR_1)
              int output = ami.convert(ch);
              outfile.write(output);          
    }//end while
         infile.close();
         outfile.close();
         }catch (IOException ex) {}
    }//main method
    }//class AMIConverter
    This is my AMI class
    import java.io.*;
    public class AMI
         int THE_CHAR_0 = '0';
    int THE_CHAR_1 = '1';
    int total = '+';
    int minus = '-';
    int count = 0;
    public int convert(int ch)
         try
              PrintWriter outfile = new PrintWriter("output.txt");
              if (ch == THE_CHAR_0)
         return ch;
         else
         if (ch == THE_CHAR_1)
         count++;
         if (count%2 == 1)
              ch = total;
              return (ch);
         else
                             ch = minus;     
                             return (ch);      
    }catch (FileNotFoundException e) {}      
         return ch;
    }//method convert
    }//class AMI
    Any help would be appreicated.
    Thanks!

    Hi,
    I need help in writing this Java program. The purpose of this program is to read a variable-length stream of 0, 1 characters from an input text file (call it input.txt) one character at a time, and generate the corresponding B8ZS output stream consisting of the +, - , and 0 characters (with appropriate substitutions) one-character-at-a-time into a text file (called output.txt).
    The program must use a class called AMIConverter with an object called AMI . Class AMIConverter must have a method called convert which converts an individual input character 0 or 1 into the appropriate character 0 or + or - of AMI.
    It first copy the line to file output.txt. Then read the line one character at a time and pass only valid characters (0 or 1) to AMI.convert, which assumes only valid characters. The first 1 in each new 'Example' should be converted to a +.
    This is what is read in, but this is just a test case.
    0101<1000
    1100a1000b00
    1201g101
    should now produce two lines of output for each 'Example', as shown below:
    This should be the output of the output.txt file
    Example 1
    in :0101<1000
    out:0+0-+000
    Example 2
    in :1100a1000b00
    out:+-00+00000
    Example 3
    in :1201g101
    out:+0-+0-
    To elaborate more, only 1 and 0 are passed to "convert" method. All others are ignored. 0 become 0 and 1 become either + or - and the first "1" in each new example should be a +.
    This is what I have so far. So far I am not able to get the "in" part, the characters (e.g. : 0101<1000 ) out to the output.txt file. I am only able to get the "out" part. And I also can't get it to display a + for the first "1" in each new examples.
    import java.io.*;
    public class AMIConverter
    public static void main (String [] args) throws IOException
    AMI ami = new AMI();
    try
    int ch = ' ';
    int lineNum = 1;
    int THE_CHAR_0 = '0';
    int THE_CHAR_1 = '1';
    BufferedReader infile = new BufferedReader(new FileReader("input.txt"));
    PrintWriter outfile = new PrintWriter("output.txt");
    outfile.write("Example " + lineNum);//prints Example 1
    outfile.println();
    outfile.write("in :");
    outfile.println();
    outfile.write("out:");
    while ((ch = infile.read()) != -1)
    if (ch == '\r' || ch == '\n')
    lineNum++;
    outfile.println();
    outfile.println();
    outfile.write("Example " + lineNum);
    outfile.println();
    outfile.write("in :");
    outfile.println();
    outfile.write("out:");
    else
    if (ch == THE_CHAR_0)
    int output = ami.convert(ch);
    outfile.write(output);
    else
    if (ch == THE_CHAR_1)
    int output = ami.convert(ch);
    outfile.write(output);
    }//end while
    infile.close();
    outfile.close();
    }catch (IOException ex) {}
    }//main method
    }//class AMIConverterThis is my AMI class
    import java.io.*;
    public class AMI
    int THE_CHAR_0 = '0';
    int THE_CHAR_1 = '1';
    int total = '+';
    int minus = '-';
    int count = 0;
    public int convert(int ch)
    try
    PrintWriter outfile = new PrintWriter("output.txt");
    if (ch == THE_CHAR_0)
    return ch;
    else
    if (ch == THE_CHAR_1)
    count++;
    if (count%2 == 1)
    ch = total;
    return (ch);
    else
    ch = minus;
    return (ch);
    }catch (FileNotFoundException e) {}
    return ch;
    }//method convert
    }//class AMIAny help would be appreicated.
    Thanks!

  • Java program in XP - Please Help

    Hi, I am not sure if I am in the right fourm. I am not a developer, but a network engineer trying to help out my wife. My wife uses a java program to monitor the company she works for web site, which is not linked to a web browser. When she received the java program, it came with Java 1.2.2. Our PC had Windows 98 installed. I purchased a new machine, with Windows XP on it, and installed the java program and JRE on to it. The program does not work. The programmer who wrote the program was fired a few months ago, so I started looking through the internet, and the Sun fourms for a solution. First, the XP machine does not have Microsoft VM on it. Second, I upgraded the java to 1.4.1_02, following the instructions, still with no success. There was a suggestion to dual boot with Windows 98, but I really do not want to do that. What happens is - when you log in to the program, it just freezes. It does not go into the server. Any help is greatly appreciated.

    Possible reasons for the program hanging up
    1) The version of the VM on the machine is not correct.
    2) Even if the version is correct and correctly installed, can you please check whether the PATH and CLASSPATH variables are set correctly on the machine where you are running the program.
    3) I use WINXP as well with the latest version of VM downloaded from Sun and NOT Microsoft.
    Hopefully this might solve the issue.

Maybe you are looking for

  • Need help formatting Spry drop down menu

    FYI, I'm using CS3 on a Mac. I'm working on a full CSS layout of a page in a site. OK, not full CSS, I have a table controlling the text in the main content area. I need a drop down menu for this page, so I inserted a spry menu bar for the page navig

  • Booting from usb disk

    hello I'm new in solaris and I need help very much. I installed Solaris 10 for x86 on external 3.5'' usb HD but on boot it hangs and a perpetual black screen appears.I've read about usb legacy and I disabled it but now BIOS doesn't see usb disk. I tr

  • How to set -Xss or ulimit  for Oracle Http Server

    Hi, We are facing Out of Memory Error in OHS 11g in our cluster environment. Where I can see below statements in http log file: # There is insufficient memory for the Java Runtime Environment to continue. # Cannot create GC thread. Out of system reso

  • Finder window size not saved when cmd+click

    Hi. I'm not sure if anyone else is having this problem. I look through the forum but didn't find it posted. I re-sized my finder to a certain size and have done the same to some other folder such that they are basically all different sizes. However,

  • Desperately Needed Auth Help

    Hi Apple Community, I've Authorized 5 computers in the past, mostly gaming computers that I built myself.  As technology advances, so do my gaming rigs and thus I leave old computers behind, either selling them whole, or breaking them down into their