I need Help with loop
Hello everyone this is my first time posting here, i have always find java easy(up to this point), this is my first class in programming java i am just needing help with the "for loops" i cant seem to get the program generate 10 random math questions. if you guys can please help i will appreciate it, i have been working on it for a couple of hours. I am not finished with it yet but thats the only thing i need help with.
import javax.swing.JOptionPane;
public class Lab5
public static void main(String[] args)
int num1 = (int) (Math.random() * 100 + 1);
int num2 = (int) (Math.random() * 100 + 1);
int sum = num1 + num2;
int product = num1 * num2;
int quotient = num1 / num2;
int difference = num1 - num2;
for (int i = 0; i > 11; i++);
int number = (int)(Math.random()*4);
if (number == 0 )
String s1 = JOptionPane.showInputDialog(null, num1 + " + " + num2 + "=" );
if(number == 1)
String s3 = JOptionPane.showInputDialog(null, num1 + " - " + num2 + "=" );
if(number == 2)
String s3 = JOptionPane.showInputDialog(null, num1 + " x " + num2 + "=" );
if(number == 3)
String s4 = JOptionPane.showInputDialog(null, num1 + " ÷ " + num2 + "=" );
for (int i = 0; i > 11; i++);Two problems with this line:
1) The second part of a For loop is the constraint. You have said that for the loop to be entered, i must be greater than 11. Well since you've also told i to begin at 0, this will never happen. Thus, the loop will never enter. You may have meant less than?
2) You put a semicolon in the line. Semicolons are used to end statements. The For loop, when used as a block with curly braces, is not a single statement and does not require a semicolon. Here's the two structures of a basic For loop:
for(int i = 0; i <= 100; i++) {
//this is a block. you can put multiple statements in here and they are all part of the loop
int a = 1;
int b = i;
//if your loop only needs to use a single statement, no braces are required
for(int i = 0; i <= 100; i++)
int a = i;
Similar Messages
-
Hi,
I'm doing a data conversion and am fairly new to PL/SQL.
I have a cursor and in the loop i have a select statement
which returns ORA-01403(no data found). I need to skip this
row in the cursor and continue with the next.
BEGIN
OPEN cur_fill_split;
LOOP
FETCH cur_fill_split into S_ASR,S_CLIENT_NO, S_DIRCODE, S_SPLIT_RATE, I_WAYS,
S_BRANCH_NUMBER, S_BRANCH_NAME, S_DIV_NUMBER, S_DIV_NAME, S_ITEMCODE, S_LINE;
EXIT WHEN cur_fill_split%NOTFOUND;
select order_number INTO N_ORDER_NUMBER from order_header
where cmr_number||client_number||dir_number = s_asr||s_client_no||s_dircode;
SELECT SEQ INTO I_SEQ FROM ORDER_DETAIL
WHERE ORDER_NUMBER = N_ORDER_NUMBER
AND LINE_ORDER_NUMBER = TO_NUMBER(S_LINE);
********(errors on the above select)********
END LOOP;
CLOSE cur_fill_split;
END;
Thanks,
BrianHi,
I think there r 2 methods, one is by giving begin - end inside the loop as shown below 1st ex:
& the 2nd method is by selecting the record count & then based on that value executing further commands.
I think 2nd method is more safer than the 1st method.
Method 1:
1)
-- ---------------Procedure Begin------------------
BEGIN
OPEN cur_fill_split;
LOOP
FETCH cur_fill_split into S_ASR,S_CLIENT_NO, S_DIRCODE, S_SPLIT_RATE, I_WAYS,
S_BRANCH_NUMBER, S_BRANCH_NAME, S_DIV_NUMBER, S_DIV_NAME, S_ITEMCODE, S_LINE;
EXIT WHEN cur_fill_split%NOTFOUND;
select order_number INTO N_ORDER_NUMBER from order_header
where cmr_number||client_number||dir_number = s_asr||s_client_no||s_dircode;
BEGIN
SELECT SEQ INTO I_SEQ FROM ORDER_DETAIL
WHERE ORDER_NUMBER = N_ORDER_NUMBER
AND LINE_ORDER_NUMBER = TO_NUMBER(S_LINE);
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
END;
END LOOP;
CLOSE cur_fill_split;
END;
-- ---------------Procedure End------------------
Method 2)
By selecting the record count & based on that records, deciding the program control.
-- ---------------Procedure Begin------------------
declare
rec_cnt number := 0;
BEGIN
OPEN cur_fill_split;
LOOP
FETCH cur_fill_split into S_ASR,S_CLIENT_NO, S_DIRCODE, S_SPLIT_RATE, I_WAYS,
S_BRANCH_NUMBER, S_BRANCH_NAME, S_DIV_NUMBER, S_DIV_NAME, S_ITEMCODE, S_LINE;
EXIT WHEN cur_fill_split%NOTFOUND;
select order_number INTO N_ORDER_NUMBER from order_header
where cmr_number||client_number||dir_number = s_asr||s_client_no||s_dircode;
/* Here we are using cnt variable & checking for
the record count, if count = 0, then it will skip */
select count(*) into rec_cnt from ORDER_DETAIL
WHERE ORDER_NUMBER = N_ORDER_NUMBER
AND LINE_ORDER_NUMBER = TO_NUMBER(S_LINE);
if rec_cnt > 0 then
SELECT SEQ INTO I_SEQ FROM ORDER_DETAIL
WHERE ORDER_NUMBER = N_ORDER_NUMBER
AND LINE_ORDER_NUMBER = TO_NUMBER(S_LINE);
end if;
END LOOP;
CLOSE cur_fill_split;
END;
-- ---------------Procedure End------------------
Try it out & mail me
Good luck -
Need help with loops! Where can I find them?
I have garageband '09 and when I go through my loops, over half of them are missing. That is to say they are labeled and there is a list of them, but only half work, The rest of them are see-through text and wont play music. It has said I could get them back with a software update but it always comes back that everything is up to date. im wondering if they might be in a folder and garageband doesnt know of that folder as where to look or what. Any Ideas please??
Bachman22 wrote:
only half work, The rest of them are see-through text and wont play music. It has said I could get them back with a software update
http://www.bulletsandbones.com/GB/GBFAQ.html#cantdownloadloops
(Let the page FULLY load. The link to your answer is at the top of your screen) -
Need help with looping/repeat webpage in Apple Script
I would like to repeat an action in AppleScript by opening up a URL page in Safari, closing it, and then re-opening it again.
Can someone please help me with this action? Please be very specific in your response. I am not very familiar with this program.
Thank youtell application "Safari"
repeat with theURL in theURLs
make new document
set URL of front document to theURL
delay 1
repeat until ((do JavaScript "document.readyState" in front document) is "complete")
delay 1
end repeat
close front document
end repeat
end tell
This is what I have so far..but it is not working. It only opens it up ONCE. What I want is for the web page to repeatedly be generating every 1 or 2 seconds, after it closes out the previous one.
I want only ONE website continously being opened up.
Someone help please!! -
Need help with Loop Statements!!!
Hi
im a student just starting to learn Java. I have an assignment but am stuck on the folowing question:
"Describe the operation of the 'for' loop Flow Control statement explaining the function of the initialisation, conditional and iteration parts.
Also describe the operation for the 'while' loop Flow Control statement expaling the function of the initialisation, conditional and iteration parts."
Could someone please help answer it?
(Ive looked in some books but cant find much on asnwering it)
Any help would be much appreciated!
Thanks"Could someone please help answer it?
(Ive looked in some books but cant find much on asnwering it)" - Yes
put this into a for loop so that it takes any number of arguments from the command line - eg
my name is Susie Woosie Floosie (and any number of additional names)
at present it will only output - eg
my name is Susie Woosie
public class forLoop{
public static void main (String []args) {
String firstName = args[0];
String secondName = args[1];
System.out.println("my name is "+firstName+" "+secondName); -
The script below analyses an indesign doc for missing links and then places library asset on the page, cuts and "pastes into" any frame with a missing link (the cut and paste thing sucks, but we can't figure out any other way to avoid an external image source for the missing pic placeholder graphic). The loop finds the missing links except for 2. If there are 5 missing links, it finds 3. If there are 10 missing links, it finds 8...etc. Why won't it catch them all?
Script below:
myCheckGraphics();
function myCheckGraphics(){
myDocument=app.activeDocument;
for(var myCounter = 0; myCounter < myDocument.allGraphics.length; myCounter++){
var myGraphic = myDocument.allGraphics[myCounter];
if(myGraphic.itemLink.status == LinkStatus.LINK_MISSING){
var myLib=app.libraries.item("Missing Link.indl");
if(File.fs == "Macintosh"){
var myLibPath=app.open(File("/Applications/Adobe Indesign CS3/Cover Setup/Missing Link.indl"));
else{
myLibPath=app.open(File("/c/Program%20Files/Adobe/Cover Setup/Missing Link.indl"));
var selectMiss=app.select(myGraphic);
missLink=app.selection[0].parent;
var selectBox=app.select(missLink);
var myX=missLink.visibleBounds;
var myTop=myX[0];
var myLeft=myX[1];
var myBottom=myX[2];
var myRight=myX[3];
var myWide=myRight-myLeft;
var myBigBottom=myBottom-myTop;
if((myWide>35)||(myBigBottom>20)){
myAss=myLib.assets.item("Missing Link Big");
else if((myWide>15)||(myBigBottom>10)){
myAss=myLib.assets.item("Missing Link Medium");
else{
myAss=myLib.assets.item("Missing Link Small");
myMissAlert();
}//end if missing link
}//end for loop
function myMissAlert(){
////place the asset.//////
myAss.placeAsset (myDocument) ;
var myAsset=myDocument.pageItems.item("Missing Link");
var selectAss=app.select(myAsset);
var myDupe = app.copy() ;
var det=myAsset.remove();
var selectBox=app.select(missLink);
var myPaste=app.pasteInto()
app.select(NothingEnum.nothing, undefined);A fairly recurrent "problem" with Indesign.
The loop checks for missing links on an array of images. However, as soon as you correct one of these links, the array it's checking gets updated in the background, so the loop seems to skip every other image!
Suppose you have an array
missingLinks = [ "a", "b", "c" ]
(where all are missing) and you loop from 0 to 2. The first one checks #0 and corrects it. Now the array will change (in the background) to
["b", "c"]
... and your loop happily continues with #1 -- "c".
The common solution is to loop over the array backwards:
for(var myCounter = myDocument.allGraphics.length-1; myCounter >= 0; myCounter--)
Notice you have to use "length - 1" and check "myCounter >= 0", because the array elements are numbered from 0 to length-1 -- perfectly logical for a computer, somewhat less so for a human. The regular forwards loop does exactly the same, but it's a bit more 'hidden' from casual inspection. -
I need help with looping a java file
I am wondering is it possable to loop a java file. By this i mean re-run it again from a particular point in the program. Like where i have marked out below.
import java.util.*;
public class Player
public static void main(String[] args){
Songs listing = new Songs();
Player gui = new Player();
listing.readarray();
// I would like to loop it here once the option has been selected.
Scanner myScanner = new Scanner(System.in);
int option1;
System.out.println("--------Options-------");
System.out.println(" ");
System.out.println("Type Option Number ");
System.out.println(" ");
System.out.println("1 :View Songs");
System.out.println("2 :View Playlist");
System.out.println("3 :Edit Playlist");
System.out.println("4 :Play Playlist");
System.out.println(" ");
System.out.println("What option would you like?");
option1 = myScanner.nextInt();
if (option1 == 1)
listing.disparray();import java.util.*;
public class Player
public static void main(String[] args){
Songs listing = new Songs();
Player gui = new Player();
listing.readarray();
*while (true)*
// I would like to loop it here once the option has been selected.
Scanner myScanner = new Scanner(System.in);
int option1;
System.out.println("--------Options-------");
System.out.println(" ");
System.out.println("Type Option Number ");
System.out.println(" ");
System.out.println("1 :View Songs");
System.out.println("2 :View Playlist");
System.out.println("3 :Edit Playlist");
System.out.println("4 :Play Playlist");
System.out.println(" ");
System.out.println("What option would you like?");
option1 = myScanner.nextInt();
if (option1 == 1)
listing.disparray();
}} -
Help with looping and counting
i am in a CS 1 class and need help with this loop
/*Write a program that will allow the user to enter a character
until the capital letter Z is entered
The program should count the number of letters entered
and print the total after the loop is completed*/
here is what i have it doesn't end nor does it count and i don't know hwo to make it count also i suck at do..while loops hehe
char b,Z=0;
Scanner a = new Scanner(System.in);
do
System.out.print("Enter a letter: "+"\n");
b=a.next().charAt(0);
while (b !=Z);
i know that its not even close to being right just help me out here
Edited by: purplesmurf on Nov 14, 2008 7:25 PMThe following program will count the number of chacters entered until Z is enetered.
import java.io.*;
class count
public static void main(String[] args)throws IOException
char ch;
int cnt=0;
DataInputStream br=new DataInputStream(System.in);
do
System.out.print("Enter a character:");
ch=(char)br.read();
if(ch!='Z')
cnt++;
else
break;
}while((ch=(char)br.read())!='Z');
System.out.println("The Number of entered characters are:"+cnt);
} -
Need Help With File Matching Records
I need help with my file matching program.
Here is how it suppose to work: FileMatch class should contain methods to read oldmast.txt and trans.txt. When a match occurs (i.e., records with the same account number appear in both the master file and the transaction file), add the dollar amount in the transaction record to the current balance in the master record, and write the "newmast.txt" record. (Assume that purchases are indicated by positive amounts in the transaction file and payments by negative amounts.)
When there is a master record for a particular account, but no corresponding transaction record, merely write the master record to "newmast.txt". When there is a transaction record, but no corresponding master record, print to a log file the message "Unmatched transaction record for account number ..." (fill in the account number from the transaction record). The log file should be a text file named "log.txt".
Here is my following program code:
// Exercise 14.8: CreateTextFile.java
// creates a text file
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.AccountRecord;
import org.egan.TransactionRecord;
public class CreateTextFile
private Formatter output1; // object used to output text to file
private Formatter output2; // object used to output text to file
// enable user to open file
public void openTransFile()
try
output1 = new Formatter("trans.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openTransFile
// enable user to open file
public void openOldMastFile()
try
output2 = new Formatter("oldmast.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openOldMastFile
// add transaction records to file
public void addTransactionRecords()
// object to be written to file
TransactionRecord record1 = new TransactionRecord();
Scanner input1 = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s\n%s",
"Enter account number (> 0) and amount.","? ");
while (input1.hasNext()) // loop until end-of-file indicator
try // output values to file
// retrieve data to be output
record1.setAccount(input1.nextInt()); // read account number
record1.setAmount(input1.nextDouble()); // read amount
if (record1.getAccount() > 0)
// write new record
output1.format("%d %.2f\n", record1.getAccount(), record1.getAmount());
} // end if
else
System.out.println("Account number must be greater than 0.");
} // end else
} // end try
catch (FormatterClosedException formatterClosedException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input1.nextLine(); // discard input so user can try again
} // end catch
System.out.printf("%s %s\n%s", "Enter account number (> 0) ",
"and amount.","? ");
} // end while
} // end method addTransactionRecords
// add account records to file
public void addAccountRecords()
// object to be written to file
AccountRecord record2 = new AccountRecord();
Scanner input2 = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s\n%s",
"Enter account number (> 0), first name, last name and balance.","? ");
while (input2.hasNext()) // loop until end-of-file indicator
try // output values to file
// retrieve data to be output
record2.setAccount(input2.nextInt()); // read account number
record2.setFirstName(input2.next()); // read first name
record2.setLastName(input2.next()); // read last name
record2.setBalance(input2.nextDouble()); // read balance
if (record2.getAccount() > 0)
// write new record
output2.format("%d %s %s %.2f\n", record2.getAccount(), record2.getFirstName(),
record2.getLastName(), record2.getBalance());
} // end if
else
System.out.println("Account number must be greater than 0.");
} // end else
} // end try
catch (FormatterClosedException formatterClosedException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input2.nextLine(); // discard input so user can try again
} // end catch
System.out.printf("%s %s\n%s", "Enter account number (> 0),",
"first name, last name and balance.","? ");
} // end while
} // end method addAccountRecords
// close file
public void closeTransFile()
if (output1 != null)
output1.close();
} // end method closeTransFile
// close file
public void closeOldMastFile()
if (output2 != null)
output2.close();
} // end method closeOldMastFile
} // end class CreateTextFile--------------------------------------------------------------------------------------------------
// Exercise 14.8: CreateTextFileTest.java
// Testing class CreateTextFile
public class CreateTextFileTest
// main method begins program execution
public static void main( String args[] )
CreateTextFile application = new CreateTextFile();
application.openTransFile();
application.addTransactionRecords();
application.closeTransFile();
application.openOldMastFile();
application.addAccountRecords();
application.closeOldMastFile();
} // end main
} // end class CreateTextFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.8: TransactionRecord.java
// A class that represents on record of information
package org.egan; // packaged for reuse
public class TransactionRecord
private int account;
private double amount;
// no-argument constructor calls other constructor with default values
public TransactionRecord()
this(0,0.0); // call two-argument constructor
} // end no-argument AccountRecord constructor
// initialize a record
public TransactionRecord(int acct, double amt)
setAccount(acct);
setAmount(amt);
} // end two-argument TransactionRecord constructor
// set account number
public void setAccount(int acct)
account = acct;
} // end method setAccount
// get account number
public int getAccount()
return account;
} // end method getAccount
// set amount
public void setAmount(double amt)
amount = amt;
} // end method setAmount
// get amount
public double getAmount()
return amount;
} // end method getAmount
} // end class TransactionRecord -------------------------------------------------------------------------------------------------
// Exercise 14.8: AccountRecord.java
// A class that represents on record of information
package org.egan; // packaged for reuse
import org.egan.TransactionRecord;
public class AccountRecord
private int account;
private String firstName;
private String lastName;
private double balance;
// no-argument constructor calls other constructor with default values
public AccountRecord()
this(0,"","",0.0); // call four-argument constructor
} // end no-argument AccountRecord constructor
// initialize a record
public AccountRecord(int acct, String first, String last, double bal)
setAccount(acct);
setFirstName(first);
setLastName(last);
setBalance(bal);
} // end four-argument AccountRecord constructor
// set account number
public void setAccount(int acct)
account = acct;
} // end method setAccount
// get account number
public int getAccount()
return account;
} // end method getAccount
// set first name
public void setFirstName(String first)
firstName = first;
} // end method setFirstName
// get first name
public String getFirstName()
return firstName;
} // end method getFirstName
// set last name
public void setLastName(String last)
lastName = last;
} // end method setLastName
// get last name
public String getLastName()
return lastName;
} // end method getLastName
// set balance
public void setBalance(double bal)
balance = bal;
} // end method setBalance
// get balance
public double getBalance()
return balance;
} // end method getBalance
// combine balance and amount
public void combine(TransactionRecord record)
balance = (getBalance() + record.getAmount());
} // end method combine
} // end class AccountRecord -------------------------------------------------------------------------------------------------
// Exercise 14.8: FileMatch.java
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Formatter;
import java.util.FormatterClosedException;
import org.egan.AccountRecord;
import org.egan.TransactionRecord;
public class FileMatch
private Scanner inTransaction;
private Scanner inOldMaster;
private Formatter outNewMaster;
private Formatter theLog;
// enable user to open file
public void openTransFile()
try
inTransaction = new Scanner(new File("trans.txt"));
} // end try
catch (FileNotFoundException fileNotFoundException)
System.err.println("Error opening file.");
System.exit(1);
} // end catch
} // end method openTransFile
// enable user to open file
public void openOldMastFile()
try
inOldMaster = new Scanner(new File("oldmast.txt"));
} // end try
catch (FileNotFoundException fileNotFoundException)
System.err.println("Error opening file.");
System.exit(1);
} // end catch
} // end method openOldMastFile
// enable user to open file
public void openNewMastFile()
try
outNewMaster = new Formatter("newmast.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openNewMastFile
// enable user to open file
public void openLogFile()
try
theLog = new Formatter("log.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openLogFile
// update records
public void updateRecords()
TransactionRecord transaction = new TransactionRecord();
AccountRecord account = new AccountRecord();
try // read records from file using Scanner object
System.out.println("Start file matching.");
while (inTransaction.hasNext() && inOldMaster.hasNext())
transaction.setAccount(inTransaction.nextInt()); // read account number
transaction.setAmount(inTransaction.nextDouble()); // read amount
account.setAccount(inOldMaster.nextInt()); // read account number
account.setFirstName(inOldMaster.next()); // read first name
account.setLastName(inOldMaster.next()); // read last name
account.setBalance(inOldMaster.nextDouble()); // read balance
if (transaction.getAccount() == account.getAccount())
while (inTransaction.hasNext() && transaction.getAccount() == account.getAccount())
account.combine(transaction);
outNewMaster.format("%d %s %s %.2f\n",
account.getAccount(), account.getFirstName(), account.getLastName(),
account.getBalance());
transaction.setAccount(inTransaction.nextInt()); // read account number
transaction.setAmount(inTransaction.nextDouble()); // read amount
else if (transaction.getAccount() != account.getAccount())
outNewMaster.format("%d %s %s %.2f\n",
account.getAccount(), account.getFirstName(), account.getLastName(),
account.getBalance());
theLog.format("%s%d","Unmatched transaction record for account number ",transaction.getAccount());
} // end while
System.out.println("Finish file matching.");
} // end try
catch (NoSuchElementException elementException)
System.err.println("File improperly formed.");
inTransaction.close();
inOldMaster.close();
System.exit(1);
} // end catch
catch (IllegalStateException stateException)
System.err.println("Error reading from file.");
System.exit(1);
} // end catch
} // end method updateRecords
// close file and terminate application
public void closeTransFile()
if (inTransaction != null)
inTransaction.close();
} // end method closeTransFile
// close file and terminate application
public void closeOldMastFile()
if (inOldMaster != null)
inOldMaster.close();
} // end method closeOldMastFile
// close file
public void closeNewMastFile()
if (outNewMaster != null)
outNewMaster.close();
} // end method closeNewMastFile
// close file
public void closeLogFile()
if (theLog != null)
theLog.close();
} // end method closeLogFile
} // end class FileMatch-------------------------------------------------------------------------------------------------
// Exercise 14.8: FileMatchTest.java
// Testing class FileMatch
public class FileMatchTest
// main method begins program execution
public static void main( String args[] )
FileMatch application = new FileMatch();
application.openTransFile();
application.openOldMastFile();
application.openNewMastFile();
application.openLogFile();
application.updateRecords();
application.closeLogFile();
application.closeNewMastFile();
application.closeOldMastFile();
application.closeTransFile();
} // end main
} // end class FileMatchTest-------------------------------------------------------------------------------------------------
Sample data for master file:
Master file
Account Number Name Balance
100 Alan Jones 348.17
300 Mary Smith 27.19
500 Sam Sharp 0.00
700 Suzy Green -14.22Sample data for transaction file:
Transaction file Transaction
Account Number Amount
100 27.14
300 62.11
300 83.89
400 100.56
700 80.78
700 1.53
900 82.17 -------------------------------------------------------------------------------------------------
My FileMatch class program above has bugs in it.
The correct results for the newmast.txt:
100 Alan Jones 375.31
300 Mary Smith 173.19
500 Sam Sharp 0.00
700 Suzy Green 68.09The correct results for the log.txt:
Unmatched transaction record for account number 400Unmatched transaction record for account number 900------------------------------------------------------------------------------------------------
My results for the newmast.txt:
100 Alan Jones 375.31
300 Mary Smith 111.08
500 Sam Sharp 0.00
700 Suzy Green -12.69My results for the log.txt
Unmatched transaction record for account number 700-------------------------------------------------------------------------------------------------
I am not sure what is wrong with my code above to make my results different from the correct results.
Much help is appreciated. Please help.From the output, it looks like one problem is just formatting -- apparently you're including a newline in log entries and not using tabs for the newmast output file.
As to why the numbers are off -- just from glancing over it, it appears that the problem is when you add multiple transaction values. Since account.combine() is so simple, I suspect that you're either adding creating transaction objects incorrectly or not creating them when you should be.
Create test input data that isolates a single case of this (e.g., just the Mary Smith case), and then running your program in a debugger or adding debugging code to the add/combine method, so you can see what's happening in detail.
Also I'd recommend reconsidering your design. It's a red flag if a class has a name with "Create" in it. Classes represent bundles of independant state and transformations on that state, not things to do. -
Need help with a simple process with FTP Adapter and File Adapter
I am trying out a simple BPEL process that gets a file in opaque mode from a FTP server using a FTP adapter and writes it to the local file system using a File Adapter. However, the file written is always empty (zero bytes). I then tried out the FTPDebatching sample using the same FTP server JNDI name and this work fine surprisingly. I also verified by looking at the FTP server logs that my process actually does hit the FTP server and seems to list the files based on the filtering condition - but it does not issue any GET or RETR commands to actually get the files. I am suspecting that the problem could be in the Receive, Assign or Invoke activities, but I am not able identify what it is.
I can provide additional info such as the contents of my bpel and wsdl files if needed.
Would appreciate if someone can help me with this at the earliest.
Thanks
Jaypersiandude wrote:
Topic: Need help with if, else, and which statements and loops.
How would I display 60 < temp. <= 85 in java
System.out.println("60 < temp. <= 85 in java");
another question is how do I ask a question like want to try again (y/n) after a output and asking that everytime I type in yes after a output and terminate when saying No.Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
[http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806]. -
Need help with my addressbook program
hi,
i need help with my program here. this one should works as:
- saves user input into a txt file
- displays name of the saved person on the jlist whenever i run the program
- displays info about the person when clicked via textboxes given by reading the txt file where the user inputs are
- should scroll when the list exceeds the listbox
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.event.*;
import java.io.FilterInputStream;
public class AddressList extends JPanel implements ActionListener
JTextField txt1 = new JTextField();
JTextField txt2 = new JTextField();
JTextField txt3 = new JTextField();
DefaultListModel mdl = new DefaultListModel();
JList list = new JList();
JScrollPane listScroller = new JScrollPane(list);
ListSelectionModel listSelectionModel;
File fob = new File("Address3.txt");
String name;
char[] chars;
public void ListDisplay()
try
RandomAccessFile rand = new RandomAccessFile(fob,"rw");
BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
if(fob.exists())
while((name = rand.readLine()) != null)
chars = name.toCharArray();
if(chars[0] == '*')
mdl.addElement(name);
list.setModel(mdl);
if(chars[0] == '#')
continue;
else
System.out.println("No such file..");
catch(IOException a)
System.out.println(a.getMessage());
public AddressList()
this.setLayout(null);
listSelectionModel = list.getSelectionModel();
listSelectionModel.addListSelectionListener(new ListInfo());
list.setBounds(10,40,330,270);
listScroller.setBounds(320,40,20,100);
add(list);
add(listScroller);
JLabel lbl4 = new JLabel("Name: ");
lbl4.setBounds(400,10,80,30);
add(lbl4);
JLabel lbl5 = new JLabel("Cellphone #: ");
lbl5.setBounds(400,50,80,30);
add(lbl5);
JLabel lbl6 = new JLabel("Address: ");
lbl6.setBounds(400,90,80,30);
add(lbl6);
JLabel lbl7 = new JLabel("List ");
lbl7.setBounds(10,10,100,30);
add(lbl7);
txt1.setBounds(480,10,200,30);
add(txt1);
txt2.setBounds(480,50,200,30);
add(txt2);
txt3.setBounds(480,90,200,30);
add(txt3);
JButton btn1 = new JButton("Add");
btn1.setBounds(480,130,100,30);
btn1.addActionListener(this);
btn1.setActionCommand("Add");
add(btn1);
JButton btn2 = new JButton("Save");
btn2.setBounds(480,170,100,30);
btn2.addActionListener(this);
btn2.setActionCommand("Save");
add(btn2);
JButton btn3 = new JButton("Cancel");
btn3.setBounds(480,210,100,30);
btn3.addActionListener(this);
btn3.setActionCommand("Cancel");
add(btn3);
JButton btn4 = new JButton("Close");
btn4.setBounds(480,250,100,30);
btn4.addActionListener(this);
btn4.setActionCommand("Close");
add(btn4);
public static void main(String[]args)
JFrame frm = new JFrame("Address List");
AddressList panel = new AddressList();
frm.getContentPane().add(panel,"Center");
frm.setSize(700,350);
frm.setVisible(true);
panel.ListDisplay();
public void actionPerformed(ActionEvent e)
String cmd;
cmd = e.getActionCommand();
if(cmd.equals("Add"))
txt1.setText("");
txt2.setText("");
txt3.setText("");
else if(cmd.equals("Save"))
mdl.addElement(txt1.getText());
list.setModel(mdl);
try
RandomAccessFile rand = new RandomAccessFile(fob,"rw");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LineNumberReader line = new LineNumberReader(br);
if(fob.exists())
rand.seek(fob.length());
rand.writeBytes("* " + txt1.getText());
rand.writeBytes("\r\n" + "# " + txt2.getText());
rand.writeBytes("\r\n" + "# " + txt3.getText() + "\r\n");
else
System.out.println("No such file..");
txt1.setText("");
txt2.setText("");
txt3.setText("");
catch(IOException a)
System.out.println(a.getMessage());
else if(cmd.equals("Cancel"))
txt1.setText("");
txt2.setText("");
txt3.setText("");
else if(cmd.equals("Close"))
System.exit(0);
class ListInfo implements ListSelectionListener
public void valueChanged(ListSelectionEvent e)
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
try //*this one should display the info of the person whenever i click the person's name at the list box via textbox.. but i cant seem to get it right since it always display the info of the first person inputed.. i tried to get the program to display them whenever it reads lines with * on them....
File fob = new File("Address3.txt");
RandomAccessFile rand = new RandomAccessFile(fob,"rw");
BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
LineNumberReader line = new LineNumberReader(br);
if(fob.exists())
for(int i = minIndex; i<=maxIndex; i++)
if(lsm.isSelectedIndex(i))
while((name = rand.readLine()) != null)
chars = name.toCharArray();
if(chars[0] == '#')
continue;
if(chars[0] == '*')
txt1.setText(rand.readLine());
txt2.setText(rand.readLine());
txt3.setText(rand.readLine());
else
System.out.println("No such file..");
catch(IOException a)
System.out.println(a.getMessage());
}the only problem now is about how it should display the right info about the person whenever i click its name on the list.. something about file reading or something, i just cant figure it out.
and also about how to make it scroll once it exceeds the list.. i cant make it work, maybe something about wrong declaration..
thanks in advance..
Edited by: syder on Mar 14, 2008 2:26 AMLike said before, do one thing at a time. At startup, something like:
//put all the content in a list
ArrayList<String> lines = new ArrayList<String>();
while(String line=rand.readLine()!=null) {
lines.add(line);
}If you follow the good advice to create a class to encapsulate the entries, you could populate a list of such entries like this:
static final int ENTRY_SIZE = 3;//you have 3 fields now, better to have a constant if that changes
ArrayList<Entry> entries = new ArrayList<Entry>();
for(int i=0; i<lines.size(); i+=ENTRY_SIZE) {
Entry entry = new Entry(lines.get(i), lines.get(i+1), lines.get(i+2);
entries.add(newEntry);
}You could also do both of the above in one run, but I think you will understand better what's happening if you do one thing at a time.
If you don't want to put the entries in an encapsulating class, you can still access this without looping:
int listStartIdx = <desired_entry_index>*ENTRY_SIZE;
String att1 = lines.get(listStartIdx).substring(1);
String att2 = lines.get(listStartIdx+1).substring(1);
String att3 = lines.get(listStartIdx+2).substring(1); -
Need help with connecting file inputs to arrays
In this assignment I have a program that will do the following: display a list of names inputed by the user in reverse order, display any names that begin with M or m, and display any names with 5 or more letters. This is all done with arrays.
That was the fun part. The next part requires me to take the names from a Notepad file, them through the arrays and then output them to a second Notepad file.
Here is the original program: (view in full screen so that the code doesn't get jumbled)
import java.io.*; //Imports the Java library
class progB //Defines class
public static void main (String[] arguments) throws IOException
BufferedReader keyboard; //<-
InputStreamReader reader; // Allows the program to
reader = new InputStreamReader (System.in); // read the the keyboard
keyboard = new BufferedReader (reader); //<-
String name; //Assigns the name variable which will be parsed into...
int newnames; //...the integer variable for the amount of names.
int order = 0; //The integer variable that will be used to set the array size
String[] array; //Dynamic array (empty)
System.out.println (" How many names do you want to input?"); //This will get the number that will later define the array
name = keyboard.readLine ();
newnames = Integer.parseInt (name); // Converts the String into the Integer variable
array = new String [newnames]; //This defines the size of the array
DataInput Imp = new DataInputStream (System.in); //Allows data to be input into the array
String temp;
int length; //Defines the length of the array for a loop later on
for (order = 0 ; order < newnames ; order++) //<-
{ // Takes the inputed names and
System.out.println (" Please input name "); // gives them a number according to
temp = keyboard.readLine (); // the order they were inputed in
array [order] = temp; //<-
for (order = newnames - 1 ; order >= 0 ; order--) //<-
{ // Outputs the names in the reverse
System.out.print (" \n "); // order that they were inputed
System.out.println (" Name " + order + " is " + array [order]); //<-
for (order = 0 ; order < newnames ; order++) //<-
if (array [order].startsWith ("M") || array [order].startsWith ("m")) // Finds and outputs any and all
{ // names that begin with M or m
System.out.print (" \n "); //
System.out.println (array [order] + (" starts with M or m")); //
} //<-
for (order = 0 ; order < newnames ; order++) //<-
length = array [order].length (); //
if (length >= 5) // Finds and outputs names
{ // with 5 or more letters
System.out.print (" \n "); //
System.out.println ("Name " + array [order] + " have 5 or more letters "); //<-
}The notepad file contains the following names:
jim
laruie
tim
timothy
manny
joseph
matty
amanda
I have tried various methods but the one thing that really gets me is the fact that i can't find a way to connect the names to the arrays. Opening the file with FileInputStream is easy enough but using the names and then outputing them is quite hard. (unless i'm thinking too hard and there really is a simple method)By "connect", do you just mean you want to put the names into an array?
array[0] = "jim"
array[1] = "laruie"
and so on?
That shouldn't be difficult at all, provided you know how to open a file for reading, and how to read a line of text from it. You can just read the line of text, put it in the array position you want, until the file is exhausted. Then open a file for writing, loop through the array, and write a line.
What part of all that do you need help with? -
Need help with threads?.. please check my approach!!
Hello frnds,
I am trying to write a program.. who monitors my external tool.. please check my way of doing it.. as whenever i write programs having thread.. i end up goosy.. :(
first let me tell.. what I want from program.. I have to start an external tool.. on separate thread.. (as it takes some time).. then it takes some arguments(3 arguments).. from file.. so i read the file.. and have to run tool.. continously.. until there are arguments left.. in file.. or.. user has stopped it by pressing STOP button..
I have to put a marker in file too.. so that.. if program started again.. file is read from marker postion.. !!
Hope I make clear.. what am trying to do!!
My approach is like..
1. Have two buttons.. START and STOP on Frame..
START--> pressed
2. check marker("$" sign.. placed in beginning of file during start).. on file..
read File from marker.. got 3 arg.. pass it to tool.. and run it.. (on separate thread).. put marker.. (for next reading)
Step 2.. continously..
3. STOP--> pressed
until last thread.. stops.. keep running the tool.. and when last thread stops.. stop reading any more arguments..
Question is:
1. Should i read file again and again.. ?.. or read it once after "$" sign.. store data in array.. and once stopped pressed.. read file again.. and put marker ("$" sign) at last read line..
2. how should i know when my thread has stopped.. so I start tool again??.. am totally confused.. !!
please modify my approach.. if u find anything odd..
Thanks a lot in advance
gerviniHello,
I have no experience with threads or with having more than run "program" in a single java file. All my java files have the same structure. This master.java looks something like this:
---master.java---------------------------------------------------
import java.sql.*;
import...
public class Master {
public static void main(String args []) throws SQLException, IOException {
//create connection pool here
while (true) { // start loop here (each loop takes about five minutes)
// set values of variables
// select a slave process to run (from a list of slave programs)
execute selected slave program
// check for loop exit value
} // end while loop
System.out.println("Program Complete");
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
if (rSet1 != null)
try { rSet1.close(); } catch( SQLException ignore ) { /* ignored */ }
connection.close();
-------end master.java--------------------------------------------------------
This master.java program will run continuously for days or weeks, each time through the loop starting another slave process which runs for five minutes to up to an hour, which means there may be ten to twenty of these slave processes running simultaneously.
I believe threads is the best way to do this, but I don't know where to locate these slave programs: either inside the master.java program or separate slave.java files? I will need help with either method.
Your help is greatly appreciated. Thank you.
Logan -
i'm making a game at the moment.......
i need help with a way to check all the hashmaps of enimies in a class called room......i need to check if they all == 0...when they all equal zero the game ends......
i know i can check the size of a hash map with size().....but i want to check if all the hashmaps within all the rooms == 0.First of all stop cross posting. These values in the HashMap, they are a "Collection" of values, so what is wrong with reply two and putting all these collections of values into a super collection? A collection of collections? You can have a HashMap of HashMaps. One HashMap that holds all your maps and then you can use a for loop to check if they are empty. A map is probably a bad choice for this operation as you don't need a key and an array will be much faster.
HashMap [] allMaps = {new HashMap(),new HashMap()}; -
Hi All,
This is Rajani. I need help on LOOP AT SCREEN statement.
I have 3 selection blocks in the selection screen.
First block contains two radio buttions, the second block contains 6 parameters and the third block contains 3 parameters.
If the first radiobutton is selected, then the parameters in the third block should be grayed out.
In the similar way for the second radiobutton.
Please let me know my mistake from the following code :
SELECTION-SCREEN BEGIN OF BLOCK B1 WITH FRAME TITLE TEXT-001.
PARAMETERS : P_SALES TYPE C RADIOBUTTON GROUP G1 MODIF ID R1,
P_OPS TYPE C RADIOBUTTON GROUP G1 MODIF ID R1,
P_MONTH TYPE SPMON OBLIGATORY MODIF ID R1.
SELECTION-SCREEN END OF BLOCK B1.
SELECTION-SCREEN BEGIN OF BLOCK B2 WITH FRAME TITLE TEXT-002.
PARAMETERS : P_SADIS TYPE BZIRK MODIF ID M1,
P_CUGRP TYPE KDGRP MODIF ID M1,
P_SADCH TYPE VTWEG MODIF ID M1,
P_SADIV TYPE SPART MODIF ID M1,
P_CUPAR TYPE HIEZU04 MODIF ID M1,
P_MAGRP TYPE MVGR1 MODIF ID M1,
P_PRHIE TYPE PRODH1 MODIF ID M1.
SELECT-OPTIONS: S_MATNR FOR S889-MATNR.
PARAMETERS : P_PLANT TYPE WERKS_EXT.
SELECTION-SCREEN END OF BLOCK B2.
SELECTION-SCREEN BEGIN OF BLOCK B3 WITH FRAME TITLE TEXT-003.
PARAMETERS : P_WERKS TYPE WERKS_EXT MODIF ID M2,
P_MATGR TYPE PMNUX MODIF ID M2,
P_MRPCN TYPE DISPO MODIF ID M2.
SELECTION-SCREEN END OF BLOCK B3.
*INITIALIZATION.
AT SELECTION-SCREEN OUTPUT.
LOOP AT SCREEN.
IF SCREEN-GROUP1 = 'M1'.
IF P_OPS = 'X'.
SCREEN-INPUT = '0'.
ENDIF.
MODIFY SCREEN.
ENDIF.
IF SCREEN-GROUP1 = 'M2'.
IF P_SALES = 'X'.
SCREEN-INPUT = '0'.
ENDIF.
MODIFY SCREEN.
ENDIF.
ENDLOOP.Hi,
This is your expected solution.
TABLES: mara.
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
PARAMETERS : p_sales TYPE c RADIOBUTTON GROUP g1 USER-COMMAND ucom DEFAULT 'X', "MODIF ID r1
p_ops TYPE c RADIOBUTTON GROUP g1 . "MODIF ID r1
PARAMETERS: p_month TYPE spmon OBLIGATORY ." MODIF ID r1
SELECTION-SCREEN END OF BLOCK b1.
SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.
PARAMETERS : p_sadis TYPE bzirk MODIF ID m1,
p_cugrp TYPE kdgrp MODIF ID m1,
p_sadch TYPE vtweg MODIF ID m1,
p_sadiv TYPE spart MODIF ID m1,
p_cupar TYPE hiezu04 MODIF ID m1,
p_magrp TYPE mvgr1 MODIF ID m1,
p_prhie TYPE prodh1 MODIF ID m1.
SELECT-OPTIONS: s_matnr FOR mara-matnr.
PARAMETERS : p_plant TYPE werks_ext.
SELECTION-SCREEN END OF BLOCK b2.
SELECTION-SCREEN BEGIN OF BLOCK b3 WITH FRAME TITLE text-003.
PARAMETERS : p_werks TYPE werks_ext MODIF ID m2,
p_matgr TYPE pmnux MODIF ID m2,
p_mrpcn TYPE dispo MODIF ID m2.
SELECTION-SCREEN END OF BLOCK b3.
AT SELECTION-SCREEN.
AT SELECTION-SCREEN OUTPUT.
LOOP AT SCREEN.
IF p_sales = 'X'.
IF screen-group1 = 'M2'.
screen-input = '0'.
ENDIF.
ENDIF.
IF p_ops IS NOT INITIAL.
IF screen-group1 = 'M1'.
screen-input = '0'.
ENDIF.
ENDIF.
MODIFY SCREEN.
ENDLOOP.
Close this thread if you got soloution.
Regards,
Peranandam
Maybe you are looking for
-
Profile manager w/o Apple Push Certification
Hello all. Is it possible to use Profile manager without using Apple Push Certification? The Mac Pro running Lion Server has no Internet access but i want to use it to manage network accounts for the lab (all iMac and Mac Mini systems). Can this be d
-
Just upgraded from Snow Leopard Server to Mountain Lion Server. Running into a few issues that I can't resolve. 1. Updated wiped out my Users. Cannot add a User becuase the "+" is grayed out, same for groups. All I see are my local users which I
-
When I run the same job the film using CS5 or CVS4 the film separation is differently. The screens aren't the same, It looks like the is a profile that effects the film while running using CS5. I have check and under Color setting -Preserve Numbers
-
Gregorian (or other) in getting time and date
import java.util.*; public class CalendarTest public static void main (String[] args) Calendar myDate = Calendar.getInstance(); System.out.println (myDate.toString()); }gives me a looong string of garbled info. how do i extract
-
Finder problem or LaCie HD problem
How do I tell whether my external HD (LaCie d2 quadra) used for TM failed or if the trouble is with my Mac (Finder)? Today I had trouble saving a pages document. The Finder showed the spinning beach ball When I typed the 1st few letter of the destina