Rounding a float to an integer in this program

Hello, I would like to be able to use floats in this program. If i input say 50.5 at the moment i get an error (the program compiles ok).
What I want to happen is that i enter say 50.5, the program rounds this to 51 and then uses 51 thus not getting an error.
Thanks anyone
*Write a program to prompt the user to enter a mark as a
*floating point number.  Check that the mark is in the
*range 0.0 to 100.0 and, if not, repeat the prompt until
*the mark is in the required range.  Then display the
*indicative degree classification according to the mapping
*above, bearing in mind that marks with fractional parts
*greater than .5 are rounded up (e.g. 59.5 is to be interpreted
*as 60 and so as an Upper Second).
*Test your program to ensure that the mapping is correct.
import java.util.Scanner;
class FloatMark
     public static void main(String[] argStrings) throws Exception
          float mark;
          int intMark;
          do
               Scanner scan = new Scanner(System.in);
               System.out.println("Give me the float mark please: ");
               mark = scan.nextInt();
               intMark = Math.round(mark);
               if(intMark < 0 || intMark > 100)
                    System.out.println("Give me a valid float mark please");
               else if (intMark < 40)
                    System.out.println("Fail!");
               else if (intMark >= 40 && intMark < 49)
                    System.out.println("Third");
               else if (intMark >= 50 && intMark < 59)
                    System.out.println("Lower second");
               else if (intMark >= 60 && intMark < 69)
                    System.out.println("Higher second");
               else if (intMark >= 70)
                    System.out.println("First");
          while(intMark < 40 || intMark > 0);
}

This is the latest and greatest for you, woo!
import java.util.Scanner;
class FloatMark
     public static void main(String[] argStrings) throws Exception
          float mark;
          int intMark;
          String exit = null;
          do
               Scanner scan = new Scanner(System.in);
               System.out.println("Give me the float mark please: ");
               mark = scan.nextFloat();
               exit = scan.nextLine();
               intMark = Math.round(mark);
               if(intMark < 0 || intMark > 100)
                    System.out.println("Give me a valid float mark please");
               else if (intMark < 40)
                    System.out.println("Fail!");
               else if (intMark >= 40 && intMark < 49)
                    System.out.println("Third");
               else if (intMark >= 50 && intMark < 59)
                    System.out.println("Lower second");
               else if (intMark >= 60 && intMark < 69)
                    System.out.println("Higher second");
               else if (intMark >= 70)
                    System.out.println("First");
          while(intMark < 100 || intMark > 0 || exit != "e");
}

Similar Messages

  • Java newbie (what's could be wrong with this program?)

    First things first, I just started programming with JAVA recently so please forgive me if it seems stupid. Since I am so relatively new to the language, in order to get a feel for it I started running some simple scripts. I can compile and execute most of them without any problem. However when I tried to compile this one I get a couple of errors I am not familiar with. So my question is what could be wrong and what needs to be changed in order to get it to work? or if the syntax is correct could there be some other problem?
    On a side note, I am coming more from a C and C++ background so if anyone can recommend a way to start learning the JAVA language from a prespective in C that would be highly appreciated.
    System Environment: I am using j2sdk1.4.2 on a Windows 2000 machine running SP3.
    If anything else needs further clarification please let me know.
    |------------------------- The Code -----------------------------------|
    package RockPaperScissors;
    import java.util.HashMap;
    public class RockPaperScissors {
    String[] weapons = {"Rock", "Paper", "Scissors"};
    EasyIn easy = new EasyIn();
    HashMap winners = new HashMap();
    String playerWeapon;
    String cpuWeapon;
    int cpuScore = 0;
    int playerScore = 0;
    public static void main(String[] args) {
    RockPaperScissors rps = new RockPaperScissors();
    boolean quit = false;
    while (quit == false) {
    rps.playerWeapon = rps.getPlayerWeapon();
    rps.cpuWeapon = rps.getCpuWeapon();
    System.out.println("\nYou chose: " + rps.playerWeapon);
    System.out.println("The computer chose: " + rps.cpuWeapon + "\n");
    rps.getWinner(rps.cpuWeapon, rps.playerWeapon);
    if (rps.playAgain() == false) {
    quit = true;
    System.out.println("Bye!");
    public RockPaperScissors() {
    String rock = "Rock";
    String paper = "Paper";
    String scissors = "Scissors";
    winners.put(rock, scissors);
    winners.put(scissors, paper);
    winners.put(paper, rock);
    System.out.println("\n\t\tWelcome to Rock-Paper-Scissors!\n");
    public String getPlayerWeapon() {
    int choice = 6;
    String weapon = null;
    System.out.println("\nPlease Choose your Weapon: \n");
    System.out.println("1. Rock \n2. Paper \n3. Scissors \n\n0. Quit");
    try {
    choice = easy.readInt();
    } catch (Exception e) {
    errorMsg();
    return getPlayerWeapon();
    if (choice == 0) {
    System.out.println("Quitting...");
    System.exit(0);
    } else {
    try {
    weapon = weapons[(choice - 1)];
    } catch (IndexOutOfBoundsException e) {
    errorMsg();
    return getPlayerWeapon();
    return weapon;
    public void errorMsg() {
    System.out.println("\nInvalid Entry.");
    System.out.println("Please Select Again...\n\n");
    public String getCpuWeapon() {
    int rounded = -1;
    while (rounded < 0 || rounded > 2) {
    double randomNum = Math.random();
    rounded = Math.round(3 * (float)(randomNum));
    return weapons[rounded];
    public void getWinner(String cpuWeapon, String playerWeapon) {
    if (cpuWeapon == playerWeapon) {
    System.out.println("Tie!\n");
    } else if (winners.get(cpuWeapon) == playerWeapon) {
    System.out.println("Computer Wins!\n");
    cpuScore++;
    } else if (winners.get(playerWeapon) == cpuWeapon) {
    System.out.println("You Win!\n");
    playerScore++;
    public boolean playAgain() {
    printScore();
    System.out.print("\nPlay Again (y/n)? ");
    char answer = easy.readChar();
    while (true) {
    if (Character.toUpperCase(answer) == 'Y') {
    return true;
    } else if (Character.toUpperCase(answer) == 'N') {
    return false;
    } else {
    errorMsg();
    return playAgain();
    public void printScore() {
    System.out.println("Current Score:");
    System.out.println("Player: " + playerScore);
    System.out.println("Computer: " + cpuScore);
    |------------------------- Compiler Output ----------------------------|
    C:\ide-xxxname\sampledir\RockPaperScissors>javac RockPaperScissors.java
    RockPaperScissors.java:8: cannot resolve symbol
    symbol : class EasyIn
    location: class RockPaperScissors
    EasyIn easy = new EasyIn();
    ^
    RockPaperScissors.java:8: cannot resolve symbol
    symbol : class EasyIn
    location: class RockPaperScissors
    EasyIn easy = new EasyIn();
    ^
    2 errors

    limeybrit9,
    This importing certainly seems to be the problem, I'm still not used to how compilation works within the JAVA language, I'll play around with it a bit and see if I can get it to work correctly.
    bschauwe,
    The C++ approach has certainly clarified some of the points. I guess I will be sticking to that.
    bsampieri,
    You were correct on the class looking rather generic, but as I mentioned before I was just sort of tinkering to see if I could get it to work.
    Thanks to all for the help, very much appreciated.

  • New to Java and need help with this program..please!

    I'd really appreciate any helpful comments about this program assignment that I have to turn in a week from Friday. I'm taking a class one night a week and completely new to Java. I'd ask my professor for help, but we can't call him during the week and he never answers e-mails. He didn't tell us how to call from other classes yet, and I just can't get the darn thing to do what I want it to do!
    The assignment requirements are:
    1. Change a card game application that draws two cards
    and the higher card wins, to a Blackjack application
    2. Include a new class called Hand
    3. The Hand class should record the number of draws
    4. The application should prompt for a number of draws
    5. The game is played against the Dealer
    6. The dealer always draws a card if the dealer's hand total is <= 17
    7. Prompt the player after each hand if he wants to quit
    8. Display the total games won by the dealer and total and the total games wond by the player after each hand
    9. Display all of the dealer's and player's cards at the
    end of each hand
    10. Player has the option of drawing an additional card after the first two cards
    11. The Ace can have a value of 11 or 1
    (Even though it's not called for in the requirements, I would like to be able to let the Ace have a value of 1 or an 11)
    The following is my code with some comments about a few things that are driving me nuts:
    import java.util.*;
    import javax.swing.*;
    import java.text.*;
    public class CardDeck
    public CardDeck()
    deck = new Card[52];
    fill();
    shuffle();
    public void fill()
    int i;
    int j;
    for (i = 1; i <= 13; i++)
    for (j = 1; j <= 4; j++)
    deck[4 * (i - 1) + j - 1] = new Card(i, j);
    cards = 52;
    public void shuffle()
    int next;
    for (next = 0; next < cards - 1; next++)
    int rand = (int)(Math.random()*(next+1));
    Card temp = deck[next];
    deck[next] = deck[rand];
    deck[rand] = temp;
    public final Card draw()
    if (cards == 0)
    return null;
    cards--;
    return deck[cards];
    public int changeValue()
    int val = 0;
    boolean ace = false;
    int cds;
    for (int i = 0; i < cards; i++)
    if (cardValue > 10)
    cardValue = 10;
    if (cardValue ==1)     {
    ace = true;
    val = val + cardValue;
    if ( ace = true && val + 10 <= 21 )
    val = val + 10;
    return val;
    public static void main(String[] args)
    CardDeck d = new CardDeck();
    int x = 3;
    int i;
    int wins = 1;
    int playerTotal = 1;
    do {
    Card dealer = (d.draw());
    /**I've tried everything I can think of to call the ChangeValue() method after I draw the card, but nothing is working for me.**/
    System.out.println("Dealer draws: " + dealer);
    do {
    dealer = (d.draw());
    System.out.println(" " + dealer);
    }while (dealer.rank() <= 17);
    Card mine = d.draw();
    System.out.println("\t\t\t\t Player draws: "
    + mine);
    mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
    do{
    String input = JOptionPane.showInputDialog
    ("Would you like a card? ");
    if(input.equalsIgnoreCase("yes"))
         mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
         playerTotal++;
         else if(input.equalsIgnoreCase("no"))
    System.out.println("\t\t\t\t Player stands");
         else
    System.out.println("\t\tInvalid input.
    Please try again.");
    I don't know how to go about making and calling a method or class that will combine the total cards delt to the player and the total cards delt to the dealer. The rank() method only seems to give me the last cards drawn to compare with when I try to do the tests.**/
    if ((dealer.rank() > mine.rank())
    && (dealer.rank() <= 21)
    || (mine.rank() > 21)
    && (dealer.rank() < 22)
    || ((dealer.rank() == 21)
    && (mine.rank() == 21))
    || ((mine.rank() > 21)
    && (dealer.rank() <= 21)))
    System.out.println("Dealer wins");
    wins++;
         else
    System.out.println("I win!");
    break;
    } while (playerTotal <= 1);
    String stop = JOptionPane.showInputDialog
    ("Would you like to play again? ");
    if (stop.equalsIgnoreCase("no"))
    break;
    if (rounds == 5)
    System.out.println("Player wins " +
    (CardDeck.rounds - wins) + "rounds");
    } while (rounds <= 5);
    private Card[] deck;
    private int cards;
    public static int rounds = 1;
    public int cardValue;
    /**When I try to compile this nested class, I get an error message saying I need a brace here and at the end of the program. I don't know if any of this code would work because I've tried adding braces and still can't compile it.**/
    class Hand()
    static int r = 1;
    public Hand() { CardDeck.rounds = r; }
    public int getRounds() { return r++; }
    final class Card
    public static final int ACE = 1;
    public static final int JACK = 11;
    public static final int QUEEN = 12;
    public static final int KING = 13;
    public static final int CLUBS = 1;
    public static final int DIAMONDS = 2;
    public static final int HEARTS = 3;
    public static final int SPADES = 4;
    public Card(int v, int s)
    value = v;
    suit = s;
    public int getValue() { return value; }
    public int getSuit() { return suit;  }
    public int rank()
    if (value == 1)
    return 4 * 13 + suit;
    else
    return 4 * (value - 1) + suit;
    /**This works, but I'm confused. How is this method called? Does it call itself?**/
    public String toString()
    String v;
    String s;
    if (value == ACE)
    v = "Ace";
    else if (value == JACK)
    v = "Jack";
    else if (value == QUEEN)
    v = "Queen";
    else if (value == KING)
    v = "King";
    else
    v = String.valueOf(value);
    if (suit == DIAMONDS)
    s = "Diamonds";
    else if (suit == HEARTS)
    s = "Hearts";
    else if (suit == SPADES)
    s = "Spades";
    else
    s = "Clubs";
    return v + " of " + s;
    private int value; //Value is an integer, so how can a
    private int suit; //string be assigned to an integer?
    }

    Thank you so much for offering to help me with this Jamie! When I tried to call change value using:
    Card dealer = (d.changeValue());
    I get an error message saying:
    Incompatible types found: int
    required: Card
    I had my weekly class last night and the professor cleared up a few things for me, but I've not had time to make all of the necessary changes. I did find out how toString worked, so that's one question out of the way, and he gave us a lot of information for adding another class to generate random numbers.
    Again, thank you so much. I really want to learn this but I'm feeling so stupid right now. Any help you can give me about the above error message would be appreciated.

  • PLEASE HELP ME. THIS PROGRAM IS KILLING ME.

    Hi. I am getting so sick of this program. I have been trying to do it for the past couple of weeks and I am getting nowhere. I really wish someone can help me on it ... like totaly help me on it. I am getting so frustrated. I would appreciate all the help.
    This is the program:
    In Belageusia, a plorg has these properties:
    Data:
         A plorg has a name
         A plorg has a contentment index (CI), which is an integer between 0 and 100
    The population of plorgs in Belagersia is further subdivided into three mutually exclusive classes: Plebeians, Equidians, and Elitians.
    A Plorg?s stature is completely determined by their contentment index and witht that designation comes certain burdens and/or advantages.
    Plebeians have a contentment index in [0, 24].
    Each new Plebeian is welcomed with a contentment index of 2 and burdened with a debt of $10.00
    Plebeians never manage to break even, so they have no taxes imposed upon them. Furthermore, since they can never get out debt, they cannot accumulate any wealth.
    Equidians have a contentment index in [25, 75]
    Each new Equidian is welcomed with a contentment index of 50 and burdened with taxes of $20.00
    Equidians have taxes imposed upon them. Furthermore, since they do manage to break even, they have no debt. However, since they only manager to break even, they do not accumulate any wealth.
    Elitians have a contentment index in [76, 100]
    Each new Elitian is welcomed with a contentment index of 87 and burdened with taxes of $20.00, but also provided with a ?silver spoon? of $30.00 in accumulated wealth.
    Elitians manage to expand upon their wealth, sot hey have taxes imposed upon them. Furthermore, since they are accumulating wealth, they have no debt.
    At each interim time epoch the population of Belageusia retracts with a death rate randomly selected between 0% and 10%. If a plorg survives the purge, they have an opportunity to move one class higher and/or one class lower. However, remember that a plorg?s name is final. It never changes.
    For Plebeians this is transition is determined by randomly selecting a CI in [0, 49]. If this new CI is les than 25 then the plorg remains a Plebeian, with this newly assigned CI, and their debt increases 3.7%. If this new CI is in [25, 49], the Plebeian ascends to a Equidian, with this newly assigned CI, their debt is forgiven, but taxes of $20 are assessed.
    For Equidians this is determined by randomly selecting a CI in [0,100].
    If this new CI is in [25, 75] then the plorg remains a Equidian, with this newly assigned CI, but their taxes are increased 6.1%.
    If this new CI is in [0, 24] then the plorg becomes a Plebeian, with this newly assigned CI, their taxes are forgiven, but they are burdened with a debt of $10.00.
    If this new CI is in [76, 100] then the plorg becomes a Plebeian, with this newly assigned CI, but their taxes are increased 6.1%. However, they are bewtowed a wealth of $30.00.
    For Eletians this is determined by randomly selecting a CI in [51, 100]. If this new CI is greater than 76 then the plorg remains an Eletian, with this newly assigned CI, their taxes increase 6.1% and their wealth increases 4.9%. If this new CI is in [51, 75], then this plorg becomes an Equidian, with this newly assigned CI, their wealth is eliminated, and their taxes are increased 6.1%.
    At each time epoch, the population of Belageusia at a birth rate randomly selected between 0% and 10%. A randomly chosen number between 0-100 determines each newly born plorg?s stature. If this random number is in the range 0-24, create a new Plebeian. In the range 25-75, create a new Equidian, and if in the range 76-100, create a new Elitian.
    We are supposed to output the population characteristics of Belageusia, after 1000 time epochs.
    This is the code that I wrote down but got no where with:
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    public class Belageusiaplorg
         public static void main (String[] args)
              ArrayList Plebs = new ArrayList(350);
              ArrayList Equids = new ArrayList(600);
              ArrayList Elits = new ArrayList(350);
              ArrayList Holding = new ArrayList(600);
              for (int i=0; i<25; i++)
                   Plebs.add(new plebian());
              for (int i=0; i<50; i++)
                   Equids.add(new equidian());
              for (int i=0; i<25; i++)
                   Elits.add(new Elitian());
              long population = Plebs.size() + Equids..size() + Elits.size();
              System.out.println("Current Belageusia Population is "+population);
              System.out.println("Current Plebeians Population is "+Plebs.size);
              System.out.println("Current Equidians Population is "+Equids.size);
              System.out.println("Current Elitians Population is "+Elits.size);
              Random generator = new Random();
              int x = generator.nextInt(11);
              for (int j=0; j=plebs.size(); j++)
                   System.out.println(Plebs.g(j));
              long Equids_size = Equids.size();
              long Elits_size = Elits.size();
              for(int j=1; j<Plebs.size(); j++)
                   Plebian e = (Plebian) Plebs.get(j);
                   int new_ci = generator.nextInt(50);
                   if (new_ci < 25)
                        e.setCI(new_ci);
                        e.raiseDebt();
                   else
                        Plebs.rename(j);
                        Equids.add(new Equidian(e.getName().newCI));
                        j++;
              for(int j=0; j < Equids.size; j++)
                   Equidian e = (Equidian) Equids.get(j);
                   int newCI = generator.nextInt(101);
                   if(new_ci < 25)
                        Equids.remove(j);
                        Plebs.add(nwe Plebian(e.getName().new_ci));
                        Equids_size --;
                        j++;
                   else
                   if (new_ci > 75)
                        Equids.remove(j);
                        Elitian f = new Elitian(e.getName(),new_ci,e.getTaxes());
                        Elits.add(f);
                        Equids_size --;
                        j--;
                   else
                        e.setCI(new_CI);
                        e.raiseTaxes();
              for (int j=0; j<Elits.size; j++)
                   Elitian e = (Elitian) Elits.get(j);
                   int ci = e.getCI();
                   int r = generator.nextINT(50);
                   int new_ci = 51+r;
                   if(new_ci > 75)
                        e.setCI(new_ci);
                        e.raisetaxes();
                        e.raisewealth();
                   else
                        Elitians.remove(j);
                        Equidian g = new Equidian(e.getName(), new_ci);
                        g.raisetaxes();
                        Equids.add(g);
                        Elits_size --;
                        j--;
              if(deathrate != 0)
                   int multiple = 100/deathrate;
                   int count 1;
                   for (int j=0; j=Plebs.size(); j++)
                        if(count % multiple == 0)
                             Plebs.remove(j);
                             j--;
                        count++;
    class Plorg
         private final String name;
         private int CI;
         private static long nextID = 1;
         public Plorg()
              name = "Plorg" + nextID;
              nextID++;
         public Plorg(int CI)
              name = "Plorg" + nextID;
              nextID++;
              this.CI = CI;
         public Plorg (String name, int CI)
              this.name = name;
              this.CI = CI;
         public void setCI(int new_CI)
              CI = new_CI;
         public String getName()
              return name;
         public int getCI()
              return CI;
         public Plorg Plebs()
         public Plorg Equids()
         public Plorg Elits()

    Sounds a lot like a homework question to me. Still it was interesting enough to try out. I have not tried to change your code, just made one of my own. Here is my solution. I have made the Plorg class an inner class of the Belageusia. This is just so I dont have to put up two java files. You could easily split it into two though.
    import java.util.Random;
    import java.util.ArrayList;
    import java.util.Iterator;
    * @author Jonathan Knight
    public class Belageusia
        /** Random number generator - Seeded with the current time. */
        private static Random random = new Random(System.currentTimeMillis());
        /** A list of all of the Plorgs */
        private ArrayList population = new ArrayList();
        /** A list of all of the Plebians. */
        private ArrayList plebians = new ArrayList();
        /** A list of all of the Equidians. */
        private ArrayList equidians = new ArrayList();
        /** A list of all of the Elitians. */
        private ArrayList elitians = new ArrayList();
        /** A count of the Epochs that have passed */
        private int epochs = 0;
         * Main method.
         * Create a new world of Belageusia and run it for 1000 epochs.
        public static void main(String[] args)
            Belageusia world;
            world = new Belageusia();
            for (int i = 0; i < 1000; i++)
                world.epoch();
            System.out.println("The Belageusia population after 1000 epochs");
            world.printPopulation();
         * Create a new World of Belageusia and create some Plorgs to live there.
         * The world will be created with 25 Plebians, 50 Equidians and 25 Elitians.
        public Belageusia()
            for (int i = 0; i < 25; i++)
                plebians.add(Plorg.createPlebian());
            for (int i = 0; i < 50; i++)
                equidians.add(Plorg.createEquidian());
            for (int i = 0; i < 25; i++)
                elitians.add(Plorg.createElitian());
         * Print the current population to System.out
        public void printPopulation()
            int total;
            int plebianCount;
            int equidianCount;
            int elitianCount;
            plebianCount = plebians.size();
            equidianCount = equidians.size();
            elitianCount = elitians.size();
            total = plebianCount + equidianCount + elitianCount;
            System.out.println("Current Belageusia population is " + total);
            System.out.println("Current Plebian population is " + plebianCount);
            System.out.println("Current Equidian population is " + equidianCount);
            System.out.println("Current Elitian population is " + elitianCount);
         * At each interim time epoch the population of Belageusia retracts with a death rate
         * randomly selected between 0% and 10%. If a plorg survives the purge, they have an
         * opportunity to move one class higher and/or one class lower. However, remember that
         * a plorgs name is final. It never changes.
         * For Plebeians this transition is determined by randomly selecting a CI in [0, 49].
         * If this new CI is les than 25 then the plorg remains a Plebeian, with this newly assigned CI,
         * and their debt increases 3.7%. If this new CI is in [25, 49], the Plebeian ascends to a
         * Equidian, with this newly assigned CI, their debt is forgiven, but taxes of $20 are assessed.
         * For Equidians this is determined by randomly selecting a CI in [0,100].
         * If this new CI is in [25, 75] then the plorg remains a Equidian, with this newly assigned CI,
         * but their taxes are increased 6.1%.
         * If this new CI is in [0, 24] then the plorg becomes a Plebeian, with this newly assigned CI,
         * their taxes are forgiven, but they are burdened with a debt of $10.00.
         * If this new CI is in [76, 100] then the plorg becomes a Plebeian, with this newly assigned CI,
         * but their taxes are increased 6.1%. However, they are bewtowed a wealth of $30.00.
         * For Eletians this is determined by randomly selecting a CI in [51, 100].
         * If this new CI is greater than 76 then the plorg remains an Eletian, with this newly assigned CI,
         * their taxes increase 6.1% and their wealth increases 4.9%. If this new CI is in [51, 75],
         * then this plorg becomes an Equidian, with this newly assigned CI, their wealth is eliminated,
         * and their taxes are increased 6.1%.
         * At each time epoch, the population of Belageusia at a birth rate randomly selected between 0% and 10%.
         * A randomly chosen number between 0-100 determines each newly born plorg?s stature.
         * If this random number is in the range 0-24, create a new Plebeian. In the range 25-75, create a new Equidian,
         * and if in the range 76-100, create a new Elitian.
        public void epoch()
            ArrayList newPlebians = new ArrayList();
            ArrayList newEquidians = new ArrayList();
            ArrayList newEletians = new ArrayList();
            Iterator it;
            Plorg plorg;
            int deathRate;
            double deathCount;
            int birthRate;
            double birthCount;
            int population;
            int subClass;
            int newCI;
            int kill;
            epochs++;
            System.out.println("Epoch = " + epochs);
            printPopulation();
            population = plebians.size() + equidians.size() + elitians.size();
            // The death rate is random 0 to 10%
            deathRate = random.nextInt(11);
            // work out the death count. population is cast to a double to avoid rounding errors
            deathCount = (double)population * deathRate / 100;
            // round up the result. We do this as once the population falls below 10
            // we would never kill anything
            deathCount = Math.ceil(deathCount);
            // We now work out the birth rate based on the population before we kill
            // anything otherwise the population tends to go down and down
            // The birth rate is random 0 to 10%
            birthRate = random.nextInt(11);
            // work out the birth count. population is cast to a double to avoid rounding errors
            birthCount = Math.ceil((double)population * birthRate / 100);
            // As with the deathCount round up the result.
            // We do this as once the population falls too low we would never create any more
            birthCount = Math.ceil(birthCount);
            System.out.println("About to kill " + deathRate + "% which is " + deathCount + " Plorgs out of " + population);
            for(int i=0; i<deathCount; i++)
                // get a random number between 0 and 2
                kill = random.nextInt(population);
                population--;
                // kill the specified Plorg
                if( kill < plebians.size() )
                    // kill a random Plebian
                    plebians.remove( random.nextInt(plebians.size()) );
                else if( kill < plebians.size() + equidians.size() )
                    // kill a random Equidian
                    equidians.remove( random.nextInt(equidians.size()) );
                else
                    // kill a random Elitian
                    elitians.remove( random.nextInt(elitians.size()) );
            System.out.println("Transitioning Plebians");
            // Transition period for Plebians
            it = plebians.iterator();
            while ( it.hasNext() )
                plorg = (Plorg) it.next();
                // select a new CI from 0 to 49 at random
                newCI = random.nextInt(50);
                plorg.setCI(newCI);
                if( newCI < 25 )
                    // Oh dear, this one stays as a Plebian; increase its dept by 3.7%
                    plorg.setDept( plorg.getDept() * 1.037 );
                else
                    // Congratulations this one is now an Equidian
                    newEquidians.add(plorg);
                    // remove from the Plebian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    plorg.setDept(0);
                    plorg.setTaxes(20);
            System.out.println("Transitioning Equidians");
            // Transition period for Equidians
            it = equidians.iterator();
            while ( it.hasNext() )
                plorg = (Plorg) it.next();
                // select a new CI from 0 to 100 at random
                newCI = random.nextInt(101);
                plorg.setCI(newCI);
                if( newCI < 25 )
                    // Oh dear, this one becomes a Plebian
                    newPlebians.add(plorg);
                    // remove from the Equidian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    plorg.setDept( 10 );
                    plorg.setTaxes(0);
                else if( newCI < 25 )
                    // This one stays as an Equidian; increase its taxes by 6.1%
                    plorg.setTaxes( plorg.getTaxes() * 1.061 );
                else
                    // Congratulations this one is now an Eletian
                    newEletians.add(plorg);
                    // remove from the Equidian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    plorg.setWealth(30);
                    // Increase its taxes by 6.1%
                    plorg.setTaxes( plorg.getTaxes() * 1.061 );
            System.out.println("Transitioning Elitians");
            // Transition period for Eletians
            it = plebians.iterator();
            while ( it.hasNext() )
                plorg = (Plorg) it.next();
                // Always increase taxes by 6.1%
                plorg.setTaxes( plorg.getTaxes() * 1.061 );
                // select a new CI from 51 to 100 at random
                newCI = 51 + random.nextInt(50);
                plorg.setCI(newCI);
                if( newCI > 76 )
                    // This one stays as an Eletian; increase its wealth by 4.9%
                    plorg.setWealth( plorg.getWealth() * 1.049 );
                else
                    // Oh dear, this one becomes an Equidian
                    newEquidians.add(plorg);
                    // remove from the Plebian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    // emove its wealth
                    plorg.setWealth(0);
            // now assign the Plorgs that are transitioning
            plebians.addAll(newPlebians);
            equidians.addAll(newEquidians);
            elitians.addAll(newEletians);
            System.out.println("Creating " + birthRate + "% new Plorgs from " + population + " which is " + birthCount);
            //create the new Plorgs
            for (int i = 0; i < birthCount; i++)
                // get a random number between 0 and 100
                subClass = random.nextInt(101);
                // create the specified Plorg
                if( subClass <= 24 )
                    plorg = Plorg.createPlebian();
                    plebians.add(plorg);
                else if( subClass >= 25 && subClass <= 75 )
                    plorg = Plorg.createEquidian();
                    equidians.add(plorg);
                else
                    plorg = Plorg.createElitian();
                    elitians.add(plorg);
        public static class Plorg
            /** Identifier used to generate unique names */
            private static int id = 0;
            /** The Plorgs name */
            private final String name;
            /** The level of wealth for this Plorg */
            private double wealth = 0;
            /** The level of dept for this Plorg */
            private double dept = 0;
            /** The level of taxes for this Plorg */
            private double taxes = 0;
            /** This Plorgs contentment index */
            private int ci = 0;
            /** Create a new Plorg with the given CI.
             * This is a private constructor. The only way for a program to
             * create new Plorgs is by calling either createPlebian(),
             * createEquidian() or createElitian().
             * @param ci
            private Plorg(int ci)
                // Generate a unique name and iincrement the ID
                this.name = "Plorg" + id++;
                // assign the CI
                this.ci = ci;
             * Create a new Plebian.
             * Plebeians have a contentment index in [0, 24].
             * Each new Plebeian is welcomed with a contentment index of 2 and burdened
             * with a debt of $10.00. Plebeians never manage to break even, so they have
             * no taxes imposed upon them. Furthermore, since they can never get out debt,
             * they cannot accumulate any wealth.
             * @return a new Plebian.
            public static Plorg createPlebian()
                Plorg plebian;
                plebian = new Plorg(2);
                plebian.setDept(10);
                return plebian;
             * Create a new Equidian
             * Equidians have a contentment index in [25, 75].
             * Each new Equidian is welcomed with a contentment index of 50 and burdened
             * with taxes of $20.00. Equidians have taxes imposed upon them. Furthermore,
             * since they do manage to break even, they have no debt. However, since they
             * only manager to break even, they do not accumulate any wealth.
             * @return a new Equidian.
            public static Plorg createEquidian()
                Plorg equidian;
                equidian = new Plorg(50);
                equidian.setTaxes(20);
                return equidian;
             * Create a new Elitian.
             * Elitians have a contentment index in [76, 100].
             * Each new Elitian is welcomed with a contentment index of 87 and burdened
             * with taxes of $20.00, but also provided with a ?silver spoon? of $30.00 in
             * accumulated wealth. Elitians manage to expand upon their wealth, so they
             * have taxes imposed upon them. Furthermore, since they are accumulating
             * wealth, they have no debt.
             * @return a new Elitian.
            public static Plorg createElitian()
                Plorg equidian;
                equidian = new Plorg(87);
                equidian.setWealth(30);
                equidian.setTaxes(20);
                return equidian;
             * Returns this Plorgs name.
            public String getName()
                return name;
             * Returns the CI of this Plorg.
            public int getCI()
                return ci;
             * Set the new Contentment index for this Plorg
             * @param ci
            public void setCI(int ci)
                this.ci = ci;
             * Returns the Dept of this Plorg
             * @return
            public double getDept()
                return dept;
             * Set the dept of this Plorg.
             * @param dept - the new dept for the Plorg.
            public void setDept(double dept)
                this.dept = dept;
             * Returns the wealth of this Plorg.
            public double getWealth()
                return wealth;
             * Sets the wealth of this Plorg.
             * @param wealth - the new wealth of this Plorg.
            public void setWealth(double wealth)
                this.wealth = wealth;
             * Returns the taxes of this Plorg.
            public double getTaxes()
                return taxes;
             * Set the taxes of this Plorg.
             * @param taxes - the new taxes for this Plorg.
            public void setTaxes(double taxes)
                this.taxes = taxes;
             * Check for equality. If the object specified is a Plorg with the same name as this
             * Plorg they are deemed to be equal.
             * @param o - The object to check
            public boolean equals(Object o)
                if ( this == o ) return true;
                if ( !(o instanceof Plorg) ) return false;
                final Plorg plorg = (Plorg) o;
                if ( name != null ? !name.equals(plorg.name) : plorg.name != null ) return false;
                return true;
             * Create a Hash Code for this Plorg
            public int hashCode()
                return (name != null ? name.hashCode() : 0);
    }

  • Problem in writing this program

    Please can anyone help me in writing this program, i am a student 
    Write a C++ program that reads a real variable x, integer variable N, and computes its exponential e<sup>x</sup> using the formula:
     Ex =  1 + x +
    x^2/2! + x^3/31 + x^4/4! + x^5/5 +...+ x^N/N!  (for N ≤ 10).
    Your program should define a function that computes factorial, which is called in the main function.
    Thanks

    Hi Kanayo
    The following program does
          total = x*0 +  x*1 + x*2 + x*3 + x*4 ...+x*N
    You may modify it for your formula. Use a recursive function or 'for' loop to compute a factorial.
    Regards
    Chong
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    int N;
    double x;
    float Fn( int n)
     double total=0.0;
     if (n<N)total= Fn(n+1);
     return(total+=x*n);
    int main()
     //double x;
     //int N;
     cout<<"Enter x: "; cin >>x;
     cout<<"Enter N: "; cin >>N;
     double total=Fn(0);
     cout<<total<<"\n";

  • Hi how to improve performence of this program

    Hi all,
    How to improve the performence of this program.....................
    REPORT z03_gil010 NO STANDARD PAGE HEADING LINE-SIZE 130.
                                 INCLUDE                                 *
    INCLUDE: z00_bci010.                   " Gestion des anomalies.
                          Déclaration des données                        *
                       Tables de la bases de données                     *
    TABLES:
            ekpo,        " Poste document d'achat.
            lfa1,        " Base fournisseurs (généralités).
            marc,        " Données division de l'article.
            z03_bw_cmp1,
            eord,        "Répertoire des sources appro. Achats
            eina,        "Fiche infos-achats - données générales
            t024,        "Groupes d'acheteurs
            tvarv.                                              "FAE17345+
                       Déclaration des données internes                  *
    Déclaration de la table interne qui permet de recuperer les mois.
    DATA: BEGIN OF itb_months OCCURS 12.
            INCLUDE STRUCTURE t247.
    DATA: END OF itb_months.
    Table pour récupération d'infos sur les divisions
    DATA: BEGIN OF itb_t001w OCCURS 0,
            werks LIKE t001w-werks,
            fabkl LIKE t001w-fabkl," Clé du calendrier d'entreprise
          END OF itb_t001w.
    Déclaration de la table interne contenant les infos sur l'adresse du
    fournisseur.
    DATA: BEGIN OF itb_adresse OCCURS 0,
            lifnr LIKE lfa1-lifnr,           " Numéro de compte fournisseur.
            name1 LIKE lfa1-name1,                              " Nom 1.
            name2 LIKE lfa1-name2,                              " Nom 2.
            name3 LIKE lfa1-name3,                              " Nom 3.
            name4 LIKE lfa1-name4,                              " Nom 4.
            stras LIKE lfa1-stras,           " N° de rue et nom de la rue.
            pstlz LIKE lfa1-pstlz,           " Code postal.
            ort01 LIKE lfa1-ort01,           " Localité.
            pfach LIKE lfa1-pfach,           " Boîte postale.
            pstl2 LIKE lfa1-pstl2,           " Code de la boîte postale.
            land1 LIKE lfa1-land1,           " Clé de pays.
            landx LIKE t005t-landx,          " Pays.
            spras LIKE lfa1-spras,           " Code langue
    END OF itb_adresse.
    Déclaration d'une table interne pour les informations sur les
    prévisions de commande.
    DATA: BEGIN OF itb_prev_cde OCCURS 0,
            werks LIKE marc-werks,            " Division
            idnlf LIKE eina-idnlf,            " ADDsde ref article frn
            lifnr LIKE eord-lifnr,            " N° fournisseur.
            ekgrp LIKE marc-ekgrp,            " Groupe d'acheteurs
            dispo LIKE marc-dispo,            " Code gestionnaire MRP
            matnr LIKE eord-matnr,            " Article.
            maktx LIKE makt-maktx,            " Désignation article.
            bstmi LIKE marc-bstmi,            " Quantité de commande.
            men00 LIKE plaf-gsmng,            " Quantité du mois en cours M.
            men01 LIKE plaf-gsmng,            " Quantité pour le mois M+1.
            men02 LIKE plaf-gsmng,            " Quantité pour le mois M+2.
            men03 LIKE plaf-gsmng,            " Quantité pour le mois M+3.
            men04 LIKE plaf-gsmng,            " Quantité pour le mois M+4.
            men05 LIKE plaf-gsmng,            " Quantité pour le mois M+5.
            men06 LIKE plaf-gsmng.            " Quantité pour le mois M+6.
    DATA: END OF itb_prev_cde.
    Structure de travail pour les commandes convernant les PFC
    DATA str_pca_pfc  LIKE itb_prev_cde.
    *add sde
    DATA str_eord_pfc  LIKE itb_prev_cde.
    Structure de travail pour les prévisons PFC
    DATA str_prev_pfc LIKE itb_prev_cde.
    Déclaration d'une table interne pour les informations sur le
    portefeuille des commandes d'achat.
    DATA: BEGIN OF itb_pca OCCURS 0,
            werks LIKE ekpo-werks,    " Division
            idnlf LIKE eina-idnlf,     " ADDsde ref article frn
            lifnr LIKE eord-lifnr,    " N° fournisseur.
            ekgrp LIKE marc-ekgrp,    " Groupe d'acheteurs
            dispo LIKE marc-dispo,    " Code gestionnaire MRP
            matnr LIKE eord-matnr,    " Article.
            maktx LIKE makt-maktx,    " Désignation article.
            ebeln LIKE ekes-ebeln,    " Numéro du document d'achat.
            ebelp LIKE ekes-ebelp,    " Numéro de poste du document d'achat.
            slfdt LIKE eket-slfdt,    " Date de livraison statistique
            eindt LIKE ekes-eindt,    " Date de livraison indiquée dans la
                                      " confirmation de la cde.
            menge LIKE ekes-menge,    " Quantité indiquée dans la confirma-
                                      " tion de la commande.
            attdu LIKE eket-wemng,    " Portefeuille fournisseur.
            netpr LIKE ekpo-brtwr,    " Prix net du document d'achat dans
                                      " la devise du document.
            rtard TYPE i,             " Retard en jours ouvres.
            wemng LIKE eket-wemng,    " Quantité de l'entrée de marchandise.
            bldat LIKE mkpf-bldat,    " Date inscrite sur la pièce/sur le
                                      " document.
            qtran LIKE ekes-menge,    " Quantité en transit.
            dtran LIKE ekes-eindt.    " Date du dernier avis de transit.
    DATA: END OF itb_pca.
    DATA: w_i TYPE i,                "Compteur
          w_i_char(1) TYPE c,        "Texte pour récupérer compteur
          w_nm_zone(20) TYPE c,      "Nom zone pour assign au field-symbols
          w_nb_j TYPE i,             "Nb de jours ouvrés jusqu'à fin mois
          w_nb_j_tot TYPE i.         "Nb de jours ouvrés du mois
    FIELD-SYMBOLS:       TYPE ANY.
    Déclaration d'une table contenant les fiches info achat.
    DATA: BEGIN OF itb_eina OCCURS 0,
            matnr LIKE eina-matnr,
            lifnr LIKE eina-lifnr,
            idfnl LIKE eina-idnlf.
    DATA: END OF itb_eina.
    Déclaration d'une table contenant les infos groupe acheteur.
    *DATA: BEGIN OF itb_t024 OCCURS 0,
           ekgrp LIKE t024-ekgrp,
           eknam LIKE t024-eknam,
           ektel LIKE t024-ektel,
           telfx LIKE t024-telfx.
    *DATA: END OF itb_t024.
    Déclaration d'une table pour le transfert du fichier.
    DATA: BEGIN OF itb_transfert OCCURS 0,
            col00(8),                 "division
            col00bis(20),             "Reference article
            col01(18),                "No article
            col02(45),                "libelle article
            col021(17),               "Groupe acheteur
            col022(13),               "gestionnaire
            col03(17),                "qte commandée ou No de commande
            col04(13),                "Mois 1 ou No poste cde
            col05(20),                "Mois 2 ou délai initial
            col06(33),                "Mois 3 ou délai négocié
            col07(13),                "Mois 4 ou qté cdée
            col08(13),                "Mois 5 ou qté attendue
            col09(13),                "Mois 6 ou Montant attendu
            col10(13),                "Mois 7 ou retard
            col11(13),                "qte partielle livree
            col12(13),                "date livraison partielle
            col13(13),                "qté en transit
            col14(13).                "date
    DATA: END OF itb_transfert.
    Déclaration d'une table contenant la liste des fournisseurs.
    DATA: BEGIN OF itb_lifnr OCCURS 0,
            werks LIKE marc-werks,
            idfnl LIKE eina-idnlf,
            lifnr LIKE eord-lifnr,
            ekgrp LIKE marc-ekgrp,
            spras LIKE lfa1-spras,
            eknam LIKE t024-eknam,
            ektel LIKE t024-ektel,
            telfx LIKE t024-telfx.
    DATA: END OF itb_lifnr.
    Déclaration d'une structure pour la selection dans la table MSEG.
    DATA : BEGIN OF itb_mseg OCCURS 0,
             mblnr LIKE mseg-mblnr,
             mjahr LIKE mseg-mjahr,
             ebeln LIKE mseg-ebeln,
             ebelp LIKE mseg-ebelp,
           END OF itb_mseg.
    déclaration d'une structure pour la selection dans EKPO.
    DATA : BEGIN OF itb_ekpo OCCURS 0,
             lifnr LIKE ekko-lifnr,
             ebeln LIKE ekpo-ebeln,
             ebelp LIKE ekpo-ebelp,
             menge LIKE ekpo-menge,
             bpumz LIKE ekpo-bpumz,
             bpumn LIKE ekpo-bpumn,
             matnr LIKE ekpo-matnr,
             werks LIKE ekpo-werks,
             netpr LIKE ekpo-netpr,
             peinh LIKE ekpo-peinh,  "Base de prix FAE17345+
             ekgrp LIKE ekko-ekgrp,   "AFT++
             dispo LIKE marc-dispo,   "AFT++
           END OF itb_ekpo.
    déclaration d'une structure pour la selection dans EKPO.
    DATA : BEGIN OF itb_ekko OCCURS 0,
             ebeln LIKE ekko-ebeln,
             lifnr LIKE ekko-lifnr,
             spras LIKE ekko-spras,
           END OF itb_ekko.
    déclaration d'une structure pour la selection dans EKES.
    DATA : BEGIN OF itb_ekes OCCURS 0,
             ebeln LIKE eket-ebeln,
             ebelp LIKE eket-ebelp,
             ebtyp LIKE ekes-ebtyp,
             eindt LIKE ekes-eindt,
             menge LIKE ekes-menge,
             dabmg LIKE ekes-dabmg,
             etens LIKE ekes-etens,
           END OF itb_ekes.
    déclaration d'une structure pour la selection dans EKET
    DATA : BEGIN OF itb_eket OCCURS 0,
             ebeln LIKE eket-ebeln,
             ebelp LIKE eket-ebelp,
             menge LIKE eket-menge,
             wemng LIKE eket-wemng,
             eindt LIKE eket-eindt,
             slfdt LIKE eket-slfdt,
           END OF itb_eket.
    déclaration d'une structure pour la selection dans MKPF.
    DATA : BEGIN OF itb_mkpf OCCURS 0,
             mblnr LIKE mkpf-mblnr,
             mjahr LIKE mkpf-mjahr,
             bldat LIKE mkpf-bldat,
           END OF itb_mkpf.
    Déclaration d'une structure pour la sélection dans EORD.
    DATA : BEGIN OF itb_eord OCCURS 0,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
             lifnr LIKE eord-lifnr,
             ekgrp LIKE marc-ekgrp,
             dispo LIKE marc-dispo,                             "DE3K924352
             disls LIKE marc-disls,
             bstfe LIKE marc-bstfe,
             bstrf LIKE marc-bstrf,
             bstmi LIKE marc-bstmi,
             bstma LIKE marc-bstma,
           END OF itb_eord.
    DATA : BEGIN OF itb_eordw OCCURS 0.
            INCLUDE STRUCTURE itb_eord.
    DATA : END OF itb_eordw.
    Déclaration d'une structure pour la sélection dans MAKT.
    DATA : BEGIN OF itb_makt OCCURS 0,
             matnr LIKE makt-matnr,
             spras LIKE makt-spras,
             maktx LIKE makt-maktx,
           END OF itb_makt.
    Déclaration d'une structure pour la sélection dans EBAN.
    DATA : BEGIN OF itb_eban OCCURS 0,
             matnr LIKE eban-matnr,
             werks LIKE eban-werks,
             flief LIKE eban-flief,
             lfdat LIKE eban-lfdat,
             menge LIKE eban-menge,
             bsmng LIKE eban-bsmng,
             webaz LIKE eban-webaz,
             ekgrp LIKE eban-ekgrp,
             ebeln LIKE eban-ebeln,
             banfn LIKE eban-banfn,
             bnfpo LIKE eban-bnfpo, "DB3K900702+
           END OF itb_eban.
    Déclaration d'une structure pour la sélection dans PLAF.
    DATA : BEGIN OF itb_plaf OCCURS 0,
             plnum LIKE plaf-plnum, "DB3K900702+
             matnr LIKE plaf-matnr,
             plwrk LIKE plaf-plwrk,
             flief LIKE plaf-flief,
             pedtr LIKE plaf-pedtr,
             gsmng LIKE plaf-gsmng,
             webaz LIKE plaf-webaz,
           END OF itb_plaf.
    Déclaration d'une structure pour la sélection dans MARC.
    DATA : BEGIN OF itb_marc OCCURS 0,
             matnr LIKE marc-matnr,
             werks LIKE marc-werks,
             disls LIKE marc-disls,
             bstrf LIKE marc-bstrf,
             bstmi LIKE marc-bstmi,
             bstma LIKE marc-bstma,
             bstfe LIKE marc-bstfe,
             ekgrp LIKE marc-ekgrp,
             dispo LIKE marc-dispo,
           END OF itb_marc.
    DATA : BEGIN OF itb_marc_eord OCCURS 0,
              matnr LIKE marc-matnr,
              werks LIKE marc-werks,
              strgr LIKE marc-strgr,   "groupe de stratégie planif
           END OF itb_marc_eord.
    DATA : BEGIN OF itb_z03_bw_cmp1 OCCURS 0,
             matnr LIKE z03_bw_cmp1-matnr,
             werks LIKE z03_bw_cmp1-werks,
             pdatu LIKE z03_bw_cmp1-pdatu,
             plnmg LIKE z03_bw_cmp1-plnmg,
           END OF itb_z03_bw_cmp1.
    Begin change BNI <DE3K937051>
    DATA : BEGIN OF itb_z03_bw_cmp2 OCCURS 0,
             matnr LIKE z03_bw_cmp2-matnr,
             werks LIKE z03_bw_cmp2-werks,
             pdatu LIKE z03_bw_cmp2-pdatu,
             plnmg LIKE z03_bw_cmp2-plnmg,
           END OF itb_z03_bw_cmp2.
    *End change BNI
    DATA : BEGIN OF str_index1,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
          END OF str_index1.
    DATA : BEGIN OF str_index2,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
          END OF str_index2.
    DATA : BEGIN OF str_index3_eord,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
          END OF str_index3_eord.
    DATA : BEGIN OF str_index4,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
          END OF str_index4.
    DATA : BEGIN OF str_index5,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
    END OF str_index5.
    DATA : BEGIN OF str_index6,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
    END OF str_index6.
    DATA : BEGIN OF str_index7,
             matnr LIKE eord-matnr,
             werks LIKE eord-werks,
    END OF str_index7.
    Déclaration des variables de debut et de fin de mois.
    DATA: w_debut_mois    LIKE sy-datum,
          w_debut_periode LIKE sy-datum,
          w_fin_mois      LIKE sy-datum,
          w_fin_periode   LIKE sy-datum.
    Déclaration des variables pour les dates.
    DATA: w_date0 LIKE sy-datum,
          w_date1 LIKE sy-datum,
          w_date2 LIKE sy-datum,
          w_date3 LIKE sy-datum,
          w_date4 LIKE sy-datum,
          w_date5 LIKE sy-datum,
          w_date6 LIKE sy-datum,
          w_datejour LIKE sy-datum,                             "FAE15269
          w_dat_da LIKE eban-lfdat,
          w_dat_op LIKE plaf-pedtr,
          w_mois0 LIKE t247-ltx,
          w_mois1 LIKE t247-ltx,
          w_mois2 LIKE t247-ltx,
          w_mois3 LIKE t247-ltx,
          w_mois4 LIKE t247-ltx,
          w_mois5 LIKE t247-ltx,
          w_mois6 LIKE t247-ltx,
          w_lendemain LIKE sy-datum.                            "FAE17345+
    Temoin d'un AR dans la commande d'achat.
    DATA: w_temoin_ar.
    Numéro de la confirmation de la commande
    DATA : w_etens LIKE ekes-etens.
    Déclaration des variables pour le nom des fichiers.
    DATA: w_nom_fichier LIKE rlgrap-filename,
          w_fichier LIKE rlgrap-filename,
          w_racine LIKE rlgrap-filename,
          w_file LIKE rlgrap-filename.
    Déclaration d'une table interne pour le transfert.
    DATA: BEGIN OF itb_trans OCCURS 0,
            w_ligne(320).
    DATA: END OF itb_trans.
    Déclaration d'une variable pour rechercher les enregistrements vides.
    DATA: w_compteur     TYPE i,
          w_compteur1    TYPE i,
          w_compteur2    TYPE i,
          w_retard       TYPE i,          " Retard en jours ouvres.
          w_trouve_pfc   TYPE c, "addsde
          w_trouve_pfs   TYPE c, "+DE3K937051
          w_trouve       TYPE c.
    *Index pour les LOOP
    DATA : w_index_ekpo LIKE sy-tabix,
           w_index_ekes LIKE sy-tabix,
           w_index_eket LIKE sy-tabix,
           w_index_mseg LIKE sy-tabix,
           w_index_eban LIKE sy-tabix,
           w_index_plaf LIKE sy-tabix,
           w_index_pca  LIKE sy-tabix,
           w_index_z03_bw_cmp1 LIKE sy-tabix,
           w_index_z03_bw_cmp2 LIKE sy-tabix."+DE3K937051
    RANGES : r_type_pfs   FOR marc-strgr.
    *fichier sur serveur +EDR231003
    DATA : w_chemin LIKE filename-fileintern,  "nom du fichier
           w_date_fichier(12) TYPE c,          "Date format DD_MM_AA
           w_csv(307) TYPE c.                  "ligne du fichier format CSV
    CONSTANTS: k_imputation_m LIKE eban-knttp VALUE 'M'.        "FAE19001+
                     Description de l écran de sélection                 *
                         Paramètres "UTILISATION"                        *
    Ouverture d'un block de sélection pour le(s) fournisseur(s).
    SELECTION-SCREEN BEGIN OF BLOCK block1 WITH FRAME TITLE text-bl1.
    Sélection division(s)
    SELECT-OPTIONS: s_werks FOR ekpo-werks.
    Sélection fournisseur(s).
    SELECT-OPTIONS: s_lifnr FOR lfa1-lifnr OBLIGATORY.
    Sélection du Groupe d'acheteur
    *SELECT-OPTIONS: s_ekgrp FOR marc-ekgrp.   "-FAE26446
    *SELECT-OPTIONS: s_dispo FOR marc-dispo.   "-FAE26446
    SELECTION-SCREEN END OF BLOCK block1.
    FAE 26446 : ajout
    SELECTION-SCREEN BEGIN OF BLOCK block3 WITH FRAME TITLE text-bl3.
    SELECTION-SCREEN BEGIN OF LINE.
    PARAMETER p_ekgrp RADIOBUTTON GROUP g3.
    SELECTION-SCREEN COMMENT 5(24) text-001 FOR FIELD p_ekgrp.
    SELECT-OPTIONS: s_ekgrp FOR marc-ekgrp.
    SELECTION-SCREEN END OF LINE.
    SELECTION-SCREEN BEGIN OF LINE.
    PARAMETER p_dispo RADIOBUTTON GROUP g3.
    SELECTION-SCREEN COMMENT 5(24) text-002 FOR FIELD p_dispo.
    SELECT-OPTIONS: s_dispo FOR marc-dispo.
    SELECTION-SCREEN END OF LINE.
    SELECTION-SCREEN END OF BLOCK block3.
    FAE 26446 : fin ajout
                           Paramètres "SYSTEME"                          *
    Saut de 2 lignes.
    SELECTION-SCREEN: SKIP 2.
    Ouverture d'un block de sélection pour l'adresse physique du fichier.
    SELECTION-SCREEN BEGIN OF BLOCK block2 WITH FRAME TITLE text-bl2.
    PARAMETERS: p_pc       RADIOBUTTON GROUP rad1 DEFAULT 'X',  "+EDR231003
                p_fic_pc LIKE rlgrap-filename.                  "+EDR231003
    SELECTION-SCREEN SKIP.                                      "+EDR231003
    PARAMETERS     : p_serve   RADIOBUTTON GROUP rad1,          "+EDR231003
                     p_fic_se LIKE filename-fileintern          "+EDR231003
                              DEFAULT 'Z03_PREV_COMMANDES'.     "+EDR231003
    SELECTION-SCREEN END OF BLOCK block2.
                           Logique de traitement                         *
                              INITIALIZATION                             *
    INITIALIZATION.
    Date du jour
      MOVE sy-datum TO w_datejour.                              "FAE15269
    Gestion des anomalies.
      MOVE text-lb1 TO w_lb_traitement.
      PERFORM f930_init USING sy-cprog '30'.
    Fin de la gestions des anomalies.
    Récuperation des mois dans la table interne 'ITB_MONTHS'.
      CALL FUNCTION 'MONTH_NAMES_GET'
           EXPORTING
                language              = sy-langu
           TABLES
                month_names           = itb_months
           EXCEPTIONS
                month_names_not_found = 1
                OTHERS                = 2.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      ENDIF.
    Récupération des differentes periodes.
      PERFORM f100_recuperation_date TABLES itb_months.
    Récupération du debut du mois.
      CONCATENATE sy-datlo(6) '01' INTO w_debut_mois.
      MOVE: w_debut_mois TO w_debut_periode.
    Récupération du dernier jour du mois.
      CALL FUNCTION 'LAST_DAY_OF_MONTHS'
           EXPORTING
                day_in            = sy-datlo
           IMPORTING
                last_day_of_month = w_fin_mois
           EXCEPTIONS
                day_in_no_date    = 1
                OTHERS            = 2.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
              WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      ENDIF.
                              TOP-OF-PAGE                                *
    TOP-OF-PAGE.
      CALL FUNCTION 'Z_00_BC_TOP_OF_PAGE'
           EXPORTING
                p_linsz   = k_ligne
                p_pagno   = sy-pagno
                p_prog    = sy-cprog
                p_projet  = k_projet
                p_societe = k_societe
                p_sujet   = sy-title.
                              END-OF-PAGE                                *
    END-OF-PAGE.
                            AT SELECTION-SCREEN                          *
    FAE 26446 : ajout
    AT SELECTION-SCREEN ON BLOCK block3.
      IF NOT ( s_ekgrp IS INITIAL )
      AND  NOT ( s_dispo IS INITIAL ).
        MESSAGE e394(z03_mm).
      ENDIF.
      IF p_ekgrp = 'X'.
        IF s_ekgrp IS INITIAL.
          MESSAGE e395(z03_mm).
        ENDIF.
      ELSE.
        IF s_dispo IS INITIAL.
          MESSAGE e396(z03_mm).
        ENDIF.
      ENDIF.
    fae26446 fin ajout
    AT SELECTION-SCREEN ON BLOCK block2.
      IF p_pc = 'X'.
        IF p_fic_pc IS INITIAL.
    *Attention, il n'y a aucune adresse de sauvegarde pour le(s) fichier(s)
          MESSAGE e021(z03_mm).
        ENDIF.
      ELSE.
        IF p_fic_se IS INITIAL.
    *Attention, il n'y a aucune adresse de sauvegarde pour le(s) fichier(s)
          MESSAGE e021(z03_mm).
        ENDIF.
      ENDIF.
    Création du matchcode pour la selection du fichier local.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_fic_pc.
      CALL FUNCTION 'WS_FILENAME_GET'
           EXPORTING
                def_filename     = p_fic_pc
                def_path         = 'C:'
                mask             = text-ma1
                mode             = 'S'
                title            = text-sel
           IMPORTING
                filename         = p_fic_pc
           EXCEPTIONS
                inv_winsys       = 1
                no_batch         = 2
                selection_cancel = 3
                selection_error  = 4
                OTHERS           = 5.
      IF sy-subrc NE 0 AND sy-subrc NE 3.
        MESSAGE e032(z03_mm).
      ENDIF.
                            START-OF-SELECTION                           *
    START-OF-SELECTION.
      PERFORM select_donnees.
    =================================================
    Liste des ARTICLES impactés pour les prévisions *
    =================================================
    ===================================
    PORTEFEUILLE DE COMMANDES D'ACHAT *
    ===================================
    Construction itb_pca à partir de EKKO/EKPO.
      w_index_ekpo  = 1.
      w_index_ekes  = 1.
      w_index_eket  = 1.
      w_index_mseg  = 1.
    SORT itb_ekko BY ebeln.           "-FAE26446
      SORT itb_ekpo BY ebeln ebelp.
      SORT itb_makt BY matnr spras.
      SORT itb_eket BY ebeln ebelp.
      SORT itb_ekes BY ebeln ebelp.
      SORT itb_mseg BY ebeln ebelp.
      SORT itb_mkpf BY mblnr mjahr.
      SORT itb_marc BY matnr werks.                             "+FAE26446
    FAE 26446 remplacement
    LOOP AT itb_ekko.
       LOOP AT itb_ekpo.
               FROM w_index_ekpo.
         IF itb_ekko-ebeln = itb_ekpo-ebeln.
      LOOP AT itb_ekpo.
        READ TABLE itb_marc WITH KEY
           matnr = itb_ekpo-matnr
           werks = itb_ekpo-werks BINARY SEARCH.
        CHECK sy-subrc = 0.
    FAE 26446 fin remplacement
        itb_pca-ebeln = itb_ekpo-ebeln.
        itb_pca-ebelp = itb_ekpo-ebelp.
      itb_pca-lifnr = itb_ekko-lifnr.   "-FAE26446
        itb_pca-lifnr = itb_ekpo-lifnr.                         "+FAE26446
        itb_pca-ekgrp = itb_ekpo-ekgrp.                         "+FAE26446
        itb_pca-dispo = itb_ekpo-dispo.                         "+FAE26446
        itb_pca-matnr = itb_ekpo-matnr.
        itb_pca-werks = itb_ekpo-werks.
      Recherche du libellé article
        READ TABLE itb_makt
                   WITH KEY matnr = itb_ekpo-matnr
                            spras = text-fra
                   BINARY SEARCH.
        IF sy-subrc = 0.
          itb_pca-maktx = itb_makt-maktx.
        ELSE.
          READ TABLE itb_makt
                    WITH KEY matnr = itb_ekpo-matnr
                             spras = text-ang
                    BINARY SEARCH.
          IF sy-subrc = 0.
            itb_pca-maktx = itb_makt-maktx.
          ENDIF.
        ENDIF.
        IF NOT itb_ekpo-bpumn IS INITIAL.
          itb_pca-menge = itb_ekpo-menge * itb_ekpo-bpumz /
                                           itb_ekpo-bpumn.
        ENDIF.
      Sélect° ds la table EKES des dates de livraisons et des qtés
      en transit
        CLEAR w_temoin_ar.
        CLEAR w_etens.
        LOOP AT itb_ekes
                FROM w_index_ekes.
          IF  itb_ekes-ebeln = itb_ekpo-ebeln
          AND itb_ekes-ebelp = itb_ekpo-ebelp.
            IF itb_ekes-ebtyp = text-arn.
              itb_pca-eindt = itb_ekes-eindt.
              w_temoin_ar = 'X'.
            ELSE.
            Si c'est une qté en transit alors on recupere
            la quantité et la date.
              IF itb_ekes-dabmg < itb_ekes-menge.
                itb_pca-qtran = itb_pca-qtran + itb_ekes-menge -
                                itb_ekes-dabmg.
              ENDIF.
              IF itb_ekes-etens > w_etens.
                w_etens = itb_ekes-etens.
                itb_pca-dtran = itb_ekes-eindt.
              ENDIF.
            ENDIF.
          ELSEIF itb_ekes-ebeln > itb_ekpo-ebeln
          OR ( itb_ekes-ebeln = itb_ekpo-ebeln
          AND itb_ekes-ebelp > itb_ekpo-ebelp ).
            w_index_ekes = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
      S'il n'y a pas d'AR alors récupérat° de la date livraison dans EKET.
        LOOP AT itb_eket
                FROM w_index_eket.
          IF  itb_eket-ebeln = itb_ekpo-ebeln
          AND itb_eket-ebelp = itb_ekpo-ebelp.
            IF w_temoin_ar IS INITIAL.
              itb_pca-eindt = itb_eket-eindt.
            ENDIF.
            itb_pca-slfdt = itb_eket-slfdt.
          Calcul du portefeuille fournisseur à partir de la
          qté commandée et la qté reçue
            itb_pca-attdu = itb_pca-attdu + itb_eket-menge -
                            itb_eket-wemng.
          Calcul du montant du poste
            itb_pca-netpr = itb_ekpo-netpr * itb_pca-attdu.
            IF itb_ekpo-peinh NE 0.
              itb_pca-netpr = itb_pca-netpr / itb_ekpo-peinh.
            ENDIF.
          Calcul quantité réceptionnée.
            itb_pca-wemng = itb_pca-wemng + itb_eket-wemng.
          Calcul du retard en nombre de jours calendaires
          Le calcul du retard  ne doit pas prendre en compte
          le jour de livraison
            ADD 1 TO itb_eket-eindt.
            IF NOT itb_pca-attdu  IS INITIAL
            AND    itb_eket-eindt LT sy-datum.
            Calcul du retard en nombre de jours ouvrés
              CLEAR w_retard.
              CALL FUNCTION 'Z_00_BC_WORKDAYS_PER_PERIOD'
                   EXPORTING
                        date_deb = itb_eket-eindt
                        date_fin = sy-datum
                   IMPORTING
                        jours    = w_retard.
              itb_pca-rtard = itb_pca-rtard + w_retard .
            ENDIF.
          ELSEIF itb_eket-ebeln > itb_ekpo-ebeln
          OR (   itb_eket-ebeln = itb_ekpo-ebeln
          AND    itb_eket-ebelp > itb_ekpo-ebelp ).
            w_index_eket = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
      Recherche de la derniere date de livraison.
        LOOP AT itb_mseg
                FROM w_index_mseg.
          IF  itb_mseg-ebeln = itb_ekpo-ebeln
          AND itb_mseg-ebelp = itb_ekpo-ebelp.
            READ TABLE itb_mkpf
                       WITH KEY mblnr = itb_mseg-mblnr
                                mjahr = itb_mseg-mjahr
                       BINARY SEARCH.
            IF sy-subrc = 0.
              IF itb_mkpf-bldat > itb_pca-bldat.
                itb_pca-bldat = itb_mkpf-bldat.
              ENDIF.
            ENDIF.
          ELSEIF itb_mseg-ebeln > itb_ekpo-ebeln
          OR (   itb_mseg-ebeln = itb_ekpo-ebeln
          AND    itb_mseg-ebelp > itb_ekpo-ebelp ).
            w_index_mseg = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
        APPEND itb_pca.
        CLEAR itb_pca.
    FAE26446 suppression parag. suivant
         ELSEIF itb_ekpo-ebeln > itb_ekko-ebeln.
           w_index_ekpo = sy-tabix.
           EXIT.
         ENDIF.
       ENDLOOP.
    Fin FAE26446
      ENDLOOP.
    =========================
    PREVISIONS DE COMMANDES *
    =========================
      SORT itb_eord        BY matnr werks lifnr ekgrp.
      SORT itb_eban        BY matnr werks flief ekgrp.
      SORT itb_plaf        BY matnr plwrk flief.
      SORT itb_z03_bw_cmp1 BY matnr werks.
      SORT itb_z03_bw_cmp2 BY matnr werks."+DE3K937051
      SORT itb_pca         BY matnr werks lifnr.
      w_index_eban = 1.
      w_index_plaf = 1.
      w_index_z03_bw_cmp1 = 1.
      w_index_pca = 1.
      w_index_z03_bw_cmp2 = 1."+DE3K937051
    Remplissage de la table des prévisions de commande.
      LOOP AT itb_eord.
        CLEAR: str_prev_pfc,
               w_trouve.
        MOVE-CORRESPONDING itb_eord TO str_index1.
        MOVE-CORRESPONDING itb_eord TO str_index3_eord.
        MOVE-CORRESPONDING itb_eord TO itb_prev_cde.
      Recherche dans table division/article (MARC) afin de déterminer si
      article PFS (prod fabriqué à stock) ou PFC (Prod fabriqué sur cde)
        AT NEW werks.
          READ TABLE itb_marc_eord
                     WITH KEY matnr = itb_eord-matnr
                              werks = itb_eord-werks
                     BINARY SEARCH.
          IF sy-subrc NE 0.
            CLEAR itb_marc_eord.
          ENDIF.
        ENDAT.
    a - Prévisions pour les PFS : DA + OP *
    *Calcul des quantités de commande.
        IF itb_eord-disls = text-tl1.
          itb_prev_cde-bstmi =  itb_eord-bstfe.
        ELSEIF itb_eord-disls = text-tl2
        OR     itb_eord-disls = text-tl3.
          IF  itb_eord-bstrf NE 0
          AND itb_eord-bstmi = 0
          AND itb_eord-bstma = 0.
            itb_prev_cde-bstmi = itb_eord-bstrf.
          ELSEIF itb_eord-bstrf NE 0
          AND    itb_eord-bstmi NE 0.
            itb_prev_cde-bstmi = itb_eord-bstmi.
          ELSEIF itb_eord-bstrf = itb_eord-bstma
          AND    itb_eord-bstrf NE 0
          AND    itb_eord-bstmi = 0.
            itb_prev_cde-bstmi = itb_eord-bstma.
          ENDIF.
        ENDIF.
      si article PFS (Prod fabriqué à stock) recherche des
      demandes d'achat ou ordres planfiés
        IF itb_marc_eord-strgr IN r_type_pfs.
      Récupérat° calendrier de la division pour calcul correct lors de
      l'ajout de eban-webaz ou plaf-webaz jours ouvrés
          CLEAR w_trouve_pfs ."+DE3K937051
          READ TABLE itb_t001w
                     WITH KEY werks = itb_eord-werks
                     BINARY SEARCH.
          IF sy-subrc = 0.
            LOOP AT itb_eban
                    FROM w_index_eban.
              MOVE-CORRESPONDING itb_eban TO str_index2.
              IF str_index1 = str_index2.
                w_trouve_pfs = 'X'."+DE3K937051
              si qte commandées pour la DA  < quantité de la DA
                IF itb_eban-bsmng < itb_eban-menge.
                ajout de quantité de la DA - qte  commandée pour la DA
                  PERFORM affect_da.
                ENDIF.
              ELSEIF str_index2 > str_index1.
                w_index_eban = sy-tabix.
                EXIT.
              ENDIF.
            ENDLOOP.
          ENDIF.
        ajout des quantité des OP (ordres planifiés)
          LOOP AT itb_plaf
                  FROM w_index_plaf.
            MOVE-CORRESPONDING itb_plaf TO str_index4.
            str_index4-werks = itb_plaf-plwrk.
          str_index4-lifnr = itb_plaf-flief.
            IF str_index4 = str_index3_eord.
            Ajout de webaz jours ouvrés à pedtr
              CALL FUNCTION 'Z_03_MM_ADD_TO_FACTORYDATE'
                   EXPORTING
                        i_date        = itb_plaf-pedtr
                        i_calendar_id = itb_t001w-fabkl
                        i_nb_days     = itb_plaf-webaz
                   IMPORTING
                        o_date        = w_dat_op
                   EXCEPTIONS
                        conv_error    = 1
                        OTHERS        = 2.
              IF sy-subrc
       If forecasts found in Z03_BW_CMP2 for the article
       IF w_trouve_pfs = 'X'."-DE3K937602
    Recalculation prev month M in fct of Nb of wrought days of the month
        IF NOT itb_prev_cde-men00 IS INITIAL.
       one does not hold any more account of the day in progress
          w_lendemain = w_date0 + 1.
          CLEAR:w_nb_j,w_nb_j_tot.         "DE3K938206+
          CALL FUNCTION 'Z_00_BC_WORKDAYS_PER_PERIOD'
               EXPORTING
                    date_deb = w_lendemain
                    date_fin = w_fin_mois
               IMPORTING
                    jours    = w_nb_j.
          CALL FUNCTION 'Z_00_BC_WORKDAYS_PER_MONTH'
               EXPORTING
                    date  = w_lendemain
               IMPORTING
                    jours = w_nb_j_tot.
          itb_prev_cde-men00  = itb_prev_cde-men00 * w_nb_j / w_nb_j_tot
    *CLA DE3K925301 FAE27197
    *to round has the higher entirety
        itb_prev_cde-men00  = ceil( itb_prev_cde-men00 ). "DE3K938206-
        ENDIF.
       ENDIF."-DE3K937602
    *End change BNI
    b - Prévisions pour les PFC (Z03_BW_CMP1 puis rééquilibrage) *
      Recherche des previsions dans Z03_BW_CMP1
      si article PFC (Prod fabriqué sur cde) recherche des prévisions
        IF  NOT itb_marc_eord-strgr IN r_type_pfs.
          CLEAR str_prev_pfc.
          MOVE-CORRESPONDING itb_eord TO str_prev_pfc.
          CLEAR w_trouve_pfc .
          LOOP AT itb_z03_bw_cmp1
                  FROM w_index_z03_bw_cmp1.
            MOVE-CORRESPONDING itb_z03_bw_cmp1 TO str_index7.
            MOVE-CORRESPONDING itb_eord TO str_index6.
            IF str_index6 = str_index7.
          si on trouve des prévisions dans z03_bw_cmp1 pour la source
          d'appro eord alors c'est un article  PFC
              w_trouve_pfc = 'X'.
              CASE itb_z03_bw_cmp1-pdatu+0(6).
                WHEN w_date0+0(6).
                  str_prev_pfc-men00 = itb_z03_bw_cmp1-plnmg.
                WHEN w_date1+0(6).
                  str_prev_pfc-men01 = itb_z03_bw_cmp1-plnmg.
                WHEN w_date2+0(6).
                  str_prev_pfc-men02 = itb_z03_bw_cmp1-plnmg.
                WHEN w_date3+0(6).
                  str_prev_pfc-men03 = itb_z03_bw_cmp1-plnmg.
                WHEN w_date4+0(6).
                  str_prev_pfc-men04 = itb_z03_bw_cmp1-plnmg.
                WHEN w_date5+0(6).
                  str_prev_pfc-men05 = itb_z03_bw_cmp1-plnmg.
                WHEN w_date6+0(6).
                  str_prev_pfc-men06 = itb_z03_bw_cmp1-plnmg.
                WHEN OTHERS.
              ENDCASE.
            ELSEIF str_index7 > str_index6.
              w_index_z03_bw_cmp1 = sy-tabix.
              EXIT.
            ENDIF.
          ENDLOOP.
    *Begin change BNI
        Si des prévisions trouvées dans Z03_BW_CMP1 pour l'article
          IF w_trouve_pfc = 'X'.
          Recalcul prev mois M en fct du nb de jours ouvrés du mois
            IF NOT str_prev_pfc-men00 IS INITIAL.
            on ne tient plus compte du jour en cours
              w_lendemain = w_date0 + 1.
              CLEAR:w_nb_j,w_nb_j_tot.               "DE3K938206+
              CALL FUNCTION 'Z_00_BC_WORKDAYS_PER_PERIOD'
                   EXPORTING
                        date_deb = w_lendemain
                        date_fin = w_fin_mois
                   IMPORTING
                        jours    = w_nb_j.
              CALL FUNCTION 'Z_00_BC_WORKDAYS_PER_MONTH'
                   EXPORTING
                        date  = w_lendemain
                   IMPORTING
                        jours = w_nb_j_tot.
              str_prev_pfc-men00 = str_prev_pfc-men00 * w_nb_j / w_nb_j_tot.
    *CLA DE3K925301 FAE27197
    *arrondir a l'entier supèrieur
              str_prev_pfc-men00 = ceil( str_prev_pfc-men00 ).
            ENDIF.
          Equilibrage PFC : commande/prévision du mois
          Recherche COMMANDES cumulées pour M à M+6
            CLEAR str_pca_pfc.
            LOOP AT itb_pca
                    FROM w_index_pca.
              MOVE-CORRESPONDING itb_pca TO str_index5.
              IF str_index5 = str_index3_eord.
                IF NOT itb_pca-menge IS INITIAL.
                  CASE itb_pca-eindt+0(6).
                    WHEN w_date0+0(6).
                      IF itb_pca-eindt >= w_date0.
                      str_pca_pfc-men00 = str_pca_pfc-men00 + itb_pca-menge.
                      ENDIF.
                    WHEN w_date1+0(6).
                      str_pca_pfc-men01 = str_pca_pfc-men01 + itb_pca-menge.
                    WHEN w_date2+0(6).
                      str_pca_pfc-men02 = str_pca_pfc-men02 + itb_pca-menge.
                    WHEN w_date3+0(6).
                      str_pca_pfc-men03 = str_pca_pfc-men03 + itb_pca-menge.
                    WHEN w_date4+0(6).
                      str_pca_pfc-men04 = str_pca_pfc-men04 + itb_pca-menge.
                    WHEN w_date5+0(6).
                      str_pca_pfc-men05 = str_pca_pfc-men05 + itb_pca-menge.
                    WHEN w_date6+0(6).
                      str_pca_pfc-men06 = str_pca_pfc-men06 + itb_pca-menge.
                  ENDCASE.
                ENDIF."NOT itb_pca-menge IS INITIAL
              ELSEIF str_index5 > str_index3_eord.
                w_index_pca = sy-tabix.
                EXIT.
              ENDIF.
            ENDLOOP."itb_pca
    *. Equilibrer commande / prévision des mois : diminuer la quantité de
    prévision de chaque mois par le portefeuille de commande client du
    mois*. Si ce solde est négatif alors lui donner la valeur 0.
            w_i = 0.
          Ajustement commandes/prévisions pour les mois M à M+6
            WHILE w_i .
            Pour un mois, SI Prévisions > Commandes en cours
              IF .
              Prévisions = Prévisions - Commandes en cours
                 = 0.
              ENDIF.
            On passe au mois suivant
              w_i = w_i + 1.
            ENDWHILE.
            MOVE str_prev_pfc-men00 TO itb_prev_cde-men00.
            MOVE str_prev_pfc-men01 TO itb_prev_cde-men01.
            MOVE str_prev_pfc-men02 TO itb_prev_cde-men02.
            MOVE str_prev_pfc-men03 TO itb_prev_cde-men03.
            MOVE str_prev_pfc-men04 TO itb_prev_cde-men04.
            MOVE str_prev_pfc-men05 TO itb_prev_cde-men05.
            MOVE str_prev_pfc-men06 TO itb_prev_cde-men06.
          ENDIF.  "w_trouve_pfc = 'X'.
        ENDIF.
    *recherche du libellé article

    Hi,
    see this link, useful tips, links and transactions for best performance, by Anji.
    https://forums.sdn.sap.com/click.jspa?searchID=5967263&messageID=4260111
    Regards

  • Please help me to get a clue from this program

    I'm sorry to bother you with such stupid questions. I have to admit I'm just making my first steps in programming.
    So I have a program like this and don't understand how it works:
    // Masking sign extension.
    class HexByte {
    static public void main(String args[]) {
    char hex[] = {
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    byte b = (byte) 0xf1;
    System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
    Specifically, how could 0xf1 be represented in binary? As far as I know 11110001 contains negative value. Moreover 0xf1 in 10's base is 241, so how can I convert it to byte? Doin so, I'm gonna lose its value (since the byte range is from -128 to 127). And why do I need it? I even have no idea how the variable would look like in binary after converting to byte, not mentioning last part of this program.
    I would really appreaciate your help.
    Thank you for your time.

    AntShay wrote:
    Thank you so much for your help guys. Now I got just 2 more questions. First of all. I guess sign-extension works only with negative values. Is that correct? When sign-extension takes place and I shift any value to the right by any number of positions, does it fill in all the previous bits with *1s*? If you can, please, tell me how exactly this works.Java primitives are all signed, so sign extension is always at work for right bit shifts. However, if you were to look into the code, it has masked away the 4 most significant bits using bit-wise and operation. Alternatively, you may use the unsigned shift (+>>>+) operator.
    And by the way, is there any method to convert the value of byte to a binary string? I only figured that it might work this way: Integer.toBinaryString(b&0xff), but is there Byte.toBinaryString method or something?It is always okay to up cast, as sign extension will convert correctly. If you don't like the long integer output, you may do a substring() on the output. It is also not hard to roll your own.

  • Problem with this program

    I see this board is very young. Well I'm a high school freshman in a java programming class and i have a little problem with my homework.
    My source code is:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class DogsHumanAge extends JApplet
    implements ActionListener
    JTextField inputHumanyears, displayDogyears;
    public void init()
    JLabel labelHumanyears = new JLabel("Enter the dog's age in human years:",
    SwingConstants.RIGHT);
    inputHumanyears = new JTextField(5);
    JLabel labelDogyears = new JLabel("Dogyears = ", SwingConstants.RIGHT);
    displayDogyears = new JTextField(5);
    displayDogyears.setEditable(false);
    JButton go = new JButton("Compute age");
    go.addActionListener(this);
    Container c = getContentPane();
    c.setBackground(Color.white);
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(3, 2, 5, 5));
    p.add(labelHumanyears);
    p.add(inputHumanyears);
    p.add(labelDogyears);
    p.add(displayDogyears);
    c.add(p, BorderLayout.CENTER);
    c.add(go, BorderLayout.SOUTH);
    public void actionPerformed(ActionEvent e)
    int Humanyears = Integer.parseInt(inputHumanyears.getText());
    double Dogyears = calculateDogyears(Humanyears);
    DecimalFormat df = new DecimalFormat("00.0");
    displayDogyears.setText(df.format(Dogyears));
    private double calculateDogyears(int Humanyears, int Dogyears)
    return 13 + (int)(16.0 / 3.0 * (Dogyears - 1));
    The error message i get is:
    DogsHumanAge.java:42: calculateDogyears(int, int) cannot be applied to (int)
    double Dogyears = calulateDogyears(Humanyears);
    The intent of this program is to calculate the number of dog years from the given human years that is inputted into the input box.

    Ok I got the solution. A friend helped me out. I had to make a few minor changes. Now the program looks like:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class DogsHumanAge extends JApplet
    implements ActionListener
    JTextField inputDogYears, displayHumanYears;
    public void init()
    JLabel labelDogYears = new JLabel("Enter the dog's age in dog years:",
    SwingConstants.RIGHT);
    inputDogYears = new JTextField(5);
    JLabel labelHumanYears = new JLabel("Human years = ", SwingConstants.RIGHT);
    displayHumanYears = new JTextField(5);
    displayHumanYears.setEditable(false);
    JButton go = new JButton("Compute age");
    go.addActionListener(this);
    Container c = getContentPane();
    c.setBackground(Color.white);
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(3, 2, 5, 5));
    p.add(labelDogYears);
    p.add(inputDogYears);
    p.add(labelHumanYears);
    p.add(displayHumanYears);
    c.add(p, BorderLayout.CENTER);
    c.add(go, BorderLayout.SOUTH);
    public void actionPerformed(ActionEvent e)
    int dogYears = Integer.parseInt(inputDogYears.getText());
    double humanYears = calculateHumanYears(dogYears);
    DecimalFormat df = new DecimalFormat("00.0");
    displayHumanYears.setText(df.format(humanYears));
    private double calculateHumanYears(int dogYears)
    return 13 + (int)(16.0 / 3.0 * (dogYears - 1));
    Thanks to all that helped me!

  • Really need help on how to write this program some 1 plz help me out here.

    i am new to java and i confused on how to be writing this program.
    i have completed the Part 1 but i am stuck on Part 2 & 3 so it would would be really great if any 1 could help me out on how to write the program.
    Part I
    An algorithm describes how a problem is solved in terms of the actions to be executed, and it specifies the order in which the actions should be executed. An algorithm must be detailed enough so that you can "walk" through the algorithm with test data. This means the algorithm must include all the necessary calculations.
    Here is an algorithm that calculates the cost of a rectangular window. The
    total cost of a window is based on two prices; the cost of the glass plus the cost of the metal frame around the glass. The glass is 50 cents per
    square inch (area) and the metal frame is 75 cents per inch (perimeter).
    The length and width of the window will be entered by the user. The
    output of the program should be the length and width (entered by the user)
    and the total cost of the window.
    FORMULAS:
    area = length times width perimeter = 2 times (length plus width)
    Here is the corresponding algorithm:
    read in the length of the window in inches
    read in the width of the window in inches
    compute the area
    compute the cost of the glass (area times 50 cents)
    compute the perimeter
    compute the cost of the frame (perimeter times 75 cents)
    compute the total cost of the window (cost of glass plus cost of frame)
    display the length, width and total cost
    The next step would be to "desk check" the algorithm. First you would need to make up the "test data". For this algorithm, the test data would involve making up a length and a width, and then calculating the cost of the window based on those values. The results are computing by hand or using a calculator. The results of your test data are always calculated before translating your algorithm into a programming language. Here is an example of the test data for the problem given:
    length = 10
    width = 20
    area = 200, glass cost= 100.00 (area times 50 cents)
    perimeter = 60, frame cost = 45.00 (perimeter times 75 cents)
    total cost =145.00
    Once the test data is chosen, you should "walk" through the algorithm using the test data to see if the algorithm produces the same answers that you obtained from your calculations.
    If the results are the same, then you would begin translating your algorithm into a programming language. If the results are not the same, then you would attempt to find out what part of the algorithm is incorrect and correct it. It is also
    necessary to re-check your hand calculations.
    Each time you revise your algorithm, you should walk through it with your test data again. You keep revising your algorithm until it produces the same answers as your test data.
    ?Now write and submit a Java program that will calculate the cost of a rectangular window according to the algorithm explained. Be sure to prompt for input and label your output.?
    Part II
    Write, compile and execute a Java program that displays the following prompts:
    Enter an integer.
    Enter a second integer
    Enter a third integer.
    Enter a fourth integer.
    After each prompt is displayed, your program should use the nextint method of the Scanner class to accept a number from the keyboard for the displayed
    prompt. After the fourth integer has been entered, your program should calculate and display the average of the four integers and the value of the first integer entered raised to the power of the second integer entered. The average and result of raising to a power should be included in an appropriate messages
    (labels).
    Sample Test Data:
    Set 1: 100 100 100 100
    Set 2: 100 0 100 0
    Be sure to write an algorithm first before attempting to write the Java code. Walk through your algorithm with test data to be sure it works as anticipated.
    Part III
    Repeat Part lI but only calculate the average, not the power. This time, make sure to use the same variable name, number, for each of the four numbers input. Also use the variable sum for the sum of the numbers. (Hint: To do this, you may use the statement sum = sum + number after each number is read.)
    For Part 1 this is what i got
    import java.util.Scanner;
    public class Window
         public static void main(String[] args)
              double length, width, glass_cost, perimeter, frame_cost, area, total;
              Scanner keyboard = new Scanner (System.in);
              System.out.println("Enter the length of the window in inches");
              length = keyboard.nextInt();
              System.out.println("Enter the width of the window in inches");
              width = keyboard.nextInt();
              area = length * width;
              glass_cost = area * .5;
              perimeter = 2 * (length + width);
              frame_cost = perimeter * .75;
              total = glass_cost + frame_cost;
                   System.out.println("The Length of the window is " + length + "inches");
                   System.out.println("The Width of the window is " + length + "inches");
                   System.out.println("The total cost of the window is $ " + total);
         Enter the length of the window in inches
         5
         Enter the width of the window in inches
         8
         The Length of the window is 5.0inches
         The Width of the window is 5.0inches
         The total cost of the window is $ 39.5
    Press any key to continue . . .
    Edited by: Adhi on Feb 24, 2008 10:33 AM

    Adhi wrote:
    i am new to java and i confused on how to be writing this program.
    i have completed the Part 1 but i am stuck on Part 2 & 3 so it would would be really great if any 1 could help me out on how to write the program.Looks like homework to me.
    What have you written so far? Post it.
    Part I
    An algorithm describes how a problem is solved in terms of the actions to be executed, and it specifies the order in which the actions should be executed. An algorithm must be detailed enough so that you can "walk" through the algorithm with test data. This means the algorithm must include all the necessary calculations.
    Here is an algorithm that calculates the cost of a rectangular window. The
    total cost of a window is based on two prices; the cost of the glass plus the cost of the metal frame around the glass. The glass is 50 cents per
    square inch (area) and the metal frame is 75 cents per inch (perimeter).
    The length and width of the window will be entered by the user. The
    output of the program should be the length and width (entered by the user)
    and the total cost of the window.
    FORMULAS:
    area = length times width perimeter = 2 times (length plus width)
    Here is the corresponding algorithm:
    read in the length of the window in inches
    read in the width of the window in inches
    compute the area
    compute the cost of the glass (area times 50 cents)
    compute the perimeter
    compute the cost of the frame (perimeter times 75 cents)
    compute the total cost of the window (cost of glass plus cost of frame)
    display the length, width and total cost
    The next step would be to "desk check" the algorithm. First you would need to make up the "test data". For this algorithm, the test data would involve making up a length and a width, and then calculating the cost of the window based on those values. The results are computing by hand or using a calculator. The results of your test data are always calculated before translating your algorithm into a programming language. Here is an example of the test data for the problem given:
    length = 10
    width = 20
    area = 200, glass cost= 100.00 (area times 50 cents)
    perimeter = 60, frame cost = 45.00 (perimeter times 75 cents)
    total cost =145.00
    Once the test data is chosen, you should "walk" through the algorithm using the test data to see if the algorithm produces the same answers that you obtained from your calculations.
    If the results are the same, then you would begin translating your algorithm into a programming language. If the results are not the same, then you would attempt to find out what part of the algorithm is incorrect and correct it. It is also
    necessary to re-check your hand calculations.
    Each time you revise your algorithm, you should walk through it with your test data again. You keep revising your algorithm until it produces the same answers as your test data.
    &#147;Now write and submit a Java program that will calculate the cost of a rectangular window according to the algorithm explained. Be sure to prompt for input and label your output.&#148;
    Part II
    Write, compile and execute a Java program that displays the following prompts:
    Enter an integer.
    Enter a second integer
    Enter a third integer.
    Enter a fourth integer.
    After each prompt is displayed, your program should use the nextint method of the Scanner class to accept a number from the keyboard for the displayed
    prompt. After the fourth integer has been entered, your program should calculate and display the average of the four integers and the value of the first integer entered raised to the power of the second integer entered. The average and result of raising to a power should be included in an appropriate messages
    (labels).
    Sample Test Data:
    Set 1: 100 100 100 100
    Set 2: 100 0 100 0
    Be sure to write an algorithm first before attempting to write the Java code. Walk through your algorithm with test data to be sure it works as anticipated.So this is where you actually have to do something. My guess is that you've done nothing so far.
    Part III
    Repeat Part lI but only calculate the average, not the power. This time, make sure to use the same variable name, number, for each of the four numbers input. Also use the variable sum for the sum of the numbers. (Hint: To do this, you may use the statement sum = sum + number after each number is read.)Man, this specification writes itself. Sit down and start coding.
    One bit of advice: Nobody here takes kindly to lazy, stupid students who are just trying to con somebody into doing their homework for them. If that's you, better have your asbestos underpants on.
    %

  • Amend this Program

    I wan to amend this program so that I will be able to enter 6 lotto numbers. The program currently is randomly selecting 6 numbers but I want to enter the number not generate them any help please?
    Thank you!
    import javax.swing.*; // for the graphical user interface
    public class Play{
    public static void main(String[] args)
    final int TOPNUMBER = 49; // top # for the CA lottery
    final int POWERBALLTOP = 49; // top powerball # for CA lottery
         final int YES = 0; // for response from Dialog box
         int response; // holds response from Dialog box
         // create an array to hold a herd of lotto numbers
    LottoNumber[] lottoNumberArray = new LottoNumber[6];
    // create the 5 lotto number objects in the array
    for(int i =0; i < lottoNumberArray.length; i++)
         lottoNumberArray[i] = new LottoNumber();
         do     // you can keep playing until the cows come home.
              // generate the numbers, and check for duplicates
    // (see the duplicateLottoNumbers() method below)
              for(int i = 0; i < lottoNumberArray.length; i++)
                        do
                             lottoNumberArray.changeNumber(TOPNUMBER);
                        while(duplicateLottoNumbers(i, lottoNumberArray) == true);
              // sort the array numerically,from smallest to largest numbers
              insertionSort(lottoNumberArray);
              // generate the powerball number. Note that this number can be
              // a duplicate of one of the 5 main numbers
              LottoNumber powerBall = new LottoNumber(POWERBALLTOP);
              // this section generates the message for the user
                   String messageDialog = "Your Lotto numbers are \n";
                   for(int i = 0; i < lottoNumberArray.length; i++)
                        messageDialog += lottoNumberArray[i].getNumber() + " ";
                   messageDialog += "\n And your powerball number is \n";
                   messageDialog += powerBall.getNumber();
              // end of section generating message
    JOptionPane.showMessageDialog(null, messageDialog);
                   response = JOptionPane.showConfirmDialog(null, "Play Again?", null, 0);
         while(response == YES); // if response = no, the cows have come home
    } // end main
    // This method checks for duplicate numbers in the array of lotto numbers.
    // If a duplicate number is found, "true" is returned. Otherwise "false" is returned.
    public static boolean duplicateLottoNumbers(int current, LottoNumber[] lottoArray)
    for(int i = current; i > 0; i--)
              if(lottoArray[current].getNumber() == lottoArray[i-1].getNumber())
              return true;
    return false;
    // This is a standard insertion sort algorithm. It is not the most efficient sort
    // algorithm available (n squared), but works fine for smaller sets of numbers.
    // Note that the algorithm has been adjusted to sort entire LottoNumber objects
    // around, rather than just their values.
    public static void insertionSort(LottoNumber[] lottoArray)
    int i, j;
    LottoNumber index;
    for (i=1; i < lottoArray.length; i++)
    index = lottoArray[i];
    j = i;
    while ((j > 0) && (lottoArray[j-1].getNumber() > index.getNumber()))
    lottoArray[j] = lottoArray[j-1];
    j = j - 1;
    lottoArray[j] = index;
    } // end class Play
    Thanks.

    Can't help you with your posted code - can't follow it in it's format, and don't have the lottonumber classes.
    Play around with this, you might be able to modify it to suit your needs
    (needs testing, error handling etc)
    import javax.swing.*;
    import java.util.*;
    public class PlayLotto
      ArrayList mainDraw = new ArrayList();
      ArrayList powerBall = new ArrayList();
      int[] userNumbers = new int[5];
      String sUserNumbers = "";
      int userPowerball;
      public PlayLotto()
        for(int x = 1; x < 50; x++)
          mainDraw.add(""+x);
          powerBall.add(""+x);
        int playAgain = 0;
        while(playAgain == 0)
          getUserNumbers();
          playGame();
          playAgain = JOptionPane.showConfirmDialog(null,"Play again?");
        System.exit(0);
      public void getUserNumbers()
        int sameNumbers = 1;
        if(userNumbers[0] != 0) sameNumbers = JOptionPane.showConfirmDialog(null,"Play the same numbers?");
        if(sameNumbers > 0)
          String[] numbers = JOptionPane.showInputDialog(
          "enter 5 numbers 0 - 49, separated by a space e.g. 1 5 15").split(" ");
          sUserNumbers = "";  
          for(int x = 0; x < numbers.length; x++)
            userNumbers[x] = Integer.parseInt(numbers[x]);
            sUserNumbers += " "+numbers[x];
          userPowerball = Integer.parseInt(JOptionPane.showInputDialog("enter your powerball number"));
          sUserNumbers += "   ("+userPowerball+")";
      public void  playGame()
        Collections.shuffle(mainDraw);
        Collections.shuffle(powerBall);
        int[] drawn = new int[5];
        int matches = 0;
        String totalDrawn = "";
        for(int x = 0; x < drawn.length;x++)
          drawn[x] = Integer.parseInt(""+mainDraw.get(x));
          for(int y = 0; y < userNumbers.length; y++)
            if(drawn[x] == userNumbers[y])
              matches++;
              break;
          totalDrawn += " "+drawn[x];
          JOptionPane.showMessageDialog(null,"This number = "+drawn[x]+
            "\n\nNumbers drawn  ="+totalDrawn+"\n\nMatches = "+matches);    
        int pBall = Integer.parseInt(""+powerBall.get(0));
        totalDrawn += "   ("+pBall+")";
        String pbResult = "";
        if(pBall == userPowerball) pbResult = " plus powerball";
        JOptionPane.showMessageDialog(null,"The powerball number is....(drum roll)");
        JOptionPane.showMessageDialog(null,""+pBall);
        JOptionPane.showMessageDialog(null,"Results\n\nNumbers drawn = "+totalDrawn+
        "\nNumbers played ="+sUserNumbers+"\n\nMatches = "+matches+pbResult);    
      public static void main(String[] args){new PlayLotto();}
    }

  • Need help on this program

    Hi all,
    The purpose of this program is listed in here:
    // Inputs the miles driven and gallons used (both integers) for each tankful.
    // Calculates and displays miles per gallon obtained for each tankful and print
    // the combined miles per gallon obtained for all tankfuls up to this point.
    // All results should be floating point. Use Scanner and sentinel-controlled
    // repetition to obtain data from the user.
    // Exercise 4.17 MPG.java
    import java.util.Scanner;
    public class MPG
    private int milesDriven;
    private int gallonsUsed;
    private float result;
    public void setMilesDriven( int miles )
    milesDriven = miles;
    public void setGallonsUsed( int gallons )
    gallonsUsed = gallons;
    public String getMilesDriven( int miles )
    return milesDriven; // error occurs here
    public String getGallonsUsed( int gallons )
    return gallonsUsed;
    public MPG( float result )
    result = gallons * miles;
    System.out.printf( result);
    I try to compile this program, but the error I get is "incompatible types-found int but expected java.lang.String." How do I fix this, and how do I
    use sentinel control? If you can help me with these two things, I'd appreciate it. The sooner you can help me, the better.

    When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
    I try to compile this program, but the error I get is
    "incompatible types-found int but expected
    java.lang.String." That means you provided an int where the program expected a string. Just like it says.
    How do I fix this,Either provide a String instead of the int, or change the code that's expecting a String to operate on an int instead.
    and how do I
    use sentinel control? II assume the instructor just wants a flag that indicates whether you're done or not. If the user enters "quit" or whatever, set that flag to true. The loop control ( while(whatever), for example) checks the flag, and either enters the loop or not.
    The sooner you can
    help me, the better.I'd advise you to keep comments like this out of your future posts. Nobody here cares about your timetable. We answer questions on our own schedule, and comments like that, and "urgent" and "asap" just annoy people.

  • Really stuck on how to start this program

    Okay, I know I should be posting some code here and showing where I've started and such, but I'm pretty lost as to how to start this program. Here's the problem:
    2. Making Change:
    This application, named ChangeMaker, will take as input a product price and an amount paid,
    both floating-point numbers representing euro and cent amounts. The application computes and prints the amount of change due the user, and also expresses the change amount in number of 2-euros, 1-euro, 20-cent, 10-cent, 5-cent, 2-cent, and1-cent coins.
    (Assume no change is given in bills, only in coins.)
    For example:
    Enter product price: 2.32
    Enter amount paid: 5.00
    Your change is 2.68 euros
    1 x 2 euro
    3 x 20-cent
    1 x 5 cent
    1 x 2 cent
    1 x 1 cent
    You can assume that the amount paid is greater than the product price, and that both inputs are
    "euro and cent" amounts: positive numbers with at most two decimal places.3
    Now, I know how to print the line asking for product price and enter amount paid, but I cannot figure out how to set up the rest of the code when switching from american USD dollars/coins to euros. I looked up the conversions and they are just intimidating as all get out when trying to take the equivalency of euros to each dollar thats entered and then taking the rest of the USD remainders and represent that in USD coinage. >.< Help is much appreciated thank you.

    thomas.behr wrote:
    random0munky wrote:
    ... when switching from american USD dollars/coins to euros. I looked up the conversions and they are just intimidating as all get out when trying to take the equivalency of euros to each dollar thats entered and then taking the rest of the USD remainders and represent that in USD coinage.Uhm, your requirement doesn't say anything about converting between USD and EUR. For starters, just write the program without any currency information at all. (That is only flavour anyways.)
    For example:
    Enter product price: 2.32
    Enter amount paid: 5.00
    Your change is 2.68
    1 x 2
    3 x 0.2
    1 x 0.05
    1 x 0.02
    1 x 0.01That deception would never fly in a Red State -- 20 cent piece? 2 cent piece? 2 dollar coin? All this smacks of Socialism!

  • How do I make this program generate a new problem once the button is hit

    Here is the code... appreciate any help given
    How do I make this program generate a new set of problem when the "NEXT" button is clicked and continue until the END button is hit
    package javaapplication3;
    import java.awt.GridLayout;
    import java.awt.Window;
    import javax.swing.*;
    import java.awt.event.*;
    * @author Sylvester Saulabiu
    class Grid extends JFrame{
        final int score = 0;
        final int total = 0;
        Grid(){
            //Set Layout of Flashcard
            setLayout(new GridLayout(4, 4, 2 , 2));
            //Create Panels
            JPanel p2 = new JPanel();
            JPanel p3 = new JPanel();
            final JPanel p1 = new JPanel();
            //Create Radio buttons & group them
            ButtonGroup group = new ButtonGroup();
            final JRadioButton ADD = new JRadioButton("Addition");
            final JRadioButton SUB = new JRadioButton("Subtraction");
            final JRadioButton MUL = new JRadioButton("Multiplication");
            final JRadioButton DIV = new JRadioButton("Division");
            p2.add(ADD);
            p2.add(SUB);
            group.add(ADD);
            group.add(SUB);
            group.add(MUL);
            group.add(DIV);
            p2.add(ADD);
            p2.add(SUB);
            p2.add(DIV);
            p2.add(MUL);
            //Create buttons
            JButton NEXT = new JButton("NEXT");
            JButton END = new JButton("End");
            //Create Labels
            JLabel l1 = new JLabel("First num");
            JLabel l2 = new JLabel("Second num");
            JLabel l3 = new JLabel("Answer:");
            JLabel l4 = new JLabel("Score:");
            final JLabel l5 = new JLabel("");
            JLabel l6 = new JLabel("/");
            final JLabel l7 = new JLabel("");
            //Create Textfields
            final JTextField number = new JTextField(Generator1());
            final JTextField number2 = new JTextField(Generator1());
            final JTextField answer = new JTextField(5);
            //Add to panels
            p1.add(l1);
            p1.add(number);
            p1.add(l2);
            p1.add(number2);
            p1.add(l3);
            p1.add(answer);
            p1.add(l4);
            p1.add(l5);
            p1.add(l6);
            p1.add(l7);
            p3.add(NEXT);
            p3.add(END);
            //Add panels
            add(p2);
            add(p1);
            add(p3);
            //Create Listners
      NEXT.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
             int answer1 = 0;
             //Grab the numbers entered
             int numm1 = Integer.parseInt(number.getText());
             int numm2 = Integer.parseInt(number2.getText());
             int nummsanswer = Integer.parseInt(answer.getText());
             //Set the score and total into new variabls
             int nummscore = score;
             int nummtotal = total;
             //Check if the add radio button is selected if so add
             if (ADD.isSelected() == true){
                 answer1 = numm1 + numm2;
             //otherwise check if the subtract button is selected if so subtract
             else if (SUB.isSelected() == true){
                 answer1 = numm1 - numm2;
             //check if the multiplication button is selected if so multiply
             else if (MUL.isSelected() == true){
                 answer1 = numm1 * numm2;
             //check if the division button is selected if so divide
             else if (DIV.isSelected() == true){
                 answer1 = numm1 / numm2;
             //If the answer user entered is the same with th true answer
             if (nummsanswer == answer1){
                 //add to the total and score
                 nummtotal += 1;
                 nummscore += 1;
                 //Convert the input back to String
                 String newscore = String.valueOf(nummscore);
                 String newtotal = String.valueOf(nummtotal);
                 //Set the text
                 l5.setText(newscore);
                 l7.setText(newtotal);
             //Otherwise just increase the total counter
             else {
                 nummtotal += 1;
                 String newtotal = String.valueOf(nummtotal);
                 l7.setText(newtotal);
      //Create End listener
    END.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // get the root window and call dispose on it
            Window win = SwingUtilities.getWindowAncestor(p1);
            win.dispose();
    String Generator1(){
         int randomnum;
         randomnum = (1 + (int)(Math.random() * 20));
         String randomnumm = String.valueOf(randomnum);
         return randomnumm;
    public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            JFrame frame = new Grid();
            frame.setTitle("Flashcard Testing");
            frame.setSize(500, 200);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }Edited by: SirSaula on Dec 5, 2009 4:39 PM

    Extract code into methods, so that when an action is performed a method is called. That way you can reuse the method for purposes such as resetting textfields to their default values, scores to default values, etc.
    You can go one step further and seperate the GUI layer from the processing layer, by deriving classes that for example maintain and calculate a score.
    Mel

  • Why doesn't this program compile?

    Compiling this program:
      public class Foo<T> {
        private final Class<T> type;
        public Foo(Class<T> type) {
            this.type = type;
        public T cast(Object obj) {
            return this.type.cast(obj);
        public void handle(T obj) {
        static void apply(Foo<?> foo, Object obj) {
            foo.handle(foo.cast(obj));
      }gives this error:
        Foo.java:12: handle(capture#31 of ?) in Foo<capture#31 of ?>
          cannot be applied to (java.lang.Object)
        foo.handle(foo.cast(obj));
        ^But this seems bogus. Obviously the result of foo.cast(obj) (generic type T) should be compatible with handle(), which takes a T.
    Am I missing something or is this a compiler bug (or limitation)?
    This is on openSuSE 11.1:
        $ javac -version
        javac 1.6.0_0
        $ rpm -qf /usr/lib/jvm/java-1.6.0-openjdk/bin/javac
        java-1_6_0-openjdk-devel-1.6_b16-0.1.3Thanks for any insights.

    endasil wrote:
    alc wrote:
    Thank you, this I understand... though it's a little disappointing the compiler can't make the simple inference required. I guess that would require data flow analysis.Which is easier said than done, and sometimes impossible.
    Imagine you changed Foo thusly:
    static Foo<?> foo = new Foo<String>(String.class);
    static void apply(Object obj) {
    foo.handle(foo.cast(obj));
    }And then used it like this:
    public class GT7 {
    public static void main(String[] args) {
    new Thread(new Runnable() {
    public void run() {
    Foo.foo = new Foo<Integer>(Integer.class);
    }).start();
    Foo.apply("Hello!");
    }How's the compiler supposed to figure that one out?Yes, if there is a race condition the compiler obviously can't assume "foo" won't change. But that's not the case in the original program.. foo is a local variable. A compiler could (with sufficient work) prove this to itself. This is not one of those an impossible Turing-complete scenarios like you sometimes see with "uninitialized variable" errors where the variable actually is always initialized.
    I'm not saying that it's necessarily worth the effort to implement this in the compiler. My only point is that this was strictly a language/compiler design choice -- and a reasonable one. But there's also nothing wrong with the "intent" of the program, even if the compiler doesn't "get it".

  • What is wrong with my converstion in this program fah to celsius

    package converter;
    import java.io.*;
    import java.text.*;
    public class Cel {
         public static void main(String arg[]) throws IOException {
            BufferedReader stdin =
            new BufferedReader ( new InputStreamReader (System.in));
            DecimalFormat twoDigitsPastPoint = new DecimalFormat("0.00");
            String get_value;
            double cel=0.00;
            char reply;
            System.out.print("ENTER CELSIUS: ");
            get_value= stdin.readLine();
            cel = Integer.parseInt(get_value);
            System.out.print("THE FAHRENHEIT DEGREE EQUIVALENT IS: "
            + twoDigitsPastPoint.format(fah_cel(cel)) + ".");
            System.out.print("\n");
                do {
                String get_value2, answer;
                double cel2=0.00;
                System.out.print("DO YOU WANT TO continue Y/N: ");
                answer = stdin.readLine();
                reply = answer.charAt(0);
                if (reply =='n' || reply=='N')
                    System.exit(0);
                else if (reply =='Y' || reply=='y')
                    System.out.print("ENTER CELSIUS: ");
                    get_value2= stdin.readLine();
                    cel2 = Integer.parseInt(get_value2);
                    System.out.print("THE FARHRENHEIT DEGREE EQUIVALENT IS: "
                    + twoDigitsPastPoint.format(fah_cel(cel2)) + ".");
                    System.out.print("\n");
            } while (reply== 'Y' || reply == 'y');
        public static double fah_cel(double c)
            double fah=0.00;
            fah = (9.0/5.0) * (c + 32);
            return(fah);
    }i do not get the correct conversion when i run the program . . . . . i also have another class in this program that i created before this class that converts from fah to celsius and it works

    yes thanks . . . . . i was googling around for different equations for this . . . . . the one my professor supplied with the homework was wrong . . . . .
    this is what i needed . . ((9.0/5.0) * celsius) + 32 . . . . it works now thanks.

Maybe you are looking for