Using return method to do this assignment
Write a method to delete character in a string.
Example:
A call to deleteChar(?hello?, ?l?) will return heo
A call to deleteChar(?madam?, ?a?) will return mdm
I have tried to solve this problem using return method, but it doesn't work. Please help me do this exercise with return method in main method.
Here is my work, using void method in main method
private static void deleteChar(String input, String deletedChar) {
for (int i = 0; i < input.length(); i++) {
if (!(input.charAt(i) + "").equalsIgnoreCase(deletedChar)) {
System.out.print(input.charAt(i));
public static void main(String[] args) {
String input, deletedChar;
Scanner kb = new Scanner(System.in);
System.out.print("Enter a String: ");
input = kb.nextLine();
System.out.println("Enter a letter you want to delete from String: ");
deletedChar = kb.nextLine();
deleteChar(input, deletedChar);
}
In your main method, you replace the line
deleteChar(input, deletedChar);by
String result = deleteChar(input, deletedChar); and the method by :
private static String deleteChar(String input, String deletedChar) {
return input.replaceAll(deletedChar, "");
}
Similar Messages
-
Using a method return in a taskflow router
I have a custom data control with following method:
public String getOutcome(){
String outcome;
//do stuff
if(something)
outcome = "o1";
else
outcome = "o2";
return outcome;
}This method is dropped on the taskflow as method call.
How can I use the return value of this method call to drive the decision of a router component of the taskflow?We can not used the method for decision the navigation rule.You have to use the router for resolving your issue.
Or if you want to navigate through the method then inside your method you have to programmatically navigate to pages on the basis of diffenent condition.
you can used following code for navigation .
FacesContext fc = FacesContext.getCurrentInstance();
Application application = fc.getApplication();
NavigationHandler navHandler = application.getNavigationHandler();
navHandler.handleNavigation(fc,null, "navigation case name"); Thanks
Prateek -
Why do we use ejbCreate() method? what does it returns?
why do we use ejbCreate() method? what does it returns?
People think its easier to get answers handed tothem
instead of looking...I do my best to disabuse them of that notion.I've given up on that idea, too much hard work.
Instead I've just written off the entire current generation of schoolkids as useless, good only for (at most) menial labour. -
I bought CS3 several years ago while in school, but had to drop out before I even opened the software. A few months ago I opened and installed the software and used Photoshop to complete a review project in preparation for my return to school. This morning when I tried to open Photoshop again I got a message saying the license didn't support the software anymore and I would need to check with my IT administrator or contact Adobe. I tried calling Adobe but the recorded message said CS was not phone supported. I know it took me a long time to get back to school, but it seems sad to waste the $1,000 I spent on the software. Is there a solution to this issue or do I need to buy new software? Thank you for your help if you have any suggestions.
Error "Licensing has stopped working" | Mac OS
Mylenium -
Void Methods and Value Returning Methods in Java
Hello,
I'm new here so please let me know if I overstep any of the rules or expectations. I merely want to learn more about Java Programming efficiently, and easily. I can ask and discuss these topics with my online prof, but she doesn't have much time.
So right now I'm trying to solve a problem. It's a typical college level computing problem which I've already turned in. So I'm not looking for someone to do my homework for me or something. It's just that the program didn't work. Even though I probably won't get a very good grade for it, I want to
make it work! I'm kind of slow when it comes to java so just bear with me.
The prof wanted us to write an algorithm that reads a student's name and 6 exam scores. Then it computes the average score for each student, assigns a letter grade, using a rating scale:
90 and above = A
80 - 89 = B
70 ? 79 = C
60 - 69 = D
Less then 60 ? F
We had to use a void method to determine the average score for each student, a loop inside the method to read the and sum the 6 scores but without outputting the average score. The sum and average had to be returned in and output in void main.
Then we had to use a value-returning method CalculateGrade to determine and return the grade for each student. But it can't output the grade because that must be done in void main.
Finally the class average must be output.
Our prof gave us a list of student names with their 6 scores.
Ward 100 54 98 65 35 100
Burris 89 65 87 84 15 32
Harris 54 21 55 87 70 54
Bettis 43 55 68 54 15 25
Staley 87 54 98 45 54 56
Randle 54 87 54 98 65 15
Maddox 56 14 40 50 40 50
Roth 30 40 54 78 24 19
Holmes 14 87 98 34 55 57
So all the data had to be read from a file and the results output to a file. Also we couldn't use 'global variables'. We had to use the appropriate parameters to pass values to and from methods.
Question 1: What does she mean by 'no global variables'? Maybe she means: don't use "*double test1, test2, test3, test4, test5*;"
Anyway because I'm a slow learner with Java, I end up looking for sample programs that seem to do a similar job as the problem posed. So with this program I decided to adapt a program called Comparison of Class Averages.
//Program: Comparison of Class Averages.
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
public class DataComparison
public static void main (String[] args) throws
FileNotFoundException, IOException
//Step 1
String courseId1; //course ID for group 1
String courseId2; //course ID for group 2
int numberOfCourses;
DoubleClass avg1 = new DoubleClass(); //average for a course
//in group 1
DoubleClass avg2 = new DoubleClass(); //average for a course
//in group 2
double avgGroup1; //average group 1
double avgGroup2; //average group 2
String inputGroup1;
String inputGroup2;
StringTokenizer tokenizer1 = null;
StringTokenizer tokenizer2 = null;
//Step 2 Open input and output files
BufferedReader group1 =
new BufferedReader(new FileReader("a:\\group1.txt"));
BufferedReader group2 =
new BufferedReader(new FileReader("a:\\group2.txt"));
PrintWriter outfile =
new PrintWriter(new FileWriter("a:\\student.out"));
DecimalFormat twoDecimal =
new DecimalFormat("0.00"); //Step 3
avgGroup1 = 0.0; //Step 4
avgGroup2 = 0.0; //Step 5
numberOfCourses = 0; //Step 6
//print heading: Step 7
outfile.println("Course No Group No Course Average");
inputGroup1 = group1.readLine(); //Step 8
inputGroup2 = group2.readLine(); //Step 9
while((inputGroup1 != null) &&
(inputGroup2 != null)) //Step 10
tokenizer1 = new StringTokenizer(inputGroup1);
courseId1 = tokenizer1.nextToken(); //Step 10a
tokenizer2 = new StringTokenizer(inputGroup2);
courseId2 = tokenizer2.nextToken(); //Step 10b
if(!courseId1.equals(courseId2)) //Step 10c
System.out.println("Data error: Course IDs "
+ "do not match.");
System.out.println("Program terminates.");
outfile.println("Data error: Course IDs "
+ "do not match.");
outfile.println("Program terminates.");
outfile.close();
return;
else //Step 10d
calculateAverage(group1, tokenizer1, avg1); //Step 10d.i
calculateAverage(group2, tokenizer2, avg2); //Step 10d.ii
printResult(outfile,courseId1,1,avg1); //Step 10d.iii
printResult(outfile,courseId2,2,avg2); //Step 10d.iv
avgGroup1 = avgGroup1 + avg1.getNum(); //Step 10d.v
avgGroup2 = avgGroup2 + avg2.getNum(); //Step 10d.vi
outfile.println();
numberOfCourses++; //Step 10d.vii
inputGroup1 = group1.readLine(); //Step 10e
inputGroup2 = group2.readLine(); //Step 10f
}//end while
if((inputGroup1 != null) && (inputGroup2 == null)) //Step 11a
System.out.println("Ran out of data for group 2 "
+ "before group 1.");
else //Step 11b
if((inputGroup1 == null) && (inputGroup1 != null))
System.out.println("Ran out of data for "
+ "group 1 before group 2.");
else //Step 11c
outfile.println("Avg for group 1: " +
twoDecimal.format(avgGroup1 / numberOfCourses));
outfile.println("Avg for group 2: " +
twoDecimal.format(avgGroup2 / numberOfCourses));
outfile.close(); //Step 12
public static void calculateAverage(BufferedReader inp,
StringTokenizer tok,
DoubleClass courseAvg)
throws IOException
double totalScore = 0.0;
int numberOfStudents = 0;
int score = 0;
if(!tok.hasMoreTokens())
tok = new StringTokenizer(inp.readLine());
score = Integer.parseInt(tok.nextToken());
while(score != -999)
totalScore = totalScore + score;
numberOfStudents++;
if(!tok.hasMoreTokens())
tok = new StringTokenizer(inp.readLine());
score = Integer.parseInt(tok.nextToken());
}//end while
courseAvg.setNum(totalScore / numberOfStudents);
}//end calculate Average
public static void printResult(PrintWriter outp,
String courseId,
int groupNo, DoubleClass avg)
DecimalFormat twoDecimal =
new DecimalFormat("0.00");
if(groupNo == 1)
outp.print(" " + courseId + " ");
else
outp.print(" ");
outp.println("\t" + groupNo + "\t "
+ twoDecimal.format(avg.getNum()));
So my adaptation turned out like this:
//Program: Compute individual and class averages from input file.
import java.io.*;
import java.util.*;
public class Exams
public static void main (String[] args)
throws FileNotFoundException
//Step 1
String nameId; //student name ID for list
int numberOfStudents;
DoubleClass avg = new DoubleClass(); //average for a student
//in list
double avgList; //average for list
//Step 2 Open the input and output files
Scanner group1 = new Scanner(new FileReader("c:\\list.txt"));
PrintWriter outfile = new PrintWriter("c:\\student.out");
avgList = 0.0; //Step 3
numberOfStudents = 0; //Step 5
//print heading: Step 6
outfile.println("NameID List Student Average");
calculateAverage(list, avg); //Step 7d.i
printResult(outfile,nameID, avg); //Step 7d.iii
avgList = avgList + avgList.getNum(); //Step 7d.v
outfile.println();
numberOfStudents++; //Step 7d.vii
outfile.printf("Avg for List: %.2f %n",
(avgList / numberOfStudents));
public static void calculateAverage(Scanner inp,
DoubleClass courseAvg)
double totalScore = 0.0;
int numberOfStudents = 0;
int score = 0;
score = inp.nextInt();
courseAvg.setNum(totalScore / numberOfStudents);
}//end calculate Average
public static void printResult(PrintWriter outp,
String nameId,
int groupNo, DoubleClass avg)
if (list == list)
outp.print(" " + nameId + " ");
else
outp.print(" ");
outp.printf("%9d %15.2f%n", list, avg.getNum());
I guess I was trying to find a shortcut that ended up being a long cut. Here's the algorithm I wrote.
Algorithm
1.) Initialize the variables
2.) Get the student name and his/her accompanying 6 exam scores, limiting the number of scores to 6.
3a.) Calculate score of 6 exams for each student using void method called CalculateAverage.
3b.) Use a loop inside the method to read and sum the six scores.
4.) Use value-returning method CalculateGrade to determine and return each student's grade.
5.) Output each student's grade in void main.
6.) Calculate the average score for all students
7.) Output entire class average
And now I'm trying to piece together code to match each step of the algorithm starting from scratch.
So I got the code for outputting each students grade in void:
public static void printGrade(double testScore)
System.out.print("Line 10: Your grade for "
+ "the course is ");
if (testScore >= 90)
System.out.println("A");
else if (testScore >= 80)
System.out.println("B");
else if (testScore >= 70)
System.out.println("C");
else if (testScore >= 60)
System.out.println("D");
else
System.out.println("F");
This code can read the the file with the scores:
Scanner inFile =
new Scanner(new FileReader("a:\\studentlist.txt"));
PrintWriter outFile =
new PrintWriter("a:\\avg.out");
courseGrade = inFile.nextDouble();
studentName=inFile.nextChar();
while (inFile.hasNext())
studentName= inFile.next().charAt(0);
courseGrade= inFile.nextDouble();
I'm just trying to piece this thing together. Any tips would be appreciated. I will return with more pieces to the puzzle soon. As you can tell it's all kind of disorganized, and scatterbrained. Just trying to find some simplification or distillation, or recommendations.
WRHello,
Thanks for your reply. So I take it you are more familiar with Object Oriented Programming more than Procedural Based Programming?
Well the teacher insisted I follow the algorithm instead of trying to adapt another program to the problem. But sometimes that approach saves time I've noticed since many of the code examples we study in Java are like 'the golden oldies'.
The student gradebook problem is repeated over and over in different forms. Maybe if I just approached the problem more linearly:
Algorithm
1.) Initialize the variables
String studentId
int numberOfStudents
DoubleClass avg = new DoubleClass(); //average for a student
double avgGroup: //average for all students2.) Get the student name and his/her accompanying 6 exam scores.
Scanner group = new Scanner(new FileReader("c:\\list.txt"));
PrintWriter outfile = new PrintWriter("c:\\student.out"));
3a.) Calculate score of 6 exams for each student using void method called CalculateAverage using a loop to read and sum the six scores. The loop must be inside the method. It does not output the average score. The sum and average must be returned and output in void main.
method calculateAverage
double totalScore //to store the sum of all the scores of each student
int numberOfExams; //to store the number of
int score; //to read and store a course score
double totalScore = 0.0
int numberOfExams = 0;
int score = 0;3b.) Use a loop inside the method to read and sum the six scores.
Using psuedocode (since the variables have been declared and initialized)
i)get the next student score
RIght here my approach of adapting another program to my new program becomes problematic
the pseudocode here is:
ii) while (score != -999):
I.) update totalScore by adding course score read in step i.
II.) increment numberOfExams by 1
III.) Get the nex student score
iii) studentAvg.setNum(totalScore / numberOfExams);
*What is the purpose of the statement while (score != -999)?*
I don't see why they picked -999? Will this loop allow me to read an endless number of student names and theri accompanying number of exams and then find the average for each student?
I'll go into the next algorithmic steps later.
4.) Use value-returning method CalculateGrade to determine and return each student's grade.
5.) Output each student's grade in void main.
6.) Calculate the average score for all students
7.) Output entire class average
Thanks ahead of time for any suggestions, tips. -
can anyone out there help me with this assignment ????? i`ll attach the file to this topic
In this assignment, you are to write a Java applet, using arrays, to simulate the functions of a drinks-vending machine.
The assignment requirements described below are broken down into 2 stages of development, described in this document
as 'Basic Requirements' and 'Additional Features'. You are advised to do your programming progressively in these
stages. An Activity Plan has also been specified for you to follow. Refer to the 'Grading Criteria' on page 5 to have
an idea of how the different components are graded.
1. 1. BACKGROUND
A company intends to build computerised drinks-vending machines to enlarge its business portfolio. You have been tasked to develop a
Java applet that simulates the operation of such a machine to determine if it will meet their needs.
2. 1. BASIC REQUIREMENTS
The machine should have a wide range of drinks available. A customer can choose a drink according to the following criteria:
a) a) Category of Drinks
� � Beverages
� � Soft Drinks
(For beverages, there is choice of whether sugar and/or creamer is required, for which there is an additional charge.)
b) b) Type of Beverages
� � Hot
� � Cold
Once a customer has specified the drink he wants, the amount payable is displayed. The unit prices to be displayed are as follows:
Drinks Price per Cup/Packet ($)
Beverage: Coffee 1.00
Tea 1.20
Milo 1.40
Horlicks 1.35
Chrysanthemum 1.00
Ginger 0.80
Soft Drinks: Apple 1.40
Orange 1.40
Pineapple 1.50
Carrot 2.00
Longan 1.20
Bandung 1.00
(For beverages, a request for sugar or creamer attracts an additional charge of $0.10 each. Creamer is not applicable for
chrysanthemum and ginger.)
The customer may then confirm his order by entering the amount payable (this symbolises his payment for the drink). Whenever the
payment input is not correct, an appropriate error message is displayed, whereupon the customer has to re-enter the amount again.
When the correct amount is paid, the required drink is dispensed.
For any drink that is out of stock, a message is shown, stating that it is not available. Each time a drink is dispensed, the stock for that
drink is updated (For beverages, the stock is stored in units of servings for each cup.) To simplify the testing, you may start the simulation
by setting the stock for each drink to 10 packets or cup-servings.
3. 2. ADDITIONAL FEATURES
In addition, the simulator can have the following features:
a) a) Smart Graphical User-Interface (GUI)
You may build upon the basic requirements by recommending alternative drinks of the same category, whenever a requested
drink is not available (as signified from the stock). In this case, only drinks which are available (i.e., in sufficient stock) are
displayed for the customer to choose. And if only soft drinks are available, the selections for creamer and sugar should be disabled.
b) b) Multiple Orders
A customer could order more than one drink. The system could allow him to specify as many drinks as he wants, prompting him
for an appropriate payment, and then dispensing the drinks accordingly, subject to availability. This may also entail the extension
of the graphical user-interface.
c) c) Sales Analysis
Periodically, the total revenue accumulated since the last collection is printed in descending order of sales for each drink sold,
together with a grand total. The cash is then cleared from the machine. This feature requires password-protection.
d) d) Replenishment of Stock
Periodically, the stock is checked to determine how much of each drink needs to be replenished. For this purpose, a list of the
drinks with the corresponding quantity on hand is printed in ascending order of stock level. Drinks with insufficient stock are
topped up to a level of 10 servings or packets. This feature also requires password-protection.
e) e) Any other relevant features
You are limited only by your creativity. You can add any other relevant features for this project. Please consult your tutor before
you proceed.
To qualify for the full marks for this section, you need to implement 2 features, at least one of which must be either (a) or (b) above.
4. 3. ACTIVITY PLAN
Suggestions for Getting Started
There are many ways that you could complete this assignment. The most important part is to think about the entire project first so that
it is easy to integrate the various pieces. You should also consider what type of graphics you want to incorporate.
a) a) Analysis
1. Understand the program specification and the requirements before attempting the project.
b) b) Program Design
2. Work out the GUI components (e.g., TextFields, CheckBoxes, ChoiceBoxes, Buttons, etc.) needed to get the user input.
3. 3. Work out the main logic of the program using modular programming techniques; i.e. use methods appropriately. E.g., tasks that perform
4. 4. a well-defined function or those that are repeated should be coded as methods. For example, you can write the methods, displayBill(),
5. 5. makePayment(), computeTotal(), dispenseDrink(), etc. You need to think carefully about the return type and the parameters of each
6. 6. method.
7. 7. You are required to use arrays appropriately for this assignment. Marks will be deducted for inefficient use or non-usage of arrays.
c) Implementation & Testing
8. 8. Write the method definition of each method ONE at a time.
9. 9. Test your program logic to make sure that it works. In the interim, you can use �g.drawString(�);� or �System.out.println(�);� to print
10. 10. out intermediate results so that you can see whether your program is working correctly. You may not want to bother about error-checking
11. 11. at this point. You should test each method as soon as it is written, as it is much easier to debug your program in this way.
5. 4. DELIVERABLES
By Monday, 25th February before 5:00 p.m., hand in the following to the School of ICT Administrative Office at Block 31, level 8:
� � A copy of the printout of your .java file.
� � A diskette labelled with your name, group, student ID. The diskette should contain ALL the necessary files (.java, .html, and .class)
to run your applet.
� � The above in an envelope topped with the Assignment Completion Report (see pages 6, 7 & 8). Page 6 is for you to paste on top
of your envelope whilst pages 7 and 8 are for you to document your Test Plan, and write your comments (including any
special instructions to run your program) - to be inserted into the envelope.
In your .java program, you are to include a blocked comment at the top stating:
q q Your name, group, student ID.
q q Assumptions (if any) or any deviations from the specified requirements.
q q Any features that you would like to highlight.
6. 5. WALK-THROUGH OF PROGRAM
Monday 25th February at 9:30 a.m. SHARP
In the walk-through, you will be asked to give short, written answers to some questions about your program. These questions will assess
your basic understanding of the code that you are handing in. If you fail to display adequate understanding of your own program, you can
be down-graded by up to two letter grades from what you would have normally received. It is also possible that you will be called to
perform a demonstration cum explanation of your work if it is suspected that you have copied someone else�s work. Lesson: do your own
work and you will have no problem!
7. 6. GRADING CRITERIA FOR PROGRAMMING
Correct and robust implementation of basic features 55 %
Additional features 20 %
Programming style:� � Program design� � Appropriate use of arrays� � Appropriate use of variables, methods, and parameters� � Proper usage of control structures (e.g. if/else, loops) 15 %
Good programming practice:� � Meaningful variable names � � Proper indentations� � Useful and neat comments 5 %
Adequate (black-box) testing:� � Suitably-designed test plan 5 %
Total: 100 %
PROBLEM SOLVING & PROGRAMMING II
(Dip IT/MMC/EI, Year 1, Semester 2)
Assignment Completion Report (to be attached to cover of envelope)
Name: ___________________________________ Group: ________
ID: ___________________ Date & Time submitted: ____________
Requirements % Done (0-100) Remarks
BASIC FEATURES
� � Can choose category (and select appropriate additives)
� � Can choose drink (with error checking)
� � Can display amount payable
� � Can indicate availability of drink (with error checking)
� � Can accept payment for drink (with error checking)
� � Can dispense drink
� � Can update stock
ADDITIONAL FEATURES
� � Smart GUI
� � Multiple Orders
� � Sales Analysis (with password checking)
� � Stock Replenishment(with password checking)
� � Any other relevant features
Test Plan
Using black-box testing, record your test specification and the results according to the following format (the examples here are provided
for your reference only):
Test No. Purpose Test Shot/Data Expected Result Actual Result
E.g. 1a) Check whether beverage can be selected Click on �Chrysanthe-mum� button Checkbox for �Sugar� but not �Creamer� appear �Sugar� and checkboxes appeared
E.g. 1b) Check whether chrysanthemum with sugar can be ordered Select sugar and click on �Order� button Amount payable appears as �$1.10� (i.e., $1.00 + $0.10) Amount payable shown as $1.10
E.g. 1c) Check whether correct payment can be accepted Enter �1.00� in �Payment� textfield Error message �Insufficient payment - $0.10 short� appears Confirmation message �Drink being dispensed� appeared � ERROR!
E.g. 1d) Re-test 1c), after amending program As above As above Error message �Insufficient payment - $0.10 short� appeared
etc.
etc.
Remember to hand in this test plan together with the other deliverables in the envelope.
Have you�
1. 1. Checked to make sure program still works properly even with windows resized?
2. 2. Tested your program thoroughly, as if you're trying to break it?
Any comments about this assignment? Any special instructions to run your program? Write it here.public class testing1 {
String gg;
public void testing3() {
System.out.print(gg); }
// this is are constructor for the object and method we are going to make
next code
class testing {
public static void main(String[] args) {
testing1 tes = new testing1();
tes.gg = "hello there";
tes.testing3(); //here we have made a object and a method
hope this helps -
Need help with this assignment!!!!
Please help me with this. I am having some troubles. below is the specification of this assignment:
In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
� / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
Random randomGen = new Random ( System.currentTimeMillis() );
Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
double xPos = (randomGen.nextDouble()) * 2 - 1.0;
double yPos = (randomGen.nextDouble()) * 2 - 1.0;
To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
The class that you will be writing will be called CalculatePI. It will have the following structure:
import java.util.*;
public class CalculatePI
public static boolean isInside ( double xPos, double yPos )
public static double computePI ( int numThrows )
public static void main ( String[] args )
In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
Computation of PI using Random Numbers
Number of throws = 100, Computed PI = ..., Difference = ...
Number of throws = 1000, Computed PI = ..., Difference = ...
Number of throws = 10000, Computed PI = ..., Difference = ...
Number of throws = 100000, Computed PI = ..., Difference = ...
* Difference = Computed PI - Math.PI
In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
and below is what i have so far:
import java.util.*;
public class CalculatePI
public static boolean isInside ( double xPos, double yPos )
boolean result;
double distance = Math.sqrt( xPos * xPos + yPos * yPos );
if (distance < 1)
result = true;
return result;
public static double computePI ( int numThrows )
Random randomGen = new Random ( System.currentTimeMillis() );
double xPos = (randomGen.nextDouble()) * 2 - 1.0;
double yPos = (randomGen.nextDouble()) * 2 - 1.0;
boolean isInside = isInside (xPos, yPos);
int hits = 0;
double PI = 0;
for ( int i = 0; i <= numThrows; i ++ )
if (isInside)
hits = hits + 1;
PI = 4 * ( hits / numThrows );
return PI;
public static void main ( String[] args )
Scanner sc = new Scanner (System.in);
System.out.print ("Enter number of throws:");
int numThrows = sc.nextInt();
double Difference = computePI(numThrows) - Math.PI;
System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + computePI(numThrows) + ", Difference = " + Difference );
}when i tried to compile it says "variable result might not have been initialized" Why is this? and please check this program for me too see if theres any syntax or logic errors. Thanks.when i tried to compile it says "variable result might not have been
initialized" Why is this?Because you only assigned it if distance < 1. What is it assigned to if distance >= 1? It isn't.
Simple fix:
boolean result = (distance < 1);
return result;
or more simply:
return (distance < 1);
and please check this program for me too see if theres any syntax or
logic errors. Thanks.No, not going to do that. That's much more your job, and to ask specific questions about if needed. -
Hey peeps
after some guidance
ok, so my lecturer for programming is quite well known in the java world, although thats probs going to get shot down now :D he wrote bluej and the text book objects first. This week he set me an assignment and i have done all the base tasks and all the challenge tasks, but we get marked for comment considteny and layout of brackets etc to.
so one of the challenge tasks was to return an avergae playing time using double, is the correct way, the 100% correct way of doing this
public double averageTrackLength()
return (double) totalPlayingTime / tracksPlayed;
}or does it need editing
thanks very muchok, i think i worded it wrong, what i mean is, have i used the double function correctly, as in, to return a double value to you only need
public double averageTrackLength()
return (double) totalPlayingTime / tracksPlayed;
}becuase some people online from what i have read suggest this is how to do ti
public double divide(){
return (double)x / (double)y;
}which is "correct"? :D
also, finally, sorry to get on all of your tits, i have a concern with my commenting, have i just over killed commenting :D
* This class is used to interact with the interface in order
* to let the user play the appropriate songs. Checks are in
* order to ensure that valid entry of selection means no
* programme crashes, and all relevant fields have been initialised.
* The track is selected by the user, then they can push play
* on the interface, once this is done, if a new track is selected
* the current track will stop, be reset to the beginning, and on
* the users selection of play, the new track shall begin. The stop
* button allwos the user to stop the track, at which point it rewinds
* it to the beginning again.
* @author Ricki Lambert
* @version 0.1 (19/10/2008)
public class Player
private PlayList playList; //Holds an object of PlayList class
private Track track; //Holds an object of Track class
private int tracksPlayed; //Used to store the int sum of tracks played
private int totalPlayingTime; //Used to store the integer value of the toal playing time
* This is the constructor for the Player class. It sets the
* tracksPlayed field to 0 and the same for totalPlayingTime. Also
* it creates a new playList from the Playlist class. Every object
* of Player will now be initialised with these fields values.
public Player()
playList = new PlayList("audio");
tracksPlayed = 0;
totalPlayingTime = 0;
* Return the track collection currently loaded in this player.
public PlayList getPlayList()
return playList;
* This method is used to play music in the G.U.I
* The method is called, and every time this happens, the counter adds
*one to the tracksPlayed variable. Then we check if the variable (that holds an object of Track)
*is null. If it is we return (exit the method) to avoid crashing the programme. If not, call the stop method
*using an internal method call, then call the play method of the track object we created. At the end, we add
*the total length of the track to the totalPlayingTime variable.
public void play()
tracksPlayed = tracksPlayed + 1;
if (track == null){
return;
stop();
track.play();
totalPlayingTime = totalPlayingTime + track.getDuration();
* Checks to see if the track object is null, if so exit the method
* using return, if not, call the stop method of the track object and
* then call the rewind method to put that track to the beginning.
public void stop()
if (track == null){
return;
track.stop();
track.rewind();
* To set the track we check if the track object is not null.
* Then if it is call the stop method by
* using an internal method call. Then we just assign the
* track object to the playlists getTrack method (this uses
* the parameter to pass the number required to the method)
public void setTrack(int trackNumber)
if (track != null){
stop();
track = playList.getTrack(trackNumber);
* Get the track name and return it. If the track is null
* then return an empty string, else return the tracks name
* by calling the objects method
public String getTrackName()
if (track == null){
return "";
else{
return track.getName();
* Return information about the currently selected track. The information
* contains the track name and playing time, in the format
* track-name (playing time)
* Return an empty string if no track is selected.
public String getTrackInfo()
if (track == null){
return "";
else{
return "The track is called " + track.getName() + " The Track lasts for " +
track.getDuration() + " seconds" ;
* Return the integer value of the tracksPlayed variable
public int getNumberOfTracksPlayed()
return tracksPlayed;
* Return the integer value of the totalPlayingTime variable
public int getTotalPlayedTrackLength()
return totalPlayingTime;
* Return the result of totalPlayingTime divided by tracksPlayed
* This is returned as a double data type value.
public double averageTrackLength()
return (double) totalPlayingTime / tracksPlayed;
}Edited by: compSciUndergrad on Oct 19, 2008 12:58 PM
Edited by: compSciUndergrad on Oct 19, 2008 12:58 PM -
Setting value for attribute 'PO_NUMBER_SOLD' using setter method
Hi Experts,
I need to set the value of a screen field according to some condition. I am using setter method of this attribute to set the value but it is not getting changed.
I have written following code in DO_PREPARE_OUTPUT method of implementation class ZL_ZZBT131I_ZCREDITCHECK_IMPL using setter method of attribute
Get Referral Authorization Code
lv_val1 = me->typed_context->crechkresph->get_po_number( attribute_path = 'PO_NUMBER' ).
me->typed_context->crechkresph->set_po_number( attribute_path = 'PO_NUMBER'
value = ' ' ).
while debugging I found that in method set_po_number set_property method has been used:--
current->set_property(
iv_attr_name = 'PO_NUMBER_SOLD' "#EC NOTEXT
iv_value = <nval> ).
In set_property method following code is getting executed
if ME->IS_CHANGEABLE( ) = ABAP_TRUE and
LV_PROPS_OBJ->GET_PROPERTY_BY_IDX( LV_IDX ) ne IF_GENIL_OBJ_ATTR_PROPERTIES=>READ_ONLY.
if <VALUE> ne IV_VALUE.
if ME->MY_MANAGER_ENTRY->DELTA_FLAG is initial.
first 'change' -> proof that entity is locked
if ME->MY_MANAGER_ENTRY->LOCKED = FALSE.
if ME->LOCK( ) = FALSE.
return.
endif.
endif.
flag entity as modified
ME->MY_MANAGER_ENTRY->DELTA_FLAG = IF_GENIL_CONTAINER_OBJECT=>DELTA_CHANGED.
endif.
ME->ACTIVATE_SENDING( ).
change value
<VALUE> = IV_VALUE.
log change
set bit LV_IDX of ME->CHANGE_LOG->* to INDICATOR_SET.
endif.
else.
check if it is a real read-only field or a display mode violation
assert id BOL_ASSERTS subkey 'READ-ONLY_VIOLATION'
fields ME->MY_INSTANCE_KEY->OBJECT_NAME
IV_ATTR_NAME
condition ME->CHANGEABLE = ABAP_TRUE.
endif.
and in debugging I found that if part ( ME->IS_CHANGEABLE( ) = ABAP_TRUE and
LV_PROPS_OBJ->GET_PROPERTY_BY_IDX( LV_IDX ) ne IF_GENIL_OBJ_ATTR_PROPERTIES=>READ_ONLY) fails and hence else part is getting executed and hence my field a real read-only field or a display mode violation is happening according to comments in code.
What shall I do so that I would be able to change the screen field value?
Any help would be highly appreciated.
Regards,
VimalHi,
Try this:
data: lr_entity type cl_crm_bol_entity.
lr_entity = me->typed_context->crechkresph->collection_wrapper->get_current( ).
lr_entity->set_property( iv_attr_name = 'PO_NUMBER' value = '').
Also, make sure the field is not read-only.
Regards
Prasenjit -
this is a part of my assignment, and im having trouble figuring out how to write this method. any help would be appreciated
"Suppose the bank wants to keep track of how many accounts exist.
a. Declare a private static integer variable numAccounts to hold this value. Like all instance and static variables, it will
be initialized (to 0, since it?s an int) automatically.
b. Add code to the constructor to increase this variable every time an account is created.
c. Add a static method getNumAccounts that returns the total number of accounts. Think about why this method
should be static ? its information is not related to any particular account."
// Account.java
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
public class Account
private double balance;
private String name;
private long acctNum;
private int numAccounts; <------ i added this, is that right?
//Constructor -- initializes balance, owner, and account number
public Account(double initBal, String owner, long number)
balance = initBal;
name = owner;
acctNum = number;
// Checks the number of accounts
public static numAccts(int number) <------- Added this method, pretty sure this isnt the way im supposed to do this
number = numAccounts;
//Returns number of accounts
public static getNumAccounts() <------------Added this
return numAccts;
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
public void withdraw(double amount)
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
// Adds deposit amount to balance.
public void deposit(double amount)
balance += amount;
// Returns balance.
public double getBalance()
return balance;
// Returns a string containing the name, account number, and balance.
public String toString()
return ?Name:? + name +
?\nAccount Number: ? + acctNum +
?\nBalance: ? + balance;
}but now i have another problem. i am getting an error
Account.java:93: invalid method declaration; return type required
public static AccountConsolidate(Account acct1, Account acct2)
^
1 error this is the assignment for this method:
Add a static method Account consolidate(Account acct1, Account acct2) to your Account class that creates a new
account whose balance is the sum of the balances in acct1 and acct2 and closes acct1 and acct2. The new account should
be returned. Two important rules of consolidation:
? Only accounts with the same name can be consolidated. The new account gets the name on the old accounts but a
new account number (a random number).
? Two accounts with the same number cannot be consolidated. Otherwise this would be an easy way to double your
money!
// Account.java
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
public class Account
private double balance;
private String name;
private long acctNum;
private static int numAccounts;
private double newAccount;
//Constructor -- initializes balance, owner, and account number
public Account(double initBal, String owner, long number)
balance = initBal;
name = owner;
acctNum = number;
numAccounts++;
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
public void withdraw(double amount)
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
// Adds deposit amount to balance.
public void deposit(double amount)
balance += amount;
// Returns balance.
public double getBalance()
return balance;
//Returns number of accounts created
public static int getNumAccounts()
return numAccounts;
// Returns name on the account
public String getName()
return name;
// Returns account number
public long getAcctNum()
return acctNum;
// Close the current account.
public void close()
if (balance == 0)
numAccounts--;
System.out.println("CLOSED");
// Consolidates two accounts into one account.
public static AccountConsolidate(Account acct1, Account acct2)
newAccount = acct1.getBalance() + acct2.getBalance();
String name1 = acct1.getName();
String name2 = acct2.getName();
if(name1.equals(name2));
newAccount = newAccount.getAcctNum();
close acct2;
return newAccount;
// Returns a string containing the name, account number, and balance.
public String toString()
return "Name:" + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
// TestAccounts1
// A simple program to test the numAccts method of the
// Account class.
import java.util.Scanner;
public class TestAccounts1
public static void main(String[] args)
Account testAcct;
Scanner scan = new Scanner(System.in);
System.out.println("How many accounts would you like to create?");
int num = scan.nextInt();
for (int i=1; i<=num; i++)
testAcct = new Account(100, "Name", i);
System.out.println("\nCreated account " + testAcct);
System.out.println("Now there are " + Account.getNumAccounts() +
" accounts");
// TestAccounts2
// A simple program to test the methods of the
// Account class.
import java.util.Scanner;
public class TestAccounts2
public static void main(String[] args)
Account acct1;
Account acct2;
Account acct3;
Scanner scan = new Scanner(System.in);
int num;
System.out.println("Enter the name for account 1: ");
int name1 = scan.nextInt();
System.out.println("Enter the name for account 2: ");
int name2 = scan.nextInt();
System.out.println("Enter the name for account 3: ");
int name3 = scan.nextInt();
for (int i=1; i>=num; i++)
acct1 = new Account(100, "name1", i);
System.out.println("\nCreated account " + name1);
System.out.println("Balance Available " + acct1.getBalance() + " account number: " + acct1.getAcctNum());
} -
Hi all,
I am using return statement in JSP page after a redirect to stop executing that page. If the data bean is not present then it must go to previous page. When this return statement is executed the previous page is displayed but url in browser remains same. Why it is so ?. Is there any other way to tell a JSP page to stop executing and redirect to another page.
rgds
Antony PaulHi Antony,
do you use the "forward()" method or the "redirect()" method???
rgds
Howy -
Payment through using payment method "W"
Hi All,
We have to create a report for bank integtration and our client is using payment method "W" Bank Transfer Domestic.
Can anyone let me how we make vendor outgoing payments through bank using the payment method "W" what is the transaction to be used and where we have to give "W".
Thanks!
ZZia,
I believe the error is clear enough for you to interpret. You are trying to use a "Bank Transfer" payment method in a transaction that creates "Checks for Payment".
Here's what I suggest:
- if you have to use F-58, your choice of payment method is wrong. "W" is usually domestic transfer, while F-58 woudl rather use "C" or "D" or "E", or a similar method, depending on what is configured in your system for your company code / country
- if, on the other hand, you have to do a "domestic transfer" as suggested by the payment method "W", then your choice of transaction is wrong. Use regular F110 after creating a vendor invoice, and specifying "W" as allowable payment method in the vendor master record.
Trust this helps you to identify the exact problem and resolve it.
Remember to assign points if found useful.
Regards
Gulshan -
Class extends JComponent how to use custom methods?
I have a class Block which extends JPanel
code is hereprivate class Block extends JLabel{
boolean top;
Block(int a,Color c){
setSize(40 + a*10,20);
setBorder(BorderFactory.createMatteBorder(40+a*10,0,0,0,c));
void setTop(boolean b){
this.top = b;
boolean getTop(){
return top;
}I need to use getTop() method of certain block in class implementing MouseMotionListener
I used getComponent() method like this
e.getComponent().getTop()but it didn't work and gave
HanoiTowers.java:59: cannot find symbol
symbol : method getTop()
location: class java.awt.Component
if(e.getComponent().getTop()){}
error
Is there some other way to do this?Antti_ wrote:
I have a class Block which extends JPanelahem, I believe that it extends JLabel.
Is there some other way to do this?You could cast I suppose:
Component c = e.getComponent();
if (c instanceof Block)
System.out.println(((Block)c).getTop());
} -
Dual WAE's in mixed return methods?
Today we have a single 7341 attached directly to the router's Gi0/1. The original WAE uses Forwarded return. Lastweek we received a second 7341 (and 15 other WAE boxes for branch sites). Since we can not connect a second WAE directly to the router without adding a switch between them, we planned on eventually moving both 7341's to our internal LAN segment. Our new 7341 will be provisioned on the internal LAN and will use GRE Negotiated Return to the routers Loopback interface. Once the new 7341 is up and running we plan on moving our original 7341 to that same architecture.
Does this present an issue? Will the router have an issue with service group 61 and 62 having two WCCP clients, using different return mechanisms?
7341#1 = Forwarded Return (Directly connected to router, L2)
7341#2 = GRE Negotiated Return (On Internal LAN, Routed)Just to clarify, both of these 7341 boxes will be in the same WCCP service groups. (61 LAN & 62 WAN). The "Return method" is GRE for both.
"However please note that the packet return method should be the same."
7341#1
wccp router-list 8 10.X.X.1 (Gi0/1 on router)
wccp tcp-promiscuous service-pair 61 62 failure-detection 30
wccp tcp-promiscuous service-pair 61 62 router-list-num 8
wccp version 2
7341#2
wccp router-list 1 10.X.X.129 (Loopback1 on same router)
wccp tcp-promiscuous service-pair 61 62 failure-detection 30
wccp tcp-promiscuous service-pair 61 62 router-list-num 1
wccp version 2
egress-method negotiated-return intercept-method wccp -
Error when using findbykey method
hi am having this error when using below method cannot assign of type sms1405.common.agrROW TO variable of type oracle.jbo.row[]. type 'oracle.jbo.row[]' excepected but 'sms1405.common.agRROW' found the error is in this line agrRows = (AGRRow)agrRows[0]; the methos is
am using this sample
http://amulyamishras-tech-blog.blogspot.com/2011/01/viewobject-getrow-vs-findbykey.html
where does EmpVORow in EmpVORow empRow =
(EmpVORow)EmpVO.getRow(key); define from above sample
where does EmpVO from EmpVORow empRow =
(EmpVORow)EmpVO.getRow(key); define from above sample
am in Jdeveloper 11.1.2.1.0
Edited by: Tshifhiwa on 2012/07/03 4:36 PMMan, you should be able to find this out your self by now!
Hint: there is one 's' too much in the line you get the error (i guess cut & past error)
Try to understand the code you copied!
Timo
Maybe you are looking for
-
Office 2013 "Help" -- What Executables Does it Call?
The help function in Office 2013 applications running under 64-bit Windows 7 Professional SP1 is blocked by my Software Restriction Policy (e.g.,.http://www.mechbgon.com/srp/). Neither clicking "?" in the upper right of the application window nor pr
-
SM58 : Internal error when accessing a table
Hi there, We have just upgraded from R/3 4.7 to ECC 6.0. After the upgarde we face many "Internal error when accessing a table" in sm58. Is there any table mapping mismatched happened during unicode conversions? How to check the details? Most of the
-
Can't transfer music from iTunes to iPhone
Ok, so I transferred this CD to iTunes and I'm trying to drag and drop it onto my iPhone but I get a symbol showing that I can't do that. I then tried to check the box under iPhone that says "Manually manage music and videos" but then get a notificat
-
Photo Library taking too much space
my photo library is currently taking up 361 mb with 0 photos or videos in it. I wanted to be able to download some apps so im wondering how i can clear this space seeing that there is nothing that should be taking it up. I have a 8gb iphone 4s ios 8
-
How to hide the unit in the query?
Hi Gurus, I have three key figures, 1, Stock: Showed as 1000 TON 2, Value: Showed as 100000 USD 3, AVG: Showed as 100 USD/TON, the formula is Value / Stock In the query, the value will display the unit, TON and USD and USD/TON. How can I hide the uni