Help learning while/do while loops
Hi everyone, glad to see there are resources out here like this where newbies with Java can get help and learn from the gurues!
I am having a problem with constructing a while loop that is going to compute the sinx without using the Math.sin function....so given this
sinx = x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ......
It seems I need to use the Math.pow function. So the sinx is alternating signs between each new set of parenthesis and the power and factorial are increasing by 2..starting with 3. I think this is were I am having my trouble.
I was going to use a do-while loop for cosx which is
cosx = x - (x^2/2!) + (x^4/4!) - (x^6/6!) + ......
I think my problem is that I can't figure out how I would go about writing this. If I can get the sinx with the while loop, I can probably get the cos on a do-while statement since they are similar. I did get factorial(n) defined below.
I have another main class which I am using to get the input of sin/cos x using computeSin and computeCos functions I am trying to build here.
import javax.swing.*;
public class NewMath
public static double computeSin(double x)
double result = x;
// Going to use A WHILE LOOP
return result;
public static double computeCos(double x)
double result = 1;
// Going to use a DO-WHILE loop
return result;
private double factorial(int x) {
if (x <= 1) return 1.0;
else return x * factorial(x - 1);
Any tibits of help would be nice. If I think I got it working before someone else posts, I'll post my results. Thanks.
Any tibits of help would be nice. If I think I got
it working before someone else posts, I'll post my
results. Thanks.You already have your own tidbits, as you've observed the pattern of alternating adding/subtracting, as well as how the power and factorial factors relate. Any more "tidbits" here would just result in doing it for you, it seems. So get to it, and if you run into specific problems, you can ask.
Similar Messages
-
Hello let me first explain what im trying to achive:
I want a moving square that you control with the arrow keys on the keyboard. It has to be smooth ie able to move fast without looking like its jumping and it has to be able to move diagonaly aswell. Think of that arcade game Raiden ...you know the birds-eye view plane flying game...another thing! I'd prefer if it didnt use timers - i made one already using 4 timers and it works great but 4 timers is a little extreme - SO NO TIMERS !
I was thinking while loops, but i cant seem to get it working. I dont want to put in all the code so ill just say that I have 4 booleans: up, down, left right and the following code:
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
up = true;
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
down = true;
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
repaint();
For the KeyReleased part i have the same as above exept it sets the booleans to false.
Soooo in theory if i set up a while loop like this (using the up direction as an example) :
while (up == true) {
[move square up]
So therefore when i press and hold the up arrow the loop will keep going untill i realease it right? WRONG ! it just keeps repeating indefinatly and it doesnt even do the " [move square up] " bit. I put a System.out.print in the loop to test and it kept printing out the message but it still didnt do the actual " [move square up] " bit.
Im not sure if im putting the while loop in the right place either....If anyone has any idea on how to use while loops in this way please heeeelp ! Its so annoying because it just doesnt work ive tried so many ways...
any help would be greatly apreciated !!!!Maybe you want something like this? You have to pause during the loop to allow for other events to happen, like if y ou release a key or whatever.
while( true )
if( up ) moveUp();
else if( down ) moveDown();
if( left ) moveLeft();
else if( right ) moveRight();
try
Thread.currentThread().sleep(10);
catch( InterruptedException e )
System.out.println( "Thread interrupted!");
} -
I am working on this program that when inputing two integers: firstNum and secondNum, the program will output all odd numbers between firstNum and secondNum.
This program will be using a while loop and I can't find any similar examples in my book on how to write the code.
any help would be greatly appreciatedyou asked for it...
//This program will prompt the user to input two integers.
//Output all odd numbers between firstnum and secondnum.
//Output the sum of all even numbers between firstnum and secondnum.
//Ouput the numbers and their square between 1 and 10.
//Output the sum of the square of odd numbers between firstnum and secondnum.
//Output all uppercase letters.
import java.io.*;
public class Program8
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException
//Declare all variables
int firstNum;
int secondNum;
System.out.print("Input first Integer: ");
firstNum = Integer.parseInt(keyboard.readLine());
System.out.println();
System.out.print("Input second Integer: ");
secondNum = Integer.parseInt(keyboard.readLine());
System.out.println();
As you can see, I don't have a clue where to begin after this... -
Need help with while loop and shift registers
I have a large data set and need to read in the data at maybe 200 samples at a time, process these samples through my VI, and have it append and concatenate a separate lvm file. The part where I am confused is the shift registers. How do I limit the number of samples read in an iteration? How do I get the while loop to stop when all the data are read in?
I've attached my diagram, maybe there is something wrong with my technique?
Solved!
Go to Solution.
Attachments:
shiftreg.JPG 56 KBThis will give you an idea. There are plenty of other (probably more efficient) methods. This is a basic, quick and dirty solution to help you grasp the overall concept.
Using LabVIEW: 7.1.1, 8.5.1 & 2013
Attachments:
ShiftRegLoop.JPG 54 KB -
Im trying to create a while loop that outputs the revers of a string, eg nice one
would be "eno ecin" Assuming i already have declared a variable intital string that holds the string, how do i go about this does anyone have any problem solving techniques. The charAt method needs to be used.i have a exam on saturday and it was a previous exam question that im trying to get help with i need to understand the course material thanks, i know how to use while loops but have trouble getting my head around this question. ill show you my code however i know its completely wrong.
now i know i hvae to use the charAt method to return a character located at the integer i
so i must go down after each case has been tested true therefore i want i=i-1;
until i=0;
String initialString="tucan";
int i=initialString.length();
while(i>0)
return charAt();
i=i-1;
} -
Sorry for the "Noob"-ness on this one. I am working on a program for class and I am having a problem with a while loop. So I opened a new document and began to code a while loop that is basic to test my while looping skill. Apparrently, I have none. Can anyone tell me why this While Loop will not work:
public class test
public static void main(String[] args)
int LoanTerm = 0;
while (LoanTerm < 3);
System.out.println (LoanTerm);
LoanTerm++;
Thanks.
FatherVicto explain, the ; means that the while loop body is empty, and you will just spin forever testing whether LoanTerm < 3, without doing anything else.
-
Hi,
I'm running a while loop to run through some results of a search. Anyway I know how to list the strings but my last item is a JComboBox (drop down box.) How do I go about changing that so its right for a drop down box. Its the one with questions marks in the code below.
while (srs.next())
//Get the values for each field in this row
String projectName = srs.getString("PROJECT_NAME");
System.out.println("Project Name = " + projectName );
String projectOfficier = srs.getString("PROJECT_OFFICER");
System.out.println("Project Officer = " + projectOfficier );
String projectDescription = srs.getString("PROJECT_OFFICER");
System.out.println("Project Description = " + projectDescription );
String paymentSchedule = srs.getString("PAYMENT_SCHEDULE");
System.out.println("Payment Schedule = " + paymentSchedule );
String banksInvestment = srs.getString("BANKS_INVESTMENT");
System.out.println("Banks Investment = " + banksInvestment );
? String paymentsMade = srs.getString("PAYMENTS_MADE");
? System.out.println("Payments Made = " + paymentsMade );Thanks.Yeah the Payments Made part is a JComboBox with 3 so called strings inside it. I wanna know instead of srs.getString what should I put in to replace String to get the results from a JComboBox?
-
Im trying to finish this loop for a guessing game, does anyone have any suggestions, thanks.
class guess
{public static void main ( String[] args )
int secretNumber = 4;
InputStreamReader inStream =
new InputStreamReader( System.in ) ;
BufferedReader stdin =
new BufferedReader( inStream );
String userGuess;
int guess;
System.out.println("Enter your guess:");
userGuess = stdin.readLine();
guess = Integer.parseInt( userGuess );
System.out.println("You entered:" + guess );
if ( guess = secretNumber )
System.out.println ("Guess is correct!")
else
System.out.println ("Guess is incorrect")
while ( (guess == secretNumber) = false ) //evaluates true or false
}Hie.
Your logic is not good here.
You should do this :
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Random;
public class Guess {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int secret = new Random().nextInt(10);
boolean guessed = false;
System.out.println("Guess the number (0 to 9, inclusive) :");
while (!guessed) {
System.out.print("Your guess : ");
System.out.flush();
int guess = -1;
while (-1 == guess) {
try {
guess = Integer.parseInt(in.readLine().trim());
if (0 > guess || guess > 9) {
System.out.println("You should type an integer between 0 and 9 inclusive.");
guess = -1;
} catch (NumberFormatException nfe) {
System.out.println("Type an INTEGER !");
guess = -1;
} catch (Throwable t) {
t.printStackTrace();
guess = -1;
guessed = guess == secret;
if (!guessed && -1 != guess) {
System.out.println("Wrong ! Try again.");
System.out.println("Right ! bye.");
}Tell me if you need explanations. -
Need help with while loop format
I'm building a form - everything works but I would like to change the way the data is output into the table.
In other scripting languages, like PHP, you had 2 different ways of dealing with a loop:
<?
do while xyz
do something here
?>
- OR -
<? do while xyz:?>
do something here
<?end while ?>
I would like to do something similar to the 2nd example in .jsp but I'm not sure of the format or how to stop the loop. From the tutorial, I'm using
<%
while(SQLResult.next())
UId = SQLResult.getString("uid");
FName = SQLResult.getString("fname");
LName = SQLResult.getString("lname");
out.println("<tr><td>" + UId + "</td><td>" + FName + "</td><td>" + LName
+ "</td></tr>");
%>
Could anyone point me in the right direction? I'd prefer it if I didn't have to build the table like this if I don't have to but haven't found anything anywhere telling me otherwise.
Thanks so much.
BobSorry - the answer was in JSP:Java Server Pages by Barry Burd. I had just gotten the output format wrong.
-
Need help w/ for loop, a do loop, and a do-while loop.
Hello I have been trying to write a program that uses a for, do, and a do-while loop, but I am having trouble. I need the program that will prompt the user to enter two numbers. The first number must be less than the second number. I need to use a "for loop", a "do loop", and a "do-while loop" to display the odd numbers between the first number and the second number. For example, if the user entered 1 and 8, the program would display 3,5,7 three different times (one for each of the loops). Please help if you can. Thanks.
boolean2009 wrote:
Thank all of you all for responding.Youre welcome.
Yes this is my homework, but my major does not even involve java i just have to take the class.Not our problem.
And yes we are suppose to have all three in one program I do not know why,So you can learn all three types of loops (there is also an enhanced for loop to learn later on).
but I just do not understand programming nor do i really want to.Once again not our problem.
If anybody could help it would be much appreciated. thanks.Yes, a lot of people are willing to help you. No, none of them will do it for you. What you need to do is attempt the code and when you get stuck, post your code using the code button, include error messages, indicate which lines in your code genereate those error messages and ask specific questions. -
Problem with while loops, please help!
I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
for(...)
read in files...
//Go through each line of the first file
while(matchLine1.find()) {
CharSequence line1 = matchLine1.group();
//Get the words in the line
String words1[] = wordBreak.split(line1);
for (int i1 = 0, n = words1.length; i1 < n; i1++) {
if(words1[i1].length() > 0) {
int count= 0;
count++;
list1.add(words1[i1]);
}This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!Don't try to construct complicated nested loops, it makes things a
tangled mess. You want a collection of words per file. You have at least
zero files. Given a file (or its name), you want to add a word to a collection
associated with that file, right?
A Map is perfect for this, i.e. the file's name can be the key and the
associated value can be the collection of words. A separate simple class
can be a 'MapManager' (ahem) that controls the access to this master
map. This MapManager doesn't know anything about what type of
collection is supposed to store all those words. Maybe you want to
store just the unique words, maybe you want to store them all, including
the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
i.e. a simple thing that is able to deliver a new collection to be associated
with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
Collection getCollection();
}Because I'm feeling lazy today, I won't design an interface for a MapManager,
so I simply make it a class; here it is:public class MapManager {
private Map map= new HashMap(); // file/words association
CollectionBuilder cb; // delivers Collections per file
// constructor
public MapManager(CollectionBuilder cb) { this.cb= cb; }
// add a word 'word' given a filename 'name'
public boolean addWord(String name, String word) {
Collection c= map.get(name);
if (c == null) { // nothing found for this file
c= cb.getCollection(); // get a new collection
map.put(name, c); // and associate it with the filename
return c.add(word); // return whatever the collection returns
// get the collection associated with a filename
public Collection getCollection(String name) { return map.get(name); }
}... now simply keep adding words from a file to this MapManager and
retrieve the collections afterwards.
kind regards,
Jos -
Hi...I am somewhat new to Java and I am trying to do a nested while loop. Basically I have a result set from a query and I want to loop though that result set BUT I need a second loop to put together 150 of the results at a time and add them to a GeoCodeRequest to send to MapInfo.....this is how I think the code should look, I need some advice if it is the proper way to loop through....
ArrayList aal = new ArrayList();
ServiceMessage sm = new ServiceMessage();
ServiceMessage rsm = new ServiceMessage();
while (rset.next())
statRecord = statRecord + currentRecord;
while (rset.next() && currentRecord <= 150)
AddressEx a = new AddressEx(rset.getString(6));
ContentColumn cc = new ContentColumn("mmhid");
cc.setValue(rset.getString(1));
StreetAddress streetAddress = new StreetAddress(rset.getString(3));
streetAddress.setBuildingName(rset.getString(2));
a.setCountrySubdivision(rset.getString(5));
a.setMunicipality(rset.getString(4));
a.setPostalCode(rset.getString(6));
a.setContentColumn(0,cc);
aal.add(a);
currentRecord++;
System.out.println("Inside inner while loop now..");
System.out.println("Add 150 to request...");
GeocodeRequestEx gr = new GeocodeRequestEx("","3.0","id",(AddressEx[])aal.toArray());
gr.setGeocodePreference(pref);
sm.addRequest(gr);
System.out.println("going to geocode now...");
try{
LocationUtilityServiceLocator lus = new LocationUtilityServiceLocator();
LocationUtility lu = lus.getLocationUtility(new URL(url));
XLSType xr = lu.perform(sm.toXLS());
rsm = new ServiceMessage(xr);......
code goes on to do oter things but this is the basis..............
I hope that all made since.....please help.I am not sure if there is a problem, that is what I am
asking......if I have the logic correct.
I haven't been able to test it correct because I am
getting an:
Exception in thread "main"
java.lang.ClassCastException: [Ljava.lang.Object; at
geoClient.main(geoClient.java:127)
That means you don't have it correct. :-)> on the following line:> > GeocodeRequestEx gr = new> GeocodeRequestEx("","3.0","id",(AddressEx[)aal.toArray
and I haven't figured out to correct that yet......You need to use toArray(Object[]). -
Help with a while loop condition
I'm trying to write to a File. I ask the user for input, then I enter a while loop and test the condition. The loop works, but it won't stop. I've tried everything. Here is my code please help!!
thanks
inputline = keyboard.readLine();//read the keyboard
try{
while( inputline != null ){
DiskOut.println( inputline );
DiskOut.flush();
inputline = keyboard.readLine();//read the keyboard again
}//end while
}//end try
catch (IOException e) {
e.printStackTrace();
}//end catch
also i've tried these while loop conditions:
while(inputline != "\n" || inputline != "\r") and the sortwhile(inputline != "\n" || inputline != "\r")The condition
X!=Y OR X!=Z (given Y != Z)
is always true. X will always not be equal to at least one of the values. So you'll want to use:
while(!inputline.equals("\n") && !inputline.equals("\r"))In other words, "while inputline is not equal to either of them". Note the use of && instead of ||.
If "keyboard" is simply a BufferedReader on top of System.in (and not your own class), the trailing line feeds and carriage returns won't even be in the string returned by readLine(). Your best bet is this:
while(null != inputline && 0 != inputline.length())Make sure you type the two parts of that AND condition in the order above. If for whatever reason there are trailing \r and \n on the strings, you'll want to accomodate for platforms that may include both characters.
// trim the trailing newline characters
while(inputline.endsWith("\r") ||
inputline.endsWith("\n")) {
inputline = inputline.substring(0,inputline.length()-1);
// or maybe this will work if you don't mind losing
// the whitespace at the beginning of the string:
inputline = inputline.trim();Hope that helps somewhat. -
Help needed with while loops please :)
I'm beginning to study java at School.
My assignment using while loops, to ask user to input 2 numbers.
I have to output all odd number between the two.
I have to output the sum of all even numbers between the two.
Output all the numbers and their squares between 1-10.
Output the squares of the odd numbers between the 2 numbers the user entered.
Output all uppercase letters.
If anyone can give me any help, I would appreciate it greatly.
Thank you.
Kelly.It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
get input from user
set counter to first number entered
while counter less than/ equal to second number
check if number is even
if even, add to even_sum
else output counter, along with its square
increment counter by one
end while
output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
Good Luck -
FUNCTION Cursor / WHILE LOOP vs LOOP / Logic help (RESOLVED)
(I HAVE RESOLVED - making it more efficient, I hope - see FUNCTION) if anyone has a different =, more efficient way to write this, please share...
I need help with a Function:
I am trying to get a handle on a rate. This table has and employee column this is usually populated with 'ALL'. On the off chance that it has an actual employee number, I want that rate; otherwise, the rate with ALL. Everything in both records will be the same except the employee field. (if there happens to be an ALL rate and an individual employee rate. Usually there will only be one record).
As I started to write this, I tested the WHILE loop logic and did not get a value back, but when I test a simple loop, I do. I have not finished the entire logic only getting a handle on a record that has the employee.
I would like help:
Understanding why WHILE loop isn't working
How to go about testing if CURSOR c_job_payroll_rate_emp FOUND - get this value and EXIT otherwise IF NOT FOUND then get value from c_job_payroll_rate_all
Start to my function is below w/ testing comments(** THIS IS THE RESOLVED FUNCTION.
FUNCTION job_pay_rate(in_comp_code IN jobpayrate.jpr_comp_code%TYPE,
in_job_code IN jobpayrate.jpr_job_code%TYPE,
in_phs_code IN jobpayrate.jpr_phs_code%TYPE,
in_cat_code IN jobpayrate.jpr_cat_code%TYPE,
in_trd_code IN jobpayrate.jpr_trd_code%TYPE,
in_emp_code IN jobpayrate.jpr_emp_no%TYPE)
RETURN jobpayrate.jpr_billing_rate%TYPE
IS
v_val jobpayrate.jpr_billing_rate%TYPE;
CURSOR c_job_payroll_rate_all IS
SELECT max(jpr_billing_rate) rate
FROM jobpayrate
WHERE jpr_comp_code = in_comp_code
AND jpr_job_code = in_job_code
AND jpr_trd_code = in_trd_code
AND jpr_phs_code = in_phs_code
AND jpr_cat_code = in_cat_code
AND jpr_emp_no <> in_emp_code;
CURSOR c_job_payroll_rate_emp IS
SELECT max(jpr_billing_rate) rate
FROM jobpayrate
WHERE jpr_comp_code = in_comp_code
AND jpr_job_code = in_job_code
AND jpr_trd_code = in_trd_code
AND jpr_phs_code = in_phs_code
AND jpr_cat_code = in_cat_code
AND jpr_emp_no = in_emp_code;
BEGIN
FOR rec_e IN c_job_payroll_rate_emp LOOP
v_val := rec_e.rate;
IF rec_e.rate IS NULL THEN
FOR rec_a IN c_job_payroll_rate_all LOOP
v_val := rec_a.rate;
END LOOP;
END IF;
END LOOP;
RETURN v_val;
END job_pay_rate;
Message was edited by:
KBRather than using cursors for zero or 1 row queries, use SELECT ... INTO
Untested
FUNCTION job_pay_rate(in_comp_code IN jobpayrate.jpr_comp_code%TYPE,
in_job_code IN jobpayrate.jpr_job_code%TYPE,
in_phs_code IN jobpayrate.jpr_phs_code%TYPE,
in_cat_code IN jobpayrate.jpr_cat_code%TYPE,
in_trd_code IN jobpayrate.jpr_trd_code%TYPE,
in_emp_code IN jobpayrate.jpr_emp_no%TYPE)
RETURN jobpayrate.jpr_billing_rate%TYPE
IS
v_val jobpayrate.jpr_billing_rate%TYPE;
BEGIN
SELECT max(jpr_billing_rate) rate INTO v_val
FROM jobpayrate
WHERE jpr_comp_code = in_comp_code
AND jpr_job_code = in_job_code
AND jpr_trd_code = in_trd_code
AND jpr_phs_code = in_phs_code
AND jpr_cat_code = in_cat_code
AND jpr_emp_no = in_emp_code;
RETURN v_val;
EXCEPTION
WHEN NO_DATA_FOUND THEN
SELECT max(jpr_billing_rate) rate INTO v_val
FROM jobpayrate
WHERE jpr_comp_code = in_comp_code
AND jpr_job_code = in_job_code
AND jpr_trd_code = in_trd_code
AND jpr_phs_code = in_phs_code
AND jpr_cat_code = in_cat_code
AND jpr_emp_no <> in_emp_code;
RETURN v_val;
--OTHER EXCEPTION HANDLING
END;
Maybe you are looking for
-
MSI-8833 (GF2 MX400) Probs with the CAPTURE driver
When I run LIve update, it shows me the BIOS and driver for the graphics card. But when I'm installing the CAPTURE driver from MSI web page, Live update doesn't rekognize my MSI 8833 graphics card as an MSI or Live updateable graphics card any more?
-
How to create a loopback adapter
How to create a loopback adapter
-
Question on Shared Photo Stream Limits
I was creating a bunch of new Shared Photo Streams on my iPhone and got a message that it "Cannot Create Photo Stream: You can only have 50 shared photo streams. Delete an existing one and try again." In checking the webpage that discusses the Photo
-
Increase SGA more than 3GB in Windows Server 2003 Ent. R2
Dear Sir; I have 2 servers with Windows server 2003 Enterprise R2, both servers are 32 Bit, but windows can manage our 16GB installed on this server. Our database is 10.2.0.3 (32 Bit) With RAC. My issue is to increase Instances SGA to 7 or 8 GB. I fa
-
HELP! Why can't I print PDFs from my applications?
For over a year I've used Adobe Pro to "print" PDFs from AutoCAD LT (a drafting program). This allows me to perform design/drafting services for long distance clients and email them PDF "prints" of drawings for them to review, print, and use. It has