Tests - Coppin State University



SOME MATERIAL THAT COMPUTER SCIENCE STUDENTS MUST KNOW, C O L D

IMPORTS:

import java.io.*;

import java.util.Scanner;

DECLARATIONS:

final int MAXVAL = 100;

int x, n, numGrade, a, b, c, age, evenCount, oddCount, femaleCount, maleCount, i, sum;

int [ ] y = new int[MAXVAL];

char ch, gender, letGrade, sex, coffee, donuts;

double avg;

String str;

Scanner keyboard = new Scanner(System.in);

SETTING UP TO WORK WITH OUTPUT FILES

FileWrite fwriter = new FileWriter(“test.txt”); //associate fwriter with the actual file test.txt

OR

System.out.print(“What is the output filename? “);

str = keyboard.nextLine();

PrintWriter outputFile = new PrintWriter(str); //later, write to file associated with str

OR

File file = new File(str); //Note the File object

while(file.exists()) //If you don't want to overwrite an existing file

{

System.out.println("The file " + filename + " already exists.");

System.out.print(“What is the NEW output filename? “);

str = keyboard.nextLine();

file = new File(str);

}

PrintWriter outputFile = new PrintWriter(file); //An overloaded version of the PrintWriter constructor

OR

FileWriter fwriter = new FileWriter(str, true); //If you want to append (add) data to an existing file

PrintWriter outputFile = new PrintWriter(fwriter); //Another overloaded version of the PrintWriter constructor

SETTING UP TO WORK WITH INPUT FILES

File file = new File (“test.txt”); //associate file with the actual file test.txt

OR

System.out.print(“What is the input filename? “);

str = keyboard.nextLine();

File file = new File(str); //associate file with the file chosen by the user

while(!file.exists())

{

System.out.print("File " + str + " does not exist—filename? ");

str = keyboard.nextLine();

file = new File(str);

}

Scanner inputFile = new Scanner(file); //the actual reading is done with inputFile

TESTS (if statements):

positive, negative, zero, non-zero

if(x > 0) if(x < 0) if(x = = 0) if(x != 0)

above average, below, etc.

if(x > avg) if(x < avg)

even, odd

if(x % 2 == 0) if(x % 2 != 0)

evenCount++; oddCount++;

lower case, upper case, etc.

if(str.isLowerCase()) if(str.isUpperCase())

female, male

if(sex == ‘f ‘ || sex == ‘F’) if(sex.Character.toUpperCase() == ‘M’)

femaleCount++; maleCount++;

lowercase vowel

if(ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’)

ladders

if(numGrade >= 90)

letGrade = ‘A’;

else if(numGrade >= 80)

letGrade = ‘B’;

else if(numGrade >= 70)

letGrade = ‘C’;

else if(numGrade >= 60)

letGrade = ‘D’;

else //if you fall through to here, it’s below 60—no need to ask

letGrade = ‘F’;

if x is between a and b

if(a ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download