Java - How to initialize parameters for an object? - java

I have been struggling with this issue for weeks and still cannot get what I need. My CalculatingRocketFlightProfile class holds the constructor with the parameters (totalImpulse, averageImpulse etc...) and the methods which calculates the outputs. My MAIN class has an object which inherits my keyboard entry class. This allows users to input a number. Now, all I need is to use these inputs and calculate a result (using the methods in the CalculatingRocketFlightProfile class) to be displayed. However my object of CalculatingRocketFlightProfile class wont acceppt any parameters or I simply doing something wronng. Please help me out I'm really frustrated.
//CalculatingRocketFlightProfile class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle; //declare variables to store results of calculations
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Setting the parameters
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Mutators - SET
public void setTheAverageMassOfTheVehicle(double theAverageMassOfTheVehicle) {
this.theAverageMassOfTheVehicle = theAverageMassOfTheVehicle;
}//method
public void setTheVehiclesMaximumVelocity(double theVehiclesMaximumVelocity) {
this.theVehiclesMaximumVelocity = theVehiclesMaximumVelocity;
}//method
//Getters
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.totalImpulse1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.averageImpulse2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.timeEjectionChargeFires3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.massEmptyVehicle4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.engineMass5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.fuelMass6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(totalImpulse,averageImpulse,timeEjectionChargeFires,massEmptyVehicle,engineMass,fuelMass ); //This will give me an error "cant find variables"
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry class (Same for all methods e.g. averageImpulse2, timeEjectionChargeFires3 etc...)
public class kbentry{
double totalImpulse1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}

You are not storing the returned information from your kbentry methods. Try this:
System.out.print("\nPlease enter a number for Total Impulse: " );
double totalImpulse = input.totalImpulse1();
System.out.println("You have entered : " + totalImpulse);
Do the same for the other variables, then use those to pass in as arguments for your new object.

Related

Need assistance with having executable code

I haven't been able to make this code executable for class and can't find the reason why there are no errors prompting however when i execute i get this:
Exception in thread "main" java.lang.UnsupportedOperationException: Not
supported yet.
at set.fixedSalary(set.java:14)
at Main.main(Main.java:23)
C:\Users\the_h\AppData\Local\NetBeans\Cache\8.2\executor-
snippets\run.xml:53: Java returned: 1
I honestly have no idea how to fix this problem any help is appreciated I have the source code below.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private double fixedSalary;
private double commission;
private double salesTarget;
private double Acc_Rate;
private ArrayList<Double> annualSales;
private ArrayList name;
public static void main(String[] args){
// salesperson will earn a fixed salary of $32,600
set.fixedSalary(32600);
// The current sales target for every salesperson is $120,000.00
set.SalesTarget(120000.00);
//The acceleration factor is 2.1
set.Acc_Rate(2.1);
}
public ArrayList<Double> getAnnualSales(){
return annualSales;
}
public Main() {
this.name = new ArrayList();
this.annualSales = new ArrayList<>();
}
private float calculateCommission(double personSale) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
function read user input
class readData{
public void readData(){
// Creates a scanner object for sales entry.
Scanner input = new Scanner(System.in);
// prompts user for name of sales person
System.out.println("Please enter First Sales Person name: ");
name = addinput.nextLine();
// prompts user for name of sales person
System.out.println("Please enter 2nd Sales Person name: ");
name = addinput.nextLine();
//Prompts user for sales
System.out.println("Please enter annual sales First Person: ");
annualSales = addinput.nextDouble();
//Prompts user for sales
System.out.println("Please enter annual sales Second Person: ");
annualSales = addinput.nextDouble();
}
}
class calculateCommission {
double commission = 0.00;
double Acc_Rate;
calculateCommission() {
}
public double calculateCommission(double annualSales, double fixedSalary,
double salesTarget) {
this.Acc_Rate = 0.045 * annualSales;
double earnings = fixedSalary;
// The current commission is 4.5 of total sales
if(annualSales < 0.8 * salesTarget) {
earnings = fixedSalary + commission;
} else if (annualSales <= salesTarget){
//The current acc rate is 2.1 of total sales
commission = 0.045 * annualSales;
earnings = fixedSalary + commission;
} else if (annualSales > salesTarget){
earnings = fixedSalary + Acc_Rate;
}
return earnings;
}
} // function get commision
public double getCommission() {
return commission;
}
// function get total annual compensation
public double getTotalCommissionCalc(){
return fixedSalary + getCommission();
}
// funtion set value for fixedSalary
public void setfixedSalary(double fixedSalary){
this.fixedSalary = fixedSalary;
}
// funtion set value for salesTarget
public void setSalesTarget(double salesTarget){
this.salesTarget = salesTarget;
}
// funtion set value for incentive rate
public void setAcc_Rate(double Acc_Rate) {
this.Acc_Rate = Acc_Rate;
}
// Display a table of potential total annual compensation
public void displayResult(){
double annualSalesCalc;
double personSale;
for (int i = 0; i < name.size(); i++){
String personName = (String) name.get(i);
personSale = annualSales.get(i);
System.out.println("Total Compensation of Sales Person " +
personName + " is " + Math.round(calculateCommission(personSale)));
//Print column names
System.out.print("SalePerson\tTotal Sales\tTotal Compensation");
annualSalesCalc = personSale * 1.50;
while(personSale <= annualSalesCalc){
calculateCommission(personSale);
System.out.println((personName) + "\t\t" +
Math.round((personSale)) + "\t\t" +
Math.round(calculateCommission(personSale)));
personSale = personSale + 5000;
}
System.out.println(); // print blank line
}
if (annualSales.get(0) > annualSales.get(1)) {
System.out.println("Salesperson " + name.get(1)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(0)) + " is");
System.out.print("$" + Math.round((annualSales.get(0) -
annualSales.get(1))));
} else if(annualSales.get(1) > annualSales.get(0)){
System.out.println("Salesperson " + name.get(0)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(1)) + " is");
System.out.print("$" + Math.round((annualSales.get(1) -
annualSales.get(0))));
} else{
System.out.print("Both have same compensation");
}
}
}
It might be because your set.fixedSalary needs to be an integer because you dont set it as a double. you set it to 36000 when it needs to be 36000.0

Java Basic Object Oriented Gratuity Calculator

I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.

my display() is not running or showing my println

The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
double tax = .05;
double totalamount;
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
while (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
}
while (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
}
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount(double totalAmount) {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
double totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)
I would massively refactor your code if given the chance. First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state. Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input. A big change I made was in how the code handles user inputs. My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method. Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
private int invoiceNum;
private double amount;
private double totalamount;
// I am hard-coding the sales tax as 5%, as you did in your question,
// though this code can easily be modified if you also want to input the tax
private final double tax = .05;
public int getInvoiceNum() {
return invoiceNum;
}
public void setInvoiceNum(int invoiceNum) {
this.invoiceNum = invoiceNum;
}
public double getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
public static void main(String[] args) {
CreatePurchase cp = new CreatePurchase();
Scanner input = new Scanner(System.in);
// these next two do-while loops will continue polling the user
// until he enters a valid input
do {
System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
} while (invoiceNum < 1000 || invoiceNum > 8000);
cp.setInvoiceNum(invoiceNum);
do {
System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
} while (amount < 0);
totalamount = amount*(1 + tax);
cp.setAmount(amount);
cp.setTotalAmount(totalAmount);
// now use the CreatePurchase object to print out
// details of the transaction
System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
System.out.println("Your sale amount is: " + cp.getAmount() + ".");
System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
}
}
You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.
try the below code, this should help!
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
static double tax = .05;
static double totalAmount;
public void updatePurchase(final Purchase purchase) {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
if (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
updatePurchase(purchase);
}
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
if (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
updatePurchase(purchase);
}
setTotalAmount(tax, amount);
display(invoiceNum, amount, getTotalAmount());
}
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
new CreatePurchase().updatePurchase(completedPurchase);
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}

Local variable can't take methods parameters

I am new To Java please help me, my local variable can't take me methods parameters.
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.text.DecimalFormat; //I can not get my local variables in my
// main to accept my methods parameters.
// This is my program.
public class AccountBank
{
public static void main (String[] args) throws IOException
{
// Calling in my Class
Accountclass BankAcc = new Accountclass();
// initialize both there variables in. order to use them in a for loop.
double depDrw = 0;// this are one of the variables that is giving me problems
double withDrw = 0; // this is the other that is giving me problems
double totalW = 0;
double totalD = 0;
// declaring all my variables
String name="";
double month;
double startBal;
// This section will greet and accept input by asking the user to enter the starting alance and set it in my class
// Greetings
JOptionPane.showMessageDialog(null,"Lets Get Started");
// receiving input for my name variable
name = JOptionPane.showInputDialog(null, "Please Enter Your Name Below: ");
// ask user for starting balance
startBal = Double.parseDouble(JOptionPane.showInputDialog("What Is The Starting Balance In Your Account:"));
// This will set the value in my class
BankAcc.setBal(startBal);
// ask user how many months has the account been active
month = Double.parseDouble(JOptionPane.showInputDialog("Months That Account Has Been Active:"));
// This section will accept input by asking the user to enter each amount deposited every month from the account set it in my class.
// This will be shown in the message box
depDrw = depositTotal(deposit); << // I am having trouble here it wont take my parameters variable which I created on the buttom. please help
// This will sum up every amount the user enters in the message box.
totalD += depDrw;
// This will set the value in my class
BankAcc.setdeposit(totalD);
// This section will accept input by asking the user to enter each amount withdrawn every month from the account and set it in my class
// This will be shown in the message box
withDrw = withdrawTotal(wit); // <<< I am having problem here this variable does not take the value of my methods parameter, which i created on the bottom of this page.
// This will sum up every amount the user enters in the message box.
totalW += withDrw;
// This will set the value in my class
BankAcc.setwithdraws(totalW);
//This section will display the " monthly interest rate, monthly interest earned, total amount deposited, total amount withdrawn, and the final balance of the account."
DecimalFormat formatter = new DecimalFormat("#0.0000");
DecimalFormat formatter2 = new DecimalFormat("#0.0");
DecimalFormat formatter3 = new DecimalFormat("#0.00");
//Get the calculations from the savings account class and display them.
JOptionPane.showMessageDialog(null," Account Name: " +name+"\n \n Your Monthly Interest Rate Is ..... "
+ formatter.format(BankAcc.monthInt())+"%" + "\n \n Your Monthly Interest Earned Was ..... $"
+ formatter2.format(BankAcc.GetInt()) + "\n \n Your Overall Amount With Deposited Was ..... $" + totalD +
" \n \n Your Overall Amount WithDrawn Was ..... $" + totalW + " \n \n Your Remaining Balance Is ..... $"
+ formatter3.format(BankAcc.getFinalbal()),"Results", JOptionPane.PLAIN_MESSAGE );
}
public static double depositTotal( String deposit)
throws IOException
{
double sales;
double totalDeposit = 0;
File file = new File ("deposits.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
inputfile.close();
return totalDeposit;
}
public static double withdrawTotal( String wit)
throws IOException
{
double sales;
double totalwithdraws = 0;
File file = new File ("withdraws.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalwithdraws += sales;
}
inputfile.close();
return totalwithdraws;
}
Your while loop is
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
There shouldn't be a ; after the while (inputfile.hasNextDouble())
while (inputfile.hasNextDouble())
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
Similarly for other while loops, remove the ;
Change your method declaration so it doesn't receive any parameter. And because it's returning a double, you may store the value it returns in a double variable:
double deposit = depositTotal();
In your depositTotal() method:
public static double depositTotal() throws IOException {
...
}

How do I write a method to calculate total cost for all items in an array?

I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}

Categories