lect10 Methods

Download Report

Transcript lect10 Methods

Files Review
• For output to a file:
– FileOutputStream variable initialized to
filename (String) and append/not append
(boolean)
– PrintWriter variable initialized to
FileOutputStream variable
• For input from file:
– File variable initialized to filename (String)
– Scanner variable initialized to File variable
import java.util.Scanner;
import java.io.*;
mydata.txt file
class FormatFileData
{
public static void main(String [ ] args)
throws IOException
{
int loops, integer, i;
float decimal;
String name;
5
8 9.3 Jon
6 14.335 Bill
0 35.67e9 Mary
-23 -4.55 Smith
-3 -4e3 xyz
File ifile = new File("mydata.txt");
Scanner scan = new Scanner(ifile);
loops = scan.nextInt();
for(i= 0 ; i < loops; i++)
{
integer = scan.nextInt();
decimal = scan.nextFloat();
name= scan.next();
System.out.print(integer + " ");
System.out.print(decimal + " ");
System.out.print(name + " ");
System.out.println();
}
Output:
8 9.3 Jon
6 14.335 Bill
0 3.567E10 Mary
-23 -4.55 Smith
-3 –4000.0 xyz
Determining End of File
• There is a scan.hasNext() in JAVA
• Not used to determine if there is a String
• Used to Detect End of File (EOF), i.e.,
there is nothing left to read in the file
• Returns false if at EOF
Methods
public static void
main(String [] args)
{
…
displayVals();
…
displayVals();
…
…
displayVals();
return(0);
}
public static void
displayVals()
{
System.out.println(…);
System.out.println(…);
System.out.println(…);
return; /*back to where
we left off */
}
Methods
• Method: A Discrete Piece of Code that
Performs a Specific Operation or Task
• Named with a Descriptive Identifier
• Called from main() or Another Method
• When Called, Program Control (Execution) Is
Transferred to the method
• Method Performs Required Tasks, and then
Possibly Returns a Value
• After Return from Method, Control Returns to
the Statement Following the Method Call
Method Attributes
• Method Name: Identifier Used to Call
method
• Method Parameter(s) or Argument(s):
Value(s) Passed into method for Use by
method Code
• Method Return Value: Value Returned by
method Back to Calling method
Method Parameters
(Arguments)
• May Pass as Many Parameters as
Necessary to method
• A Copy of the Value of the Parameter Is
Passed to the Method
• Changing the Value of the Parameter in
the Method Does Not Affect the Value of
the Original Variable
• This Is Called Pass-by-Value
Methods – Return Values
• Methods Are Typed According to Their
Return Values: void, int, double,
etc.
• Method Returns a Value to Calling method
via return Statement
public static void main(String [ ] args)
{
int val = 9,resultSq;
resultSq = squareVal(val);
System.out.println(“squareVal returned: "
+ resultSq);
resultSq = squareVal(12);
}
public static int squareVal(int numToSq)
{
System.out.println("In squareVal ");
return(numToSq * numToSq);
}