Need help with a reverse number method
hey all..
i have this program which should return the integer reversed ..
i have done this program using methods.. but the problem is if the
number endes with 0 when it reversed the output doesn't contain the number 0
for example:
input
123450
output
54321
where before the 5 there should be 0
This program that reads an integer and then calls a method
that receives an integer and returns the integer with its digits reversed.
Main prints the resulting integer.
import java.util.Scanner; // program uses class Scanner
class Sh9q4
// main method begins execution of Java application
public static void main( String args[] )
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
int number; // The number entered by the user
System.out.println("Enter an integer"); // prompt for input
number = input.nextInt(); // read the the integer
reverse (number); // print the method reverse
} // end method main
public static void reverse ( int num )
int lastDigit; // the last digit returned when reversed
int reverse = 0;
do
lastDigit = num % 10;
reverse = (reverse * 10) + lastDigit;
num = num / 10;
while (num > 0);
System.out.println("The integer with its digits reversed " + reverse); // print the integer reversed
}// end method reverse
} // end class Sh9q4thanks for your help :)
If you need the leading zero to display, then you will have to do as Keith recommended and convert the input number to a String, then reverse that String and print it as a String.
A number is a number is a numerical value, and there is no difference between the value of 054321 and 54321 except when written as a literal, when the first is an octal, and the second a decimal, value.
If you are still confused, plug in these few lines of code and run them:String str = "012345";
int x = Integer.parseInt (str);
System.out.println(str);
System.out.println(x);db
Similar Messages
-
I need help with my serial number. I downloaded soundbooth cs3 to restore my downloaded purchase, but my serial number is not being accepted. I have 16 more days to resolve this. I don't need tech support, I just need the software I purchased to work for me. That's not to much to ask, is it? Can anyone from adobe help me please?
ChrisError "The serial number is not valid for this product" | Creative Suite
-
Need help with Rounding a number.
I have 3 cells each with a formula in them. Please bear with me while I try to explain this.
Cell D18 contains the formula: =Sum(L18/C5) (L18's value is 58, C5's value is 10), So the value of the cell is 5.8. I need this number to round properly to 6. It does visually on the spreadsheet.
Cell F18 contains the formula: =Sum(E18/F5) (E18=28, F5=8) So the actual value of F18 is 3.5 which is rounded to 4 visually on the spreadsheet.
Cell G18 contains the formula =Sum(D18+F18). (D18 visually displays 6, F18 visually displays 4, therefore G18 should display 10). G18 actually displays 9. For some reason the calculations are still based on the actual calculations of D18 & F18, instead of the rounded displayed numbers. How do I get G18 to display the correct number of 10, rather than the rounded down number of 9?
I'm sure there's a simple fix that I'm just not understanding. I hope I explained my problem well enough, I'd appreciate any help I can get. These numbers are to calculate insulin dosage, so I need to be sure the math is correct.
Thanks in advance for any help!yvieinca wrote:
I have 3 cells each with a formula in them. Please bear with me while I try to explain this.
Cell D18 contains the formula: =Sum(L18/C5) (L18's value is 58, C5's value is 10), So the value of the cell is 5.8. I need this number to round properly to 6. It does visually on the spreadsheet.
Cell F18 contains the formula: =Sum(E18/F5) (E18=28, F5=8) So the actual value of F18 is 3.5 which is rounded to 4 visually on the spreadsheet.
Cell G18 contains the formula =Sum(D18+F18). (D18 visually displays 6, F18 visually displays 4, therefore G18 should display 10). G18 actually displays 9. For some reason the calculations are still based on the actual calculations of D18 & F18, instead of the rounded displayed numbers. How do I get G18 to display the correct number of 10, rather than the rounded down number of 9?
The explanation is that you don't understand what you are doing.
When you ask numbers to display 0 decimal, you don't ask it to round the contents but to display the rounded value.
A contents remains 3.6 but the display is 4
an other contents may be 3.6 too displaying 4
When you sum, you ask number to add the contents (3.6 + 3.6) which is 7.2 and you ask it to display the rounded value of this result. So you correctly see 7 not 8.
If you want to get what you described, you MUST force Numbers to round.
First,I don't understand how you may invent such a silly thing like =Sum(L8/C5)
You are asking Numbers to sum the result of the division L8/C5 to nothing.
The correct syntax would ask it to calculate the quotient, no less no more.
=L8/C5
but here we need to round so, in D18, enter
=ROUND(L8/C5,0)
in F18, enter
=ROUND(E8/F5,0)
In G18, =Sum(D18+F18) is silly too.
You are asking nummber to sum (D18+F18) and nothing.
The correct formula may be:
=SUM(D18,F18)
or
=D18+F18
Yvan KOENIG (from FRANCE samedi 13 juin 2009 18:05:33) -
Need help with formatting a number
hi all,
the problem i am having has been a hot topic over time in java. i have an integer say 123. i want to convert this to a string of 10 characters. how do i pad the first seven spaces with blanks. ex. " 123" in c++ you can use sprintf. how do i do this in java. i have seen mention of NumberFormat but being new to java cannot figure this class out. any helpful code would be much appreciated.
thanksThat would certainly works but it is not the most efficent method to achive the goal since it discards String objects left right and center (especially if you want more than 10 padding spaces)
public String pad(Integer i) {
String value = i.toString();
StringBuffer buff = new StringBuffer();
for( int i = 0, n = ( 10 - value.length ); i < n; i++ ) {
buff.append( " " );
return buff.toString() + value;
} -
Need help with union-by-size method
Hello :)
I'm having a problem with a union-by-size method.
It was originally intended for a university assignment, but as I'm getting random errors by using it, I've changed to using union-by-heigth instead (which works flawlessly :-).
But I'm still very much interested in finding out what I did wrong with the union-by-size implementation (as I belive it'd be the better method since I use path compression and a lot of find(x)).
So if anyone can tell me what I'm doing wrong with the following code, I'd really appreciate it. As it is it is I'm getting ArrayIndexOutOfBoundsException with a positive much higher number than the array contains (ie. 1606 with a 900 long array)...
(I've also gotten a few stackoverflows in main, but I guess that is more with too much printouts... )
int[] union-by-size-array = new int[n*n] //implemented in other part of the code
private void union (int root1, int root2){
int temporaryInteger;
if(union-by-size-array[root2] < union-by-size-array[root1]){
temporaryInteger = union-by-size-array[root2];
union-by-size-array[root1] = root2;
union-by-size-array[navn2] += temporaryInteger;
}else {
temporaryInteger = union-by-size-array[root1];
union-by-size-array[root2] = root1;
union-by-size-array[root1] += temporaryInteger;
}Ok, I'll supplement.
n is given by the user as an argument.
int nrOfDisJointSets = 1;
int[][] board = new int[n][n];
int[] ] union-by-size-array = new int[n+1];
private void createNewNodeBoard(){
for(int i = 0; i < n; i++){
for(int j = 0; j <n; j++){
board[i][j] = createNode();
private Node createNode(){
Node newNode = new Node(nrOfDisJointSetst);
union-by-size-array[nrOfDisJointSets] = -1;
nrOfDisJointSets++;
return newNode;
}the union method is called by the following line
union(find(x), find(y));navn2 is supposed to be root2 btw.. -
Need help with understanding Skype Number please
Hi there,
Not sure if this is posted twice!
I live in the UK and am trying to offer online coaching through a company in America. I can only offer live chat sessions if I have a US or Canadian number. Is it a Skype Number that I need? Why would it matter which State I choose - will people only be able to contact me from that State?
Would be really grateful for some clarity.
Many thanks,
Solved!
Go to Solution.Hi, Tracy255, and welcome to the Community,
Unfortunately, for several reasons, Skype Numbers are not available in Canada.
The concept of any virtual number is to provide a way for people who do not have accounts on the service to contact the subscriber, but using a fixed line or land line number. In the case of Skype Numbers in the United States, the best scenario would be to have a number set up where most of your customers would be able to call without incurring high toll charges or ideally no toll charges. Of note, not all states participate in the Skype Number program, again for any number of legitimate reasons.
Skype does not offer "toll-free" numbers.
Here is a link to the library of FAQ articles related to Skype Numbers seeing as I believe you will have more questions than I have provided information for!
https://support.skype.com/en/category/ONLINE_NUMBER_SKYPEIN/
Please pardon the naming convention confusion; today's Skype Numbers where formerly known as Online Numbers or Skype In.
Regards,
Elaine
Was your question answered? Please click on the Accept as a Solution link so everyone can quickly find what works! Like a post or want to say, "Thank You" - ?? Click on the Kudos button!
Trustworthy information: Brian Krebs: 3 Basic Rules for Online Safety and Consumer Reports: Guide to Internet Security Online Safety Tip: Change your passwords often! -
Need help with forward/reverse animation depending on playhead position
I'm trying to create a side-scrolling image gallery, with a series of thumbnails at the top that will take you to their corresponding full size images. I've been able to make them link to the correct frames, and able to animate the scrolling going in one direction, but the scrolling in reverse is presenting a challenge. It might be an easy fix, it might not.
Basically, in my non-AS3 literate mind, the way I imagine it would work is I'll have animations in my timeline corresponding to forward and reverse, and depending on what frame the playhead is on when a user clicks the thumbnail, it will play a certain portion of one animation or the other. So how would I accomplish this? A series of 'if' and 'then' commands?
I don't know the syntax (yet). If anyone has been down this road before and can give me some guidance, I'd sure appreciate it.
Thanks!Based on the code you show, it would appear that your image changing involves timeline-based animations, unless you have stop();s in all the frames you gotoAndPlay. I can only guess that's how you have it... one images transitions into another as you move along the timeline.
Actionscript is the coded approach, but beyond moving around to different frames. The ultimate coded version of this occupies one frame of one layer and is all code (possibly just one line of code, importing the real code from a Class file), with all content being loaded dynamically from a server.
Here's something I offered for another posting from today that took another approach that involved having all the content in the file and a bit of timeline transition--I've edited it slightly. Maybe you can get an idea from it.
... you could create each slide as a movieclip which transitions in and out, with a stop on the first frame and on the frame where it is in full view. Using a variable or two to keep track of things, such as the current slide and the next slide, you could have your buttons call a function that identifies/assigns the next slide, and commands the current slide transition out. At the end of that transition (last frame), you assign the next slide to be the current slide and tell that slide to transition in. Here's a working example that you can look at...
http://www.nedwebs.com/Flash/AS3_slideshow.fla -
The serial number is on the back of the box my DVD came in.
If you only have 18 numbers that's not a serial number. Try this first:
Find your serial number quickly -
Need help with the puk number to m 4gsim card
My phone has locked me out someone please tell me what to do
Let's resolve this Jst1911@doc! The default pin is 1111. View more information and visuals here http://vz.to/19nhXLQ Please share if you need additional assistance. Thank you.
TominqueBo_VZW
Please follow us on Twitter @VZWSupport -
Need help with my file receiving method ??????
Hi, I have a method that can recieve files from other peers. Currently, it can recieve any file name such as d1.txt, d2.txt ...d5.txt. However, my method doesn't know the file name of the file it is recieving and assigns it to c:\\files\d1.txt. How can I change my method so that It knows what the file name is that it is receiving and assign it properly? thanks
public void receive() throws IOException {
try {
ServerSocket ss = new ServerSocket(1234);
while (true) {
Socket s = ss.accept();
BufferedInputStream bis =
new BufferedInputStream(
s.getInputStream());
FileOutputStream fis =
new FileOutputStream(c:\\files\d1.txt);
BufferedOutputStream bos =
new BufferedOutputStream(fis);
int c, i = 0;
c = bis.read();
while (c != -1) {
bos.write(c);
c = bis.read();
bos.flush();
bos.close();
fis.close();
bis.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}I see two options:
1. send (and thus receive) the file name first
2. use a static variable that you increment for each new file
Kind regards,
Levi
PS. your writing algorithm is very slow, right? -
Need Help with a getText method
Gday all,
I need help with a getText method, i need to extract text from a JTextField. Although this text then needs to converted to a double so that i can multiply a number that i have already specified. As you may of guessed that the text i need to extract already will be in a double format.e.g 0.1 or 0.0000004 etc
Thanks for your help
ps heres what i have already done its not very good though
ToBeConverted.getText();
( need help here)
double amount = (and here)
total = (amount*.621371192);
Converted.setText("= " + total);Double.parseDouble( textField.getText() );
-
Hi, I am new to java and need help with sound methods.
q: create a new method that will halve the volume of the positive values and double the volume of the negative values.
Message was edited by:
Apaula30duplicate message #2
-
I can't find my serial number and once I do I would like to move my Pro to another computer. Need help with both.
Hi Rick ,
Here is the link that will help you find the serial number for your product quickly .
https://helpx.adobe.com/x-productkb/global/find-serial-number.html
You would have to deactivate that software from your older machine first.
Refer to the following link to deactivate your product .
https://helpx.adobe.com/x-productkb/policy-pricing/activation-deactivation-products.html
After it is deactivated from the older machine you can use it on your new machine just by entering the serial number of the product .
Let us know if you need further assistance.
Regards
Sukrit Dhingra -
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 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.
Maybe you are looking for
-
My Ipod touch plays music but every time I open an app that I have downloaded it closes immediately. This started happening after updating to the latest version of Ipod software.
-
Droplet not creating folder cs4 photoshop windows 7
so i created a script that creats folder and subfolders inside ( folder1\subfolder1\subfolder2 etc" and i run the script in photoshot cs4 11.0 it creats the foldets no prob. yet when i creat a droplet it wont work. the folders dont get made... i hav
-
HT202213 ITunes and homesharing and apple tv on iMac G5
followed all instructions and the appletv connects, says it is reading the library then fails. also, there is no homesharing item in the left tree on itunes. homesharing is on and logged in though.
-
I don't know what my daughter did but her screen is just black when you go to her camera option. I tap the screen and still no options are available to do anything. What happened and what do I do to fix this?
-
How to make the Commit after calling a BAPI from SE37 ?
Hi When i use a BAPI for update some SAP table i always call the BAPI inside a program and then i call the BAPI_TRANSACTION_COMMIT for made the changes and validate them Bot now i need to test the BAPI directly in SE37 , and the BAPI returns the suce