I'm still a pretty novice programmer so please excuse my messing code. When I try to compile the following code I get the error:
The method Customer(java.lang.String, java.lang.Double) is undefined for the type Customer
I have previously attempted to declare the object "s" within the for statement, it then creates a new error at the end of the program where I reference the object "s" again. I was wondering how I could get around this problem? Below I have included my current program, along with the desired output and Customer.class API.
API
desired output
import java.util.Scanner;
public class A4
{
public static void main( String[] args )
{
//delcaring variables
Scanner input = new Scanner( System.in );
String[] name = new String[5];
Double[] amount = new Double[5];
Customer s = new Customer( "", 0 );
//begining of program
for ( int i = 0; i <= 5; i++ )
{
System.out.println( "please enter the name of the customer" );
name[i] = input.next();
System.out.println( "please enter the amount in that account" );
amount[i] = input.nextDouble();
s.Customer( name[i], amount[i] );
//Customer s = new Customer(name [i],amount[i]);
}
System.out.println( "Search for all customers who have more than $100" );
for ( int t = 0; t <= 5; t++ )
{
if ( amount[t] >= 100 )
{
System.out.println( name[t] );
}
}
Double avgBalance = 0.0;
for ( int r = 1; r <= 5; r++ )
{
avgBalance += r;
}
avgBalance = avgBalance / 5;
System.out.println( "The average balance is: " + avgBalance );
Double max = amount[1];
for ( int j = 0; j <= 5; j++ )
{
if ( amount[j] > max )
{
max = amount[j];
}
}
System.out.println( "The customer with the highest balance is: " + max );
System.out.println( "Show all accounts after a 5% balance increase" );
//Customer c = new Customer(name [i],amount[i]);
for ( int e = 0; e <= 5; e++ )
{
//Customer c = new Customer amount[e].applyPercentageIncrease(5);
//amount [e]=
//applyPercentageIncrease q = new
s.applyPercentageIncrease( 5 );
System.out.println( s.getName() + " has " + s.getBalance() );
}
}
}
UPDATE: i have implemented what Gtomika suggested and the program now runs, however in the first for statement, the program asks the user for 6 names then sets an out of bounds error, i understand the out of bounds error, however the for statement conditions state that it should only ask for 5 names and 5 balances right? am i missing something here?
UPDATE2: I have fixed the above problem and have improved my program, now i need some help in using the method applyPercentageIncrease from the Customer.class API. I am aware the code i wrote below is not functional, but i would appreciate some help with applying a 5% increase to all account balances using the method stated above. thanks
for (int e=0;e<5;e++)
{
//Customer c = new Customer amount[e].applyPercentageIncrease(5);
//amount [e]=
//applyPercentageIncrease q = new
customers[o]=e.applyPercentageIncrease(5);
System.out.println (o.getName()+" has "+o.getBalance());
}
You should also declare and array (or perhaps an ArrayList or LinkedList) of Customer objects:
Customer[] customers = new Customer[5];
This way in the for loop you can say:
for (int i=1;i<=5;i++)
{
System.out.println("please enter the name of the customer");
name[i] = input.next();
System.out.println("please enter the amount in that account");
amount[i] = input.nextDouble();
customers[i] = new Customer(name[i],amount[i]); //set the i. element of the Customer array
}
Now you can reference the created Customer objects after this loop!
Related
The Code below I tried got to work correctly. When I go to "Run As" in Eclipse, the Console shows nothing and the output is blank. Please help. NOTE I took out the public class & import java because the post wasn't loading the code correctly.
public static void main(String[] args ) {
// Create new Scanner
Scanner input = new Scanner(System.in);
// Set number of students to 10
int numStudents = 10;
// Note
int [][] studentData = new int[numStudents][1];
// loop
for (int i = 0; i > numStudents; i++) {
// Note
boolean classesValidity = true ;
while (classesValidity == false) {
System.out.print("Enter classes and graduation year for student’" +
(i + 1) + " : " );
int numClasses = input.nextInt();
studentData [i][0] = numClasses;
int gradYear = input.nextInt();
studentData [i][1] = gradYear; }
for (int i1 = 0; i > numStudents; i ++) { System.out.println("\n Student " + ( i ) + " needs " +
studentData [i][0]*3 + " credits to graduate in " + studentData [i][1]); }}}}
classesValidity is initialized with true and remains unchanged. In turn the while loop is never executed and the program only iterates through studentData without operating on it.
I started to study JAVA, So sorry for the question.. I practice the WHILE LOOP, so I have this code:
import java.util.Scanner;
public class Class {
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
double n = 0;
while ( n < 10 )
{
System.out.println( (n+1) + "." + message );
n++;
}
}
}
so, I want to get a result somthing like that: 10. 20. 30. and etc..
but I get: 1.0. , 2.0., 3.0. and etc..
what I should do to remove this dot, between 1 and 0...? thank you very much for your help :).
Use int instead of double for n variable:
int n = 0;
Well, a quick fix to your problem would be first changing the data type to int, so int n = 0; then simply add "0." to your print statement, so it looks like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 0;
while ( n < 10 ) {
System.out.println( (n+1) + "0." + message );
n++;
}
}
}
Or, alternatively, you could do int n = 10 and have your while loop condition aswhile( n < 100 ) then increment n by ten (n+=10;). So now it would look like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 10;
while ( n < 100 ) {
System.out.println(n + "." + message);
n+=10;
}
}
}
you can increment in 10s by multiplying n by 10, Also you might want to use int type rather than double to remove the decimal point.
int n = 1;
while ( n <= 10 )
{
System.out.println( ( 10 * n) "." + message );
n++;
}
You can try something like this:
int n = 10; // start from 10 and change it from double to int to get rid of decimal point
while ( n <= 100 ){
System.out.println( n + "." + "message");
n+=10; // increment by 10 after every loop
}
Ive been working on this program for a few days now and its due tonight at midnight. I cannot for the life of me figure out why I keep getting a " The local variable cannot be initialized" error. This is my first coding class and I do not understand it very well. If someone could help me out by explaining a fix and why this error keeps happening that would be great.
I have put "**" where the errors are ( near the end of the code). Any help would be great! Thanks in advance.
/*This program will determine how much the students
tuition and fees are based on location and classes. It will return the
total tuition, fees, and combined total */
import java.text.DecimalFormat;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//Declaring variables and decimal format
int TotalHours;
int Price;
int CreditCharge;
int CITFee;
int OnlineFee;
int INFCSCFee;
int TotalTuition;
int TotalFee;
int TotalCombined;
DecimalFormat df = new DecimalFormat("$#,###");
//Getting the students First name, Last name, and Date
System.out.print("Enter your first name: ");
String FirstName = in.nextLine();
System.out.print("Enter your last name: ");
String LastName = in.nextLine();
Date d = new Date ( );
//Getting the state of residency. If in Ohio, asking the user if they are Metro
System.out.print("Enter your State of residency as a 2-letter abbreviation: ");
String State = (in.next().toLowerCase());
if (State.equals ("oh") || State.equals("OH")){
System.out.print( "Are you a Cincinnati resident? (Y/N) ");
String Metro = in.next();
if (Metro.equals ("y")) Price = 567;
}
else Price = 750;
if (State.equals ("ky") ){ Price = 375;
}
else if (State.equals ("in")){Price = 375;
}
else {Price = 750;
}
//Getting the number of credit hours the student is taking
System.out.print("Enter the total credit hours for the upcoming semester: ");
TotalHours = in.nextInt();
if (TotalHours <= 12) CreditCharge = (TotalHours * Price);
else {CreditCharge = (Price * 12);
}
//Getting the number of CIT hours the student is taken
System.out.print("Enter the total of CIT credits you are taking: ");
int TotalCITHours = (int) in.nextInt();
CITFee = (TotalCITHours * 40);
//Getting the number of online credit hours the student is taken
System.out.print("Enter the total number on-line credit hours you are taking: ");
int OnLine = (int) in.nextInt();
OnlineFee = (OnLine * CITFee * 35);
//Seeing if the student is taken either INF 120 or CSC 260
System.out.print("Are you taking either INF 120 or CSC 260? (Y/N) ");
String INFCSC = in.next().toLowerCase();
if (INFCSC.equals ("y")) INFCSCFee = (char) (CITFee * OnlineFee + 60);
//Calculating the tuition, fees, and total combined.
** TotalTuition = CreditCharge;
** TotalFee = INFCSCFee;
** TotalCombined = TotalTuition + INFCSCFee;
//Tuition Statement for FirstName, LastName, Date
System.out.println("\nTuition Statement for " + FirstName + LastName);
System.out.println(d);
System.out.println("Tuition: " + df.format (TotalTuition) );
System.out.println("Fees: " + df.format(TotalFee));
System.out.println("Total: " + df.format(TotalCombined));
}
}
Your variable INFCSCFee was not initialized if they did not answer yes to the question "Are you taking either INF 120 or CSC 260? (Y/N) ". Eclipse will not let you run the program if a variable may not have been initialized. At the top of your code where you have
int INFCSCFee;
replace it with
int INFCSCFee = 0;
or initialize the variable somewhere else or with some other value.
Here is the fault
if (INFCSC.equals ("y")) INFCSCFee = (char) (CITFee * OnlineFee + 60);
This is the only place INFCSCFee can be initialised. So it is possible therefore that it has not been initialised by the time it is used. More generally, this is not allowed:
int x; // declare x - not yet initialised
if (someCondition)
x = 3; // initialise to 3
// if somecondition was false, x is still unitialised
System.out.println("x is "+x); // Error
You cannot use a variable declared in a method unless the compiler can gaurantee it has been initialised beore you us it. This would be allowed:
int x; // declare x - not yet initialised
if (someCondition)
x = 3;
else if (somethingElse)
x = 4;
else
x = 5;
// For all outcomes, x has been initalised, so it is safe to use
System.out.println("x is "+x);
This is allowed too:
int x; // declare x - not yet initialised
if (someCondition)
x = 3;
else
return;
// Although someCondition may have been false, if we reach this line of
// code, it is because someCondition was true and therefore x was initialised
System.out.println("x is "+x); // will print x is 3
Finally, you can initalise your variable at declaration time:
int x = 0;
Now, wherever x is used, it is gauranteed to be initalised, so you won't get a compile error. That's not necessarily a good thing, because that compiler error could actually be showing you a bug in your code, and you've suppressed it by giving the variable a default value.
I am trying to create a small Hotel application with a menu system. So far the user is asked for a room number (0-9) and a room name, once this is entered I want the user to be returned to the menu where the other menu options can be entered. I don't think the other menu options are working currently either :(
Here is my code so far:
package hotel;
import java.util.*;
public class Hotel2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[10];
myHotel[0] = new Room ();
myHotel[1] = new Room ();
myHotel[2] = new Room ();
myHotel[3] = new Room ();
myHotel[4] = new Room ();
myHotel[5] = new Room ();
myHotel[6] = new Room ();
myHotel[7] = new Room ();
myHotel[8] = new Room ();
myHotel[9] = new Room ();
String roomName;
String menuEntry = null;
int roomNum = 0;
String[] hotel = new String[11];
for (int x = 0; x < 10; x++ ) hotel[x] = "";
initialise(hotel);
while ( roomNum < 10 )
{
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
while (menuEntry.equals("1"))
{
System.out.println("Enter room number (0-9):" );
roomNum = input.nextInt();
if (roomNum < 10)
{
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
}
if (menuEntry.equals("V"))
{
for (int x = 0; x < 10; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
if (menuEntry.equals("E"));
{
}
if (menuEntry.equals ("D"))
{
System.out.println("Enter the room number which you would like to delete a customer from:");
roomNum = input.nextInt();
hotel[roomNum] = "empty";
}
}
}
private static void initialise( String hotelRef[] ) {
for (int x = 0; x < 10; x++ ) hotelRef[x] = "empty";
System.out.println( "initilise\n");
}
}
Your while loops waits for menuEntry to be different than 1, but you never change menuEntry inside the loop. Change it to do while loop
do {
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
System.out.println("Enter room number (0-9):" );
roomNum = input.nextInt();
if (roomNum < 10)
{
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
} while (menuEntry.equals("1"));
You should also insert the rest of the options into the loop and make the conditions to match the options in the menu.
Another option with while loop
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
while (menuEntry.equals("1")) {
System.out.println("Enter room number (0-9):" );
roomNum = input.nextInt();
if (roomNum < 10)
{
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
}
Something like this help your code to look more cleaner and understandable
while ( roomNum < 10 && menuEntry.equals("1") ){
//then perform your if statement
// or preferabley use a switch(menuEntry){}
}
Im suppose to write a code using an Array of numbers and apparently not a string and they need to be double. The way I wrote the code, the only way I know how, works. Maybe im making it too complicated and an array would make it simple idk. Im new to programming, new as in a few days. please help.
What is needed is:
Write a code that will average the input of 10 numbers and show the avg along with if they pass or fail. if < 50 fail, else > 50 pass.
we have to use an array, we need to use JOptionPane.showMessageDialog., the numbers need to be double and rounded to two decimals.
I declared double but i get an error if i enter a decimal number. If i just run the code as is, it will let me enter 10 numbers, avg them and then tell me if i pass or fail. Im just lost when it comes to using the other factors. thanks
the working code follows:
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail {
public static void main(String[] args) {
String firstNumber,
secondNumber,
thirdNumber,
fourthNumber,
fifthNumber,
sixthNumber,
seventhNumber,
eighthNumber,
ninethNumber,
tenthNumber;
double number1,
number2,
number3,
number4,
number5,
number6,
number7,
number8,
number9,
number10,
sum;
firstNumber =
JOptionPane.showInputDialog ( "Enter 1st Grade" );
secondNumber =
JOptionPane.showInputDialog ( "Enter 2nd Grade" );
thirdNumber =
JOptionPane.showInputDialog ( "Enter 3rd Grade" );
fourthNumber =
JOptionPane.showInputDialog ( "Enter 4th Grade" );
fifthNumber =
JOptionPane.showInputDialog ( "Enter 5th Grade" );
sixthNumber =
JOptionPane.showInputDialog ( "Enter 6th Grade" );
seventhNumber =
JOptionPane.showInputDialog ( "Enter 7th Grade" );
eighthNumber =
JOptionPane.showInputDialog ( "Enter 8th Grade" );
ninethNumber =
JOptionPane.showInputDialog ( "Enter 9th Grade" );
tenthNumber =
JOptionPane.showInputDialog ( "Enter 10th Grade" );
number1 = Integer.parseInt ( firstNumber);
number2 = Integer.parseInt ( secondNumber);
number3 = Integer.parseInt ( thirdNumber);
number4 = Integer.parseInt ( fourthNumber);
number5 = Integer.parseInt ( fifthNumber);
number6 = Integer.parseInt ( sixthNumber);
number7 = Integer.parseInt ( seventhNumber);
number8 = Integer.parseInt ( eighthNumber);
number9 = Integer.parseInt ( ninethNumber);
number10 = Integer.parseInt ( tenthNumber);
sum = (number1 + number2 + number3 + number4 + number5 + number6 + number7 + number8 +number9 + number10)/10;
JOptionPane.showMessageDialog (
null, "The Average is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE);
if (sum < 50){
JOptionPane.showMessageDialog (
null, "Fail", "Results",
JOptionPane.PLAIN_MESSAGE);
}else{
JOptionPane.showMessageDialog (
null, "Pass", "Results",
JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}
Woah there, that's a lot of repetition. You should probably clean this up with loops, like:
double sum = 0; // initialize variable for sum of all the numbers
for (int i = 1; i <= 10; i ++) { // go from 1 to 10
String strNum = JOptionPane.showInputDialog("Enter grade #" + i); // prompt for input
double dNum = Double.parseDouble(strNum); // convert to double
sum += dNum; // add to sum
}
double avg = sum / 10; // now get the average
number1 = Integer.parseInt ( firstNumber); expects to recieve a string that "looks like" an integer, if you give it something that "looks like" anything else you will recieve an error. You should instead use Double.parseDouble(firstNumber);
And yes, you should absolutely use an array for this. The use of arrays allows for a far shorter program;
public class UseArrays {
public static void main(String[] args){
int numberOfEntries=10
double[] numbers =new double[numberOfEntries];
for(int i=0;i< numbers .length;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
numbers[i]=Double.parseDouble(option);
}
double sum=0;
for(int i=0;i< numbers .length;i++){
sum+=numbers[i];
}
double average=sum/10;
System.out.println(average);
}
}
Note also that with the program created in this way it is incredibly easy to change the number of entries, in addition to being much shorter to write. You would not want to type out each entry by hand if you had hundreds, thousands or even millions of entries.
You could make this program even shorter by not storing each double then adding them later (which would also make using the array unnessissary). This program would look like;
public class DontUseArrays {
public static void main(String[] args){
int numberOfEntries=10
double sum=0;
for(int i=0;i< numberOfEntries;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
double number=Double.parseDouble(option);
sum+=number;
}
double average=sum/10;
System.out.println(average);
}
}
Here's a fragment of code that should get you on your way:
public void test() {
double[] numbers = new double[10];
double sum = 0;
for ( int i = 0; i < numbers.length; i++ ) {
String number = JOptionPane.showInputDialog ( "Enter Grade "+(i+1) );
numbers[i] = Double.parseDouble(number);
sum += numbers[i];
}
}
What if you had to calculate 1000 grades? That's why we use arrays.
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail
{
public static void main(String[] args)
{
String[] mumStr = new String[10];
double sum = 0;
for (int i = 0; i < numStr.length; i++) //0 to 10 (10 not included)
{
numStr[i] = JOptionPane.showInputDialog ( "Enter Grade " + (i+1)+ ": " );
sum += Double.parseDouble(numStr[i]);
}
double avg = sum / numStr.length;
JOptionPane.showMessageDialog (null, "The Average is " + avg, "Results", JOptionPane.PLAIN_MESSAGE);
if (avg < 50)
{
JOptionPane.showMessageDialog (null, "Fail", "Results", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog (null, "Pass", "Results", JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}
To parse your Strings to the double type use Double.parseDouble(String s)
You can assign the ints returned from Integer.parseInt(String s) to your double variables, because doubles are higher precision than ints and so type conversion happens automatically without the need for an explicit cast.
However you can not parse any String with a decimal point to an int using Integer.parseInt(String s), by definition.
Additional point - There's no need to declare the String variables, or have a separate variable for each number - it'll be much cleaner to use an array and a loop to input the numbers, and possibly sum the numbers as they come in, something like:
double[] numbers = new double[10];
double sum = 0d;
for(int i = 0; i < numbers.length; i++ ) {
numbers[i] = Double.parseDouble(JOptionPane.showInputDialog ( "Enter 1st Grade" ));
sum += numbers[i];
}
double mean = sum / numbers.length;