For loops & inheritance question
I am trying this exercise dealing w/inheritance. I enter at command line a random number of c's, s's and m's. for checking,savings and money market. I then parse the string and check for the character. From there I create one of the accounts. then I am supposed to make a report that displays the past 3 months activities. the first account created gets 500 deposit the from there each account after the first gets an additional 400. so it would be: 500,900,1300,etc. Here is what I have so far, but the report part is where I can't figure out exactly how to go about solving it. Thanks in advance.
public static void main( String args[] ){
int intDeposit = 500;
char charTest;
Object [] objArray = new Object[args[0].length()];
for ( int j = 0; j < 3; j ++ ){ System.out.println( "Month " + ( j +1 ) + ":" );
for( int i = 0; i < args[ 0 ].length(); i ++ ){
charTest = args[ 0 ].charAt( i );
if (charTest == 'c' ){
BankAccount at = new CheckingAccount( intDeposit );
objArray=at;
else if( charTest == 's' ){
BankAccount at = new SavingsAccount( intDeposit );
objArray[i]=at;
else if( charTest == 'm' ){
BankAccount at = new MoneyMarket( intDeposit );
objArray[i]=at;
else{
System.out.println( "invalid input" );
}//else
intDeposit += 400;
System.out.println();
}//for j
for (int counter = 0; counter < objArray.length; counter ++ ){
System.out.println( "Account Type: " +
objArray[counter].toString() );
System.out.println( "Initial Balance: " +
(BankAccount) objArray[counter].getCurrentBalance() );
System.out.println( "TotalDeposits: " + objArray[counter].getTotalDeposits() );
System.out.println();
}//for i
}//main
}//TestBankAccount.java\
The only thing I think is wrong is the following line:
System.out.println( "Initial Balance: " + (BankAccount) objArray[counter].getCurrentBalance() );
Should be:
System.out.println( "Initial Balance: " + ((BankAccount) objArray[counter]).getCurrentBalance() );
Similar Messages
-
For-Loops: The question no one asks.
Why don't For-Loops have a premature exit capability --- i.e. why didn't
NI include the exit capability that exists in other languages? Is it a dataflow
thing? I don't see how. Just curious.Jay,
I have to say I`m no programming Guru, but isn`t a State Maschine based on a
case (Switch) statement? This statement does allow the user to hop to and
fro within a certian pre-defined space, but the use of a GOTO is, as far as
I am aware, not limited to a particular region of the code. At least with a
switch statement (Case) the beginning point of each "choice" is well defined
and fixed, therefore reducing the change of mistakes.
just my 2 cents
Shane
Jay schrieb in Nachricht <[email protected]>...
>
>Hey, Tim. You say:
>
>>I believe that the loop exit capability wasn't included because it was
considered
>bad programming practice, like using goto's.
>
> That's funny. How can it be any worse (or different) than putt
ing exit
>logic into a While-Loop? As for Goto's, they're the basic logic behind the
>much revered State Machine, and no one seems to mind that. If you're not
>careful, State Machines can wind up producing some pretty good spaghetti
>code, just like any text-based code can do.
>
>Jay
>
>>> Original message: Why don't For-Loops have a premature exit capability
>--- i.e. why didn't NI include the exit capability that exists in other
languages?
> Is it a dataflow thing? I don't see how. Just curious.
Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2) -
Arrays dimension changed by "for loop"
When using a two(multi)-dimension array as input to a "for loop", the connection
changes inside the loop to a 1D array automatically. Why?!?
I want to perform the same procedure on each subarray of the basic two-dimension
array, by specifing an index. The second dimension I disable indexing. The
index itself can be the for loop index. The problem is the change in connection
between out and in of the for loop.The question is that you have indexing enabled in the for
loop entry, and the for loop will convert your 2D array in
the necessary number of 1D arrays to be completed in the
for loop. This is good when you don't know how long the
array is going to be, but if you don't like it, you can
right click on the input tunnel and disable indexing.
Hope this helps.
* Sent from AltaVista http://www.altavista.com Where you can also find related Web Pages, Images, Audios, Videos, News, and Shopping. Smart is Beautiful -
For Loop and Void Method Questions
Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted.
Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)?
Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now.
for (int index = 0; index < howNum; index++) // process each number in the array
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
numArray = new double[howNum];
try
numArray[index] = Double.parseDouble(enterYourNumbers);
catch (NumberFormatException e)
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
DecimalFormat fmt = new DecimalFormat ("###,###.00");
JOptionPane.showMessageDialog(null, enterYourNumbers + " " + "squared is " + fmt.format(calcSquare(numArray[index]))
+ "\n" + enterYourNumbers + " " + "cubed is " + fmt.format(calcCube(numArray[index])));
wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
while (wantToContinue.equalsIgnoreCase("y"));
import javax.swing.*;
import java.text.DecimalFormat;
public class Array
public static void main(String[] args)
int howNum = 0;
int whichNum = 0;
double[] numArray;
boolean invalidInput = true;
String howManyNumbers, enterYourNumbers, wantToContinue;
do // repeat program while "y"
do // repeat if invalid input
howManyNumbers = JOptionPane.showInputDialog
("How many numbers do you want to enter");
try
howNum = Integer.parseInt(howManyNumbers);
invalidInput = false;
catch (NumberFormatException e )
howManyNumbers = JOptionPane.showInputDialog
("How many numbers do you want to enter");
while (invalidInput);
for (int index = 0; index < howNum; index++) // process each number in the array
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
numArray = new double[howNum];
try
numArray[index] = Double.parseDouble(enterYourNumbers);
catch (NumberFormatException e)
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
DecimalFormat fmt = new DecimalFormat ("###,###.00");
JOptionPane.showMessageDialog(null, enterYourNumbers + " " + "squared is " + fmt.format(calcSquare(numArray[index]))
+ "\n" + enterYourNumbers + " " + "cubed is " + fmt.format(calcCube(numArray[index])));
wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
while (wantToContinue.equalsIgnoreCase("y"));
public static double calcSquare(double yourNumberSquared)
return yourNumberSquared * yourNumberSquared;
public static double calcCube(double yourNumberCubed)
return yourNumberCubed * yourNumberCubed * yourNumberCubed;
public static void calcAverage(double yourNumberAverage)
}DeafBox wrote:
Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted. Use a while loop instead.
Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)? Why would you want to use 2 methods. Use the loop to sum the numbers. Then after the loop a single line of code calculates the average.
Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now. If I understand you correctly, use 2 loops. One gathers user inputs and stores them in an array/List. The second loop iterates over the array/List and does calculations. -
Hi,
I have a cursor in my plsql and I am trying to get the record through a FOR loop. I know that for loop will take care of opening, fetching and closing the cursor implicitly.
Ex.
declare
cursor c1 is
select * from emp;
begin
for l_rec in c1 loop
end loop;
My question is i want to check whether the cursor in the for loop is returning any record or not using IF condition.
where and how i will find that?
Can anyone help how to do that.
Rds,
Nagwithout using boolean variables.Obvious question, WHY?
If you are so particular..
SQL> declare
2 cursor c1 is
3 select empno, ename, job
4 from emp
5 where empno = 7839123;
6 ex exception;
7 rec c1%rowtype;
8 begin
9 open c1;
10 fetch c1 into rec;
11 if c1%notfound then
12 raise ex;
13 end if;
14 loop
15 dbms_output.put_line(rec.empno||'-->'||rec.ename||'-->'||rec.job);
16 fetch c1 into rec;
17 exit when c1%notfound;
18 end loop;
19 exception
20 when ex then
21 dbms_output.put_line('cur not found');
22 end;
23 /
cur not found
PL/SQL procedure successfully completed. -
VERY IMPORTANT FOR LOOP QUESTION
public class ForTest2 {
public static void main(String args[]) {
int i=0, j = 0;
for (j=0; j < 10; j++) {
i++;
System.out.println("i is: " + i);
System.out.println("j is: " + j);
System.out.println("Final i is: " + i);
System.out.println("Final j is: " + j);
}j ends up being 10. Why? It should only be 9. This is as when j is 10 the for loop fails, so j++ shouldnt happen.First, please, please, please stop using all caps. It's extremely annoying.
Second, don't mark your question as urgent or important. It is 100
% guaranteed NOT to get you help any faster, and it might just delay you getting help because it's annoying.
As for your question, you're misunderstanding how the for loop works. j HAS to become 10 for it to end. The loop body executes as long as j < 10. If j didn't become 10, the loop body couldn't terminate, because j<10 would always be true.
The body is executed, the j++ is executed, then the j<10 is tested.
int j;
for (j = 0; j < 10; j++) {
// body
// is equivalent to
int j;
j = 0;
while (j < 10) {
// body
j++:
} -
Hi
Lets say I have an array with boolean values in it:
my_array = [ false , false , false ]
My question is:
How do you make a function to check, if the value is all
false, than do this (not only one but all false than trigger a
function)
thank youThe 350Z,
> Lets say I have an array with boolean values in it:
> my_array = [ false , false , false ]
I'm with ya.
> My question is:
> How do you make a function to check, if the value is
> all false, than do this (not only one but all false than
> trigger a function)
Your subject line already states the answer. A for loop
would come in
handy. :) In your case, you're looking for all three values
to be false.
If even a mere one of them is true, the whole result doesn't
count. Let's
write a function that returns true if all three are false,
and returns false
if any are true.
function checkWholeArray(arr:Array):Boolean {
for (var n:Number = 0; n < arr.length; n++) {
if (arr[n] == true) {
return false;
return true;
To use this function, you could call it and supply your
array as the
parameter ...
checkWholeArray(my_array);
... and since that resolves to either true or false, you
could even use that
expression in an if statement.
if (checkWholeArray(my_array)) {
// do something
} else {
// do something else
The for loop simply steps through each element in the
passed-in array.
If the current element is true, then the desired outcome --
that all
elements are false -- is a loss, so the function returns
false and
immediately stops (the return statement always exits the
function at that
point). Otherwise, the for loop finishes, and the function
returns true.
David
stiller (at) quip (dot) net
Dev essays:
http://www.quip.net/blog/
"Luck is the residue of good design." -
Nested FOR cursor LOOPs, BASIC QUESTION
Hello,
I am trying to nest a For-loop using a cursor (see below), but the program is not entering the second (nested) for-loop. This program compiles fine, but during run-time, the nested loop does not execute. I'd rather not use FETCH statements and keep everything in place. I think the solution is rather trivial, but I'm new to PL/SQL. PLEASE HELP!!!!!
cursor c1 is
select coi_con_uid,coi_not_code,coi_closed_yn,coi_timestamp
from s_coi_con_issue
where coi_not_code = 'NOT107'
and coi_timestamp <= v_aweekago
and coi_closed_yn = 'N';
cursor c2 is
select tsk_uid
from s_tsk_task
where tsk_status in ('C')
and tsk_tty_code = 'CONTAC'
and tsk_date_end = '' FOR UPDATE;
BEGIN
select to_date(sysdate - 7) into v_aweekago from dual;
DBMS_OUTPUT.PUT_LINE('System date used is ' || v_aweekago);
FOR coi_row in c1 LOOP
v_tsk_cnt := 0;
v_coi_row_cnt := v_coi_row_cnt + 1;
v_con_uid := rtrim(to_char(coi_row.coi_con_uid));
v_tsk_act_str := ('"CON_UID","' || v_con_uid || '"') ;
DBMS_OUTPUT.PUT_LINE('COI_CON_UID: ' || v_con_uid);
DBMS_OUTPUT.PUT_LINE('v_tsk_act_str: ' || v_tsk_act_str);
-----The Program is not entering into this Loop
FOR tsk_row in c2 LOOP
v_update_cnt := v_update_cnt + 1;
update s_tsk_task
set tsk_status = 'A'
where tsk_uid = tsk_row.tsk_uid and
tsk_action_string = v_tsk_act_str;
DBMS_OUTPUT.PUT_LINE('----Task updated');
END LOOP;
END LOOP;
COMMIT;using your query on your cursor c2 when you execute it on sql*plus did it return any rows?
select tsk_uid
from s_tsk_task
where tsk_status in ('C')
and tsk_tty_code = 'CONTAC'
and tsk_date_end = ''; if not it might have something to do with the predicates in your where clause
and tsk_date_end = '';consider revising your c2 cursor select statement to something like:
cursor c2 is
select tsk_uid
from s_tsk_task
where tsk_status = 'C'
and tsk_tty_code = 'CONTAC'
and tsk_date_end IS NULL
FOR UPDATE; -
Insert Procedure For LOOP question
Hi all,
I have made a Procedure which basically massages data and loads into into another table and makes a time record aswell. I am practising my good datawarehousing practise (So load table into real DW_table)
I am using an Explicit Cursor For Loop....
What i was wondering is if there is some type of SQL%rowcount I can do in order to check that the record where "INSERTED" into dw_client and dw_time; before i create a auit record in another table. I know this is normally done using triggers, but I am testing this for a Datawarehouse and not sure triggers are the best answer. But please correct me if im wrong:
I basically wanted to put another insert in there, if the inserts actually ran!RPuttagunta wrote:
Why can you not use a merge statement in your code instead of writing a whole procedure for it?
merge into mehmet_schema.dw_client a
using
mehmet_schema.client.....
If I understand it right, you are checking if there are any records that exists in 'client' and doesn't exist in 'dw_client' table, then, you are inserting. Is that correct?Yes that is correct. Also I am inserting into the dw_time table using the sqeuence values, so i didnt think merge statement would do this!
aslo i wanted to use this procedure to clean up some of the data, as you can see in my Cursor, again why i havent used a merge
Edited by: oraCraft on 09-Nov-2010 09:53 -
Hi here is a segment of my code:
public void vietaLoop(){
int loopParameter;
final int START_CONDITION=0;
final long END_CONDITION=no_Terms;
double initialTerm = Math.sqrt(2)/2;
double newTerm;
double previousTerm;
/* calculate the next PI term */
newTerm = Math.sqrt(2+previousTerm);
/* assign new term to previous */
previousTerm = newTerm;
for (loopParameter = START_CONDITION; loopParameter < END_CONDITION;
loopParameter++)
/* Prints the new PI approximation */
System.out.println(+ newTerm);
im having loads of trouble, above is how far I have got but I'm unable to 'call' the previous calculation to be included in the next calculation to calculate the new term of PI. as a result all my output is the same..... ie = 1.645.......
If anyone could point me in the right direct... its really getting to me. Thanks.Hi there,
Is this what you want?
import java.awt.*;
class vietaLoop
public static void main(String[] args)
int loopParameter;
int no_Terms=10;
int START_CONDITION=0;
int END_CONDITION=no_Terms;
double initialTerm=Math.sqrt(2)/2;
double newTerm;
double previousTerm;
previousTerm=initialTerm;
for (loopParameter=0; loopParameter<END_CONDITION;loopParameter++)
newTerm = Math.sqrt(2+previousTerm);
previousTerm = newTerm;
System.out.println(newTerm);
}If you use it as a function, set it as
public double vietaLoop(int noTerm)
Then you can change no of term for looping.
Regards
John -
Question to modify a for loop to put a counter and parametrize it
I have a FOR loop which is part of a PROCEDURE, the loop currently commits records for a large group of network providers. I need to modify it put a counter and commit for every 100 rows and make the number of rows of 100 parametrized. Any idea how this can be accomplished?
FOR cur_netrec IN cur_network_mc (curproc.mpicontractid)
LOOP
v_effectivedate := NULL;
v_terminationdate := NULL;
v_delegated := 'N';
v_individual := 'N';
v_credential := NULL;
FOR cur_conrec
IN cur_cont (cur_netrec.providerid, cur_netrec.mpinetworkcode)
LOOP
IF cur_conrec.effdate IS NOT NULL
THEN
v_effectivedate :=
LEAST (cur_conrec.effdate,
NVL (v_effectivedate, '31-DEC-9999'));
END IF;
END LOOP;
IF cur_netrec.mpinetworkproviderid IS NULL
THEN
INSERT INTO mpi_provider.mpinetworkprovider (
mpinetworkproviderid,
providerid,
mpinetworkcode,
providernetworkcode,
effectivedate,
terminationdate,
credentialingtypecode,
createdby,
creationdate,
modifiedby,
modificationdate
VALUES (
seq_mpinetworkprovider.NEXTVAL,
cur_netrec.providerid,
cur_netrec.mpinetworkcode,
(SELECT otherid
FROM mpi_provider.mpiprovider
WHERE providerid = cur_netrec.providerid),
NVL (cur_netrec.effectivedateoverride,
v_effectivedate),
NVL (cur_netrec.terminationdateoverride,
v_terminationdate),
v_credential,
USER,
TRUNC (SYSDATE),
USER,
TRUNC (SYSDATE)
ELSE
UPDATE mpinetworkprovider
SET effectivedate =
NVL (cur_netrec.effectivedateoverride,
v_effectivedate),
terminationdate =
NVL (cur_netrec.terminationdateoverride,
v_terminationdate),
credentialingtypecode = v_credential,
modificationdate = TRUNC (SYSDATE),
modifiedby = USER
WHERE providerid = cur_netrec.providerid
AND mpinetworkcode = cur_netrec.mpinetworkcode;
END IF;
--update when contract credential type code change
UPDATE mpi_provider.person prs
SET prs.credentialingtypecode =
(SELECT DECODE (MIN (credtype),
1, 'DELEGNCQA',
2, 'DELEGNETEX',
3, 'DELEGATED',
4, 'NONDELEG',
5, 'INDIVIDUAL',
6, 'NONDENETEX',
'NONE')
AS personcredentialingtypecode
FROM (SELECT DECODE (
c.credentialingtypecode,
'DELEGNCQA',
1,
'DELEGNETEX',
2,
'DELEGATED',
3,
'NONDELEG',
4,
'INDIVIDUAL',
5,
'NONDENETEX',
6,
7
AS credtype
FROM mpi_provider.mpicontractprovider cp,
mpi_provider.mpicontract c
WHERE c.mpicontractid =
cp.mpicontractid
AND cp.providerid =
cur_netrec.providerid
AND cp.terminationdate >
SYSDATE))
WHERE prs.providerid = cur_netrec.providerid;
COMMIT;
END LOOP;This piece could be accomplished with a MERGE, too
IF cur_netrec.mpinetworkproviderid IS NULL
THEN
INSERT INTO mpi_provider.mpinetworkprovider (
mpinetworkproviderid,
providerid,
mpinetworkcode,
providernetworkcode,
effectivedate,
terminationdate,
credentialingtypecode,
createdby,
creationdate,
modifiedby,
modificationdate
VALUES (
seq_mpinetworkprovider.NEXTVAL,
cur_netrec.providerid,
cur_netrec.mpinetworkcode,
(SELECT otherid
FROM mpi_provider.mpiprovider
WHERE providerid = cur_netrec.providerid),
NVL (cur_netrec.effectivedateoverride,
v_effectivedate),
NVL (cur_netrec.terminationdateoverride,
v_terminationdate),
v_credential,
USER,
TRUNC (SYSDATE),
USER,
TRUNC (SYSDATE)
ELSE
UPDATE mpinetworkprovider
SET effectivedate =
NVL (cur_netrec.effectivedateoverride,
v_effectivedate),
terminationdate =
NVL (cur_netrec.terminationdateoverride,
v_terminationdate),
credentialingtypecode = v_credential,
modificationdate = TRUNC (SYSDATE),
modifiedby = USER
WHERE providerid = cur_netrec.providerid
AND mpinetworkcode = cur_netrec.mpinetworkcode;
END IF;
--update when contract credential type code change
UPDATE mpi_provider.person prs
SET prs.credentialingtypecode =
(SELECT DECODE (MIN (credtype),
1, 'DELEGNCQA',
2, 'DELEGNETEX',
3, 'DELEGATED',
4, 'NONDELEG',
5, 'INDIVIDUAL',
6, 'NONDENETEX',
'NONE')
AS personcredentialingtypecode
FROM (SELECT DECODE (
c.credentialingtypecode,
'DELEGNCQA',
1,
'DELEGNETEX',
2,
'DELEGATED',
3,
'NONDELEG',
4,
'INDIVIDUAL',
5,
'NONDENETEX',
6,
7
AS credtype
FROM mpi_provider.mpicontractprovider cp,
mpi_provider.mpicontract c
WHERE c.mpicontractid =
cp.mpicontractid
AND cp.providerid =
cur_netrec.providerid
AND cp.terminationdate >
SYSDATE))
WHERE prs.providerid = cur_netrec.providerid; -
Question about using for-loop to generate array from DAQmx. Thanks!
I have a laser system with a frequency of 1kHz, I am using this 1kHz signal to trigger the DAQmx and get the data from a photodetector, e.g. I will get 1000 data points during 1 second from DAQmx, but I need to separate this 1000 data points into the even and odd list, which is two list of 500 data points, e.g.. The 1st, 3rd, ... 99th data is one array, the 2nd, 4th,... 10th data is another array, then I will do further calculations based on these two arrays.
To seperate the even and odd data, the only way I can find is put these 1000 points into an array and then seperate them afterwards.
Can I do things like this pic?
I don't know the speed of the for loop, because the 1kHz trigger is always there, once it is triggered, the DAQmx read will give a data point, if the speed of the for-loop( the time from the end of a loop to the beginning of the next loop) is slower than the 1kHz trigger, then the for-loop will miss data point, then the ordering of the 1000 points in 1 second will be changed.
Or I need to put everything, e.g. AI Voltage, Trigger, sample clock, into the for-loop and then return a Y? Thanks!Clarification:
The VI you have posted will work as following:
1) The task will read 2 analog inputs (ai0, ai3).
2) The acquisition starts, oncece digital signal (trigger) is detected on PFI0
3) The sampling rate will be as specified in "rate" control - it is continuous analog input acquisition, which means that after trigger is received (point 2), the board will start to generate hardware clock with frequency you specify as "rate"
4) with each rising edge of that hardware clock, the measurement is taken, and stored into buffer of driver.
5) DAQmx read will try to read "number of samples per channel" number of samples each time is called - and if there is not enough measurement stored in buffer (step 4), then DAQmx read will wait until DAQ card will measure reaquested number of samples (or timeout occurs before requested number of samples has been acquired)
6) DAQmx read will be then called 1000 times - so totaly you will read 1000 * "number of samples per channel" number of samples.
You do not have to be worried about speed of the loop. In fact, if you need to read just 1000 samples, with 1kS/s, then you can remove for loop and you can change measurement mode from continuous to finite samples, and specify number of samples to read to be 1000. You will read them all properly. I recomend you to read User Manual for your DAQ device - lets say M Series User Manual.
I hope it is clear now.
regards,
stefo -
Question about "Enhanced for loop"
public class NewLoopTest{
public NewLoopTest(){
int result=0;
int[] a=new int[20];
for(int i=0;i<a.length;i++){
a=i++;
for(int i:a){
System.out.println("i="+i+";"+"a["+i+"]="+a[i]+";result="+result+"+"+i+"="+(result+i));
result+=i;
System.out.println("-------------");
result=0;
for(int i=0;i<a.length;i++){
System.out.println("i="+i+";"+"a["+i+"]="+a[i]+";result="+result+"+"+i+"="+(result+i));
result+=i;
This code counts sum of the elements of a array.
At first I use the enhanced for loop and at second I use the traditional for.
Enhanced for loop in sdk1.5 returns only even elements of array, am I right?Enhanced for loop in sdk1.5 returns only even
elements of array, am I right?No. It covers them all.
The i in the enhanced for loop is not the index. It's the element at the current index. You don't have access to the index in the new loop because you don't need it.
for (int item : arr) {
System.out.println(item);
// is equivalent to
for (int ix = 0; ix < arr.length; ix++) {
int item = aa[ix];
System.out.println(item);
}The i in your new loop is the same as a [ i ] in the old loop. -
I have a for-loop problem:
I want to write a two for-loops to produce this below output
100
200 205
300 305 310
400 405 410 415
500 505 510 515 520
600 605 610 615 620 625
700 705 710 715 720 725 730
800 805 810 815 820 825 830 835Anyone has some idea, i seem to get stuck!vichet wrote:
Yeah, you all are right! it's my homework.
It looks kinda easy. but at the previous moment, I could not get it to solved.but you did. Good deal!
By the way, do you have any idea on how I can learn to improve my skill to solve such problem quickly? It seems to take me long to solve this problem. and I am worried that it might take me long to write code later on as my brain does not seem to be robust :(Yep, practice, practice, practice. Try to stretch yourself. There are problems posted here every day, so why not try to figure them out? -
Hi everybody,
I have a feeling this is so obvious that I'm missing it, so if anyone would give me some advice, I'd appreciate it.
I have a method with with three parameters that loops through them and progressively adds or subtracts them with a for loop, based on the order. The only way I can think of to do this, though, is with two for loops with almost identical code. I know there must be an easier way to do this, but I think I've been staring at it too long, can anyone give me a hand conceptually, please?
The method is:
private void create( int param1, int param2 ) {
int entries = 5;
double increment;
if( param1 > param2 ) {
increment = param1 - param2;
for( int i = 0; i < entries; i++ ) {
System.out.println( param1 - ( i * increment ) );
} else if( param2 > param1 ) {
increment = param2 - param1;
for( int i = 0; i < entries; i++ ) {
System.out.println( param1 + ( i * increment ) );
}Thanks,
Jezzica85
Edited by: jezzica85 on Mar 30, 2009 2:38 PMprivate void create( int param1, int param2 ) {
if( param1 > param2 ) {
create(param2, param1);
} else if( param2 > param1 ) {
int entries = 5;
double increment = param2 - param1;
for(int i = 0; i < entries; i++ ) {
System.out.println( param2 + (i * param1));
} //equal do nothing?
}or
private void create2( int param1, int param2 ) {
if (param1 != param2) {
int entries = 5;
int minParam = Math.min(param1, param2);
int maxParam = Math.max(param1, param2);
double increment = maxParam - minParam;
for( int i = 0; i < entries; i++ ) {
System.out.println( maxParam - (i * minParam));
}
Maybe you are looking for
-
Cannot Start Microsoft Outlook. Cannot open the Outlook Window. The set fo folders cannot be opened. You must connect to Microsoft Exchange with the current profile before you can synchronize your folders with your Outlook data file (.ost) OK. This i
-
Upgrade to Oracle 11.2.0.4.6
Hi, I am pretty new to the Upgrading and Patching of Oracle Grid and Oracle Database. I managed to upgrade my test database and grid (stand-alone / oracle restart) from version 11.2.0.3.0 to 11.2.0.4.0 successfully. But now I want Upgrade / Patch it
-
Hello-- Can someone tell me how to print the pictures in my cell phone that have been saved?
-
How to start grounding for the architecture role?
Hi , I would like to change to an architect role from developer. I am having 5 year of experience in developing the application using MS Technology. So need information on the same. Regards, Amit
-
How do I make the tool bar displays look like Firefox 3.6?
I have gotten used to the order of the tool bars and would like to make them look like the previous version of Firefox (3.6). Is there a way to move them up or down in FF 4.0?