Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Inputting for a Loop.
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
GDoughtUpInIt




PostPosted: Sun Jul 18, 2004 9:40 pm   Post subject: Inputting for a Loop.

Hey, my program is designed to help someone organize their company departments. I want the user to enter how many departments he/she has, and then the program uses the user's input to determine how many times the company form comes up. Any help would be appreciated. Here is my code. Maybe someone can help me out with it.

Quote:
import java.io.*;
import java.text.*;

class Departments
{
public static void main (String[] args) throws IOException
{
int x=0;
String departments;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many departments would you like to enter?");
departments = in.readLine ();

while (x=departments){

String department;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Department Name:");
department = in.readLine ();

String employees;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Employees:");
employees = in.readLine ();

String costPerEmployee;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Cost Per Employee:");
costPerEmployee = in.readLine ();

String sales;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Sales:");
sales = in.readLine ();

x=x+1;
}

}
}
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Sun Jul 18, 2004 10:10 pm   Post subject: (No subject)

you'd use a for loop

code:

for (int i=0; i<number; i++)
{
     //do stuff
}
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
GDoughtUpInIt




PostPosted: Mon Jul 19, 2004 9:47 pm   Post subject: (No subject)

Okay, I changed it to a for loop but now the interpreter says, "operator < cannot be applied to int,java.lang.String for (int x=0; x<departments; x++){"

Here is my current, non-working code:

code:
import java.io.*;
import java.text.*;

class Departments
{
public static void main (String[] args) throws IOException
{
String departments;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many departments would you like to enter?");
departments = in.readLine ();

for (int x=0; x<departments; x++){

String department;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Department Name:");
department = in.readLine ();

String employees;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Employees:");
employees = in.readLine ();

String costPerEmployee;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Cost Per Employee:");
costPerEmployee = in.readLine ();

String sales;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Sales:");
sales = in.readLine ();

x=x+1;
}

}
}
wtd




PostPosted: Tue Jul 20, 2004 11:57 am   Post subject: (No subject)

Not tested, but it should set you on the right path.

code:
import java.lang.*;
import java.io.*;

public class Departments {
   public static void main(String[] args) throws IOException {
      BufferedReader in = new BufferedReader(
         new InputStreamReader(System.in));
      System.out.print("How many departments would you like to enter? ");
      String[][] departments = new String[Integer.parseInt(in.readLine())][];
      String[] prompts = { "Department Name", "Employees",
         "Cost per Employee", "Sales" };
      for (int i  = 0; i < departments.length; i++) {
         departments[i] = new String[prompts.length];
         for (int j = 0; j < prompts.length; j++) {
            System.out.println(prompt[j] + ":");
            departments[i][j] = in.readLine();           
         }
      }
   }
}
GDoughtUpInIt




PostPosted: Tue Jul 20, 2004 1:54 pm   Post subject: (No subject)

Well the code works, I just had to change the variable "prompt" to "prompts" on line 17. Now I need to do something like sales-(employees*cost per employee) to see if each departments is profitable. I'm not sure how to go about this. Any suggestions?
Tony




PostPosted: Tue Jul 20, 2004 2:04 pm   Post subject: (No subject)

well first of all you'd have to declear variables as global to the class, not local to the main(). This way other methods can access the same variables.

then create a boolean function in the department class called isProfitable which would return true if the restult of your calculation (revenue - cost) is possitive or false otherwise.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
wtd




PostPosted: Tue Jul 20, 2004 2:25 pm   Post subject: (No subject)

Sorry about the typo. I was rewriting that code in O'Caml, just to test my functional programming skills and it got lost in the mess of code. Smile

But I digress...

You have all of the input about the departments in strings. For number of employees, cost per employee and sales, you'll need to convert to int. You can use Integer.parseInt to do this.

code:
import java.lang.*;
import java.io.*;

public class Departments {
   public static void main(String[] args) throws IOException {
      BufferedReader in = new BufferedReader(
         new InputStreamReader(System.in));
      System.out.print("How many departments would you like to enter? ");
      String[][] departments = new String[Integer.parseInt(in.readLine())][];
      String[] prompts = { "Department Name", "Employees",
         "Cost per Employee", "Sales" };
      for (int i  = 0; i < departments.length; i++) {
         departments[i] = new String[prompts.length];
         for (int j = 0; j < prompts.length; j++) {
            System.out.println(prompts[j] + ":");
            departments[i][j] = in.readLine();           
         }
      }
      int[] profits = new int[departments.length];
      for (int k = 0; k < departments.length; k++) {
         int num_employees = Integer.parseInt(departments[k][1]);
         int cost_per_employee = Integer.parseInt(departments[k][2]);
         int sales = Integer.parseInt(departments[k][3]);
         profits[k] = sales - (num_employees * cost_per_employee);         
      }
      boolean[] profitable = new boolean[departments.length];
      for (int m = 0; m < profitable.length; m++) {
         profitable[m] = profits[m] > 0;
      }
   }
}


If anyone's interested, the O'Caml equivalent so far looks like:

code:
open List

let info = let rec ask = function
        [] -> []
        | first_prompt::others -> let prompt = first_prompt ^ ":" in
                print_endline prompt;
                let answer = read_line () in
                        answer :: ask others and
num_departments = try print_string "Number of departments? ";
        int_of_string (read_line ()) with _ -> 0 and
prompts = ["Department Name";"Employees";"Cost per Employee";"Sales"] in
        let rec gather_info = function
                0 -> []
                | num -> let info = ask prompts in
                        info :: gather_info (num - 1) in
                gather_info num_departments
                                                                                                             
let calc_profit [n; e; c; s] =
        let [e; c; s] = List.map int_of_string [e; c; s] in
                s - (e * s)
                                                                                                             
let profits = List.map calc_profit info
                                                                                                             
let profitables = List.filter (fun a -> (calc_profit a) >= 0) info


Hmm... I might code up an object-oriented version in both languages, just for fun.
GDoughtUpInIt




PostPosted: Thu Jul 29, 2004 1:10 pm   Post subject: (No subject)

Hey guys. Need a little more guidance.

Quote:
import java.lang.*;
import java.io.*;

public class Departments2 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("How many departments would you like to enter? ");
String[][] departments = new String[Integer.parseInt(in.readLine())][];
String[] prompts = { "Department Name", "Employees",
"Cost per Employee", "Sales" };
for (int i = 0; i < departments.length; i++) {
departments[i] = new String[prompts.length];
for (int j = 0; j < prompts.length; j++) {
System.out.println(prompts[j] + ":");
departments[i][j] = in.readLine();
}
}
double[] profits = new double[departments.length];
for (int k = 0; k < departments.length; k++) {
double num_employees = Integer.parseInt(departments[k][1]);
double cost_per_employee = Integer.parseInt(departments[k][2]);
double sales = Integer.parseInt(departments[k][3]);
profits[k] = sales - (num_employees * cost_per_employee);
}
boolean[] profitable = new boolean[departments.length];
for (int m = 0; m < profitable.length; m++) {
profitable[m] = profits[m] > 0;
}
}
}


That code asks the user how many departments and allows the user to enter the information. Now I need to have this output at the bottom...


"Department A Profits: $00.00
Department B Profits: $00.00
Department C Profits: $00.00
Department D: Profits: $00.00

Together, the departments are/are not profitable."

If I could get a code that could do this, that would be great. I'd like to see the changes made by an expert so that I can compare and learn how it's done. I think it would be a good lesson for a beginner like myself. Any help would be greatly appreciated. Thanks guys.
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Thu Jul 29, 2004 6:11 pm   Post subject: (No subject)

Hopefully you can learn from this.

code:
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;

public class Departments {
        public static void main(String[] args) throws IOException {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(System.in));

                System.out.print("How many departments would you like to enter? ");
                int numberOfDepartments = Integer.parseInt(in.readLine());

                String[][] departments = new String[numberOfDepartments][];
                String[] prompts = { "Department Name", "Employees",
                        "Cost per Employee", "Sales" };

                for (int i = 0; i < departments.length; i++) {
                        departments[i] = new String[prompts.length];
                        for (int j = 0; j < prompts.length; j++) {
                                System.out.print(prompts[j] + ": ");
                                departments[i][j] = in.readLine();
                        }
                        System.out.println();
                }

                double[] profits = new double[departments.length];

                for (int k = 0; k < departments.length; k++) {
                        int num_employees = Integer.parseInt(departments[k][1]);
                        double cost_per_employee = Double.parseDouble(departments[k][2]);
                        double sales = Double.parseDouble(departments[k][3]);
                        profits[k] = sales - (num_employees * cost_per_employee);
                }

                boolean[] profitable = new boolean[departments.length];

                for (int m = 0; m < profitable.length; m++) {
                        profitable[m] = profits[m] > 0;
                }

                double totalProfit = 0.0;

                for (int n = 0; n < departments.length; n++) {
                        DecimalFormat currencyFormat = new DecimalFormat("$0.00");
                        System.out.println(departments[n][0] + " Profits: " + currencyFormat.format(profits[n]));
                        totalProfit += profits[n];
                }

                if (totalProfit > 0) {
                        System.out.println("Together the departments are profitable.");
                } else {
                        System.out.println("Together the departments are not profitable.");
                }
        }
}
GDoughtUpInIt




PostPosted: Thu Jul 29, 2004 11:31 pm   Post subject: (No subject)

Hey. I examined the code, and have learned a lot about how to do this kind of looping. Thank you for your help.
wtd




PostPosted: Fri Jul 30, 2004 7:00 pm   Post subject: (No subject)

And here's an object-oriented version of it, just to further enlighten. Smile

code:
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;

public class DocumentsProgram {
        private static BufferedReader input = new BufferedReader(
                new InputStreamReader(System.in));

        public static void main(String[] args) throws IOException {
                System.out.print("Number of departments: ");
                int numberOfDepartments = Integer.parseInt(input.readLine());

                DepartmentSet departments = new DepartmentSet(numberOfDepartments);

                for (int i = 0; i < numberOfDepartments; i++) {
                        departments.addDepartment(Department.queryForDepartment());
                }

                for (Iterator i = departments.iterator(); i.hasNext(); ) {
                        System.out.println(i.next());
                }

                System.out.println();

                if (departments.profitable()) {
                        System.out.println("Together the departments are profitable.");
                } else {
                        System.out.println("Together the departments are not profitable.");
                }
        }

        public static class Department {
                private static DecimalFormat moneyFormat =
                        new DecimalFormat("$0.00");

                public static Department queryForDepartment() throws IOException {
                        Department d = new Department();

                        System.out.print("Department Name: ");
                        d.setName(input.readLine());

                        System.out.print("Number of Employees: ");
                        d.setNumberOfEmployees(Integer.parseInt(input.readLine()));

                        System.out.print("Cost per Employee: ");
                        d.setCostPerEmployee(Double.parseDouble(input.readLine()));

                        System.out.print("Sales: ");
                        d.setSales(Double.parseDouble(input.readLine()));

                        System.out.println();

                        return d;
                }

                private String name;
                private int numberOfEmployees;
                private double costPerEmployee;
                private double sales;

                /* Constructors */

                public Department() {
                        name = "";
                        numberOfEmployees = 0;
                        costPerEmployee = 0.0;
                        sales = 0.0;
                }

                public Department(String name, int numberOfEmployees, double costPerEmployee, double sales) {
                        this.name = name;
                        this.numberOfEmployees = numberOfEmployees;
                        this.costPerEmployee = costPerEmployee;
                        this.sales = sales;
                }

                /* Accessors */

                public String getName() {
                        return name;
                }

                public int getNumberOfEmployees() {
                        return numberOfEmployees;
                }

                public double getCostPerEmployee() {
                        return costPerEmployee;
                }

                public double getSales() {
                        return sales;
                }

                public void setName(String name) {
                        this.name = name;
                }

                public void setNumberOfEmployees(int numberOfEmployees) {
                        this.numberOfEmployees = numberOfEmployees;
                }

                public void setCostPerEmployee(double costPerEmployee) {
                        this.costPerEmployee = costPerEmployee;
                }

                public void setSales(double sales) {
                        this.sales = sales;
                }

                /* Logic */

                public double totalCost() {
                        return numberOfEmployees * costPerEmployee;
                }

                public double profit() {
                        return sales - totalCost();
                }

                public boolean profitable() {
                        return profit() > 0;
                }

                public boolean breakEven() {
                        return profit() == 0;
                }

                public String costPerEmployeeString() {
                        return Department.moneyFormat.format(costPerEmployee);
                }

                public String salesString() {
                        return Department.moneyFormat.format(sales);
                }

                public String profitString() {
                        return Department.moneyFormat.format(profit());
                }

                public String totalCostString() {
                        return Department.moneyFormat.format(totalCost());
                }

                public String toString() {
                        return "Department " + name + " profit: " + profitString();
                }
        }

        public static class DepartmentSet extends ArrayList {
                /* Constructors */

                public DepartmentSet() {
                        super();
                }

                public DepartmentSet(DepartmentSet c) {
                        super(c);
                }

                public DepartmentSet(int initialCapacity) {
                        super(initialCapacity);
                }

                /* Accessing */

                public boolean addDepartment(Department d) {
                        return super.add(d);
                }

                public void addDepartment(int index, Department d) {
                        super.add(index, d);
                }

                public Department getDepartment(int index) {
                        return (Department)super.get(index);
                }

                public Department setDepartment(int index, Department d) {
                        return (Department)super.set(index, d);
                }

                public Department[] toDepartmentArray() {
                        return (Department[])super.toArray();
                }

                /* Synonym for size() */

                public int length() {
                        return size();
                }

                /* Department related logic */

                public double overallCost() {
                        double cost = 0.0;

                        for (Iterator i = iterator(); i.hasNext(); ) {
                                Department d = (Department)i.next();
                                cost += d.totalCost();
                        }

                        return cost;
                }

                public double overallSales() {
                        double sales = 0.0;

                        for (Iterator i = iterator(); i.hasNext(); ) {
                                Department d = (Department)i.next();
                                sales += d.getSales();
                        }

                        return sales;
                }

                public double overallProfit() {
                        return overallSales() - overallCost();
                }

                public boolean profitable() {
                        return overallProfit() > 0;
                }

                public boolean breakEven() {
                        return overallProfit() == 0;
                }
        }
}
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 11 Posts ]
Jump to:   


Style:  
Search: