Feb. 26 - Computing Science

advertisement

Assignment3: CMPT 101/104 Simon Fraser University, School of Computing Science

Due by Feb 23, 2004

1.

(8 points) Exercise 7 page 193 of your text

State whether the following are valid switch statements. If not explain why. Assume that n and digit are int variables a) switch(n<=2)

{ case 0: System.out.println(“Draw”);

break; case 1: System.out.println(“Win”);

break; case 2: System.out.println(“Lose”);

break;

}

Not a valid switch statement n<=2 is a relational statement with a logical value

(boolean type), the variable for a switch statement must be of an integral type.

There is no default case, this does not make the loop invalid but it is poor programming practice. b) switch(digit/4)

{ case 0: case 1: System.out.println(“low.”);

break; case 1:case 2: System.out.println(“middle.”);

break; case 3: System.out.println(“high.”);

}

Not valid two occurrences of case 1 c) switch(n%6)

{ case 1: case 2: case 3: case 4; case 5: System.out .println(n);

break; case 0: System.out.println();

}

Valid, switch variable is an integer value. No repeated cases, correct syntax d) switch(n%10)

{ case 0: case 2: case 4: case 6: case 8: System.out.println(“Even”); case 1: case 3: case 5: case 7: System.out.println(“Odd”);

}

Valid, switch variable is an integer value. No repeated cases, correct syntax

2.

(5 points) Exercise 9 page 194 of your text, explain step by step what happens as the code is executed.

Suppose the input is 3. What is the value of beta after the folliwng Java code executes? (Assume all variables are properly declared.)

Beta = Integer.parseInt(keyboard.readLine());

Switch(beta)

( case 3: beta = beta +3; case 1: beta++; break; case 5: beta = beta +5; case 4: beta = beta + 4;

}

Case 3 will execute followed by case 1 beta = (beta+3)++ = 3+3+1=7

3.

(6 points) Exercise 7 page 250 of your text

Suppose that the input is

38

45

71

4

-1 what is the output of the following code? Assume all variables are properly declared. sum = Integer.parseInt(keyboard.readLine()); num = Integer.parseInt(keyboard.readLine()); while(num != -1)

{ sum = sum + num; num = Integer.parseInt(keyboard.readLine());

}

System.out.println(“Sum = “ + sum);

Line 1:sum = 38,

Line 2: num=45

Execute loop as num != -1 sum = 38+45=83 num = 71

Execute loop as num != -1 sum = 83 + 71 =154 num =4

Execute loop as num != -1 sum = 154 +4 =158 num =-1

Loop complete num=-1

Print the output which will be Sum = 158

4.

(6 points) Exercise 18 page 254 of your text

Write a for statement to add all multiples of 3 between 1 and 100 for(i=1, i<=100,i++)

{ if(i%3 == 0)

{

} sum += i;

}

BEFORE completing the programming problems below please note

In the hard copy portion of the assignment you must include each of the following

1) Test plan

2) The final refined algorithm.

3) A listing of the final implemented program, including documentation

5.

(45 points) For research purposes and to assist students, the admissions office of your local university wants to know how well female and male students perform in certain courses. You receive a file that contains female and male student GPA’s and grades in 2 particular courses. You are given the following information about the contents of the file.

a.

Due to confidentiality, the letter code f (or F) is used for a female student, m (or M) is used for a male student. b.

Every line in the file consists of a letter code (m, M, F or f) followed by grade in the first course, the grade in the second course, and the GPA.

There are blank spaces between each of these values. Each line represents data for a single student. c.

Grades are given as integer percentages and must be between 0 and 100. d.

GPA’s are given as floating point numbers with 2 digits following the decimal. e.

The information came from a system which does not discriminate between upper and lower case letters, so the m and f codes in the file may be either upper or lower case. f.

A grade of 0 in any course indicates that the student did not take that course and should therefore not be included in the calculated averages for that course. g.

The number of lines in the file is unknown. Use a while loop to read successive lines of data. DO NOT use a sentinel value to indicate the end of the file. h.

There are no blank lines in the file i.

Any line with incorrect or inconsistent data should be skipped. (for example a flag which is not m,f ,M or F, or a grade <0). An error message informing the user the line number in the file that was skipped and the reason the line was skipped should be printed. j.

There are no format errors in the file (correctly parsing will not cause errors)

Write a program that completes each of the following tasks: a.

Read from the data file, StudentData.txt.

b.

Compute the average grade for each course (computed using only the grades of all students who took that course). c.

Compute the average grade for the female students in each course.

(computed using only the grades of all female students who took that course). d.

Compute the average grade for the male students in each course.

(computed using only the grades of all male students who took that course). e.

Compute the average GPA f.

Compute the average GPA for the female students. g.

Compute the average GPA for the male students h.

Find the maximum and minimum GPA i.

Find the maximum and minimum GPA for female students j.

Find the maximum and minimum GPA for male students k.

Print a table summarizing results a to i and formatted according to the sample below (numbers show formatting not expected values)

Total Number of Students

Mean Grades

GPA range

Number of female Students

Mean Grades (female)

GPA range (female)

Number of male Students

Mean Grades (male)

GPA range (male)

Course #1 Course #2 GPA

136

76

63

79

73

76

194

68

102

66

92

71

200

3.22

0.50 to 3.99

105

3.35

0.50 to 3.99

95

3.23

0.55 to 3.95

Test Plan:

The data in the main test file should test the following situations by having at least one line of each type:

1.

2.

Error ONLY in input of M/F variable NOT M F m or f:

Error ONLY in out of range grade for course 1: t 99 75 3.5 m 102 75 3.5

F -23 75 2.1 f 77 1450 3.

Error ONLY in out of range grade for course 2:

3.3

4.

Error ONLY in out of range for GPA

M 88 -98 2.9 f 97 89 -1.0

M 66 88 4.9

5.

Student who did not take course 1

6.

Student who did not take course 2

7.

Several lines for students of both sexes who took both courses. f 0 88 3.8 m 98 0 3.5

8.

Should assure that numbers of students in each course (total male and female) are all different and the means and ranges are different from each other so the output can be completely checked.

A second data file containing a single incorrect line of data should be used to check that the code can deal with 0 students in any given groupl

Detailed Algorithm:

1.

Declare and Initialize counter variables, variables to accumulate the sums, and variables to hold the maximum and minimum GPAs for each group a.

Total number of students in course1, in course 2, and with GPA

(initialized to 0) b.

Minimum and maximum GPA (max initialized to 0, min to 4.0 or more) c.

Total number of male students and mean grade for male students in course1 (Initialized to 0) d.

Total number of male students and mean grade for male students in course2 (initialized to 0) e.

Total number of male students and minimum and maximum GPAs for male students (mean and number initialized to 0, min to 4.0 or more) f.

Total number of female students and mean grade for female students in course1, g.

Total number of female students and mean grade for female students in course2 (initialized to 0) h.

Total number of female students and minimum and maximum GPAs for female students in course1

Initialize a counter to count the number of lines read to 0

Read the first line of data from the file into a variable

While there are tokens in the last line read repeat the following steps: i.

Increment the number of lines read counter ii.

Tokenize and parse data into four data variables,

1.

1 st

variable is a character indicating male or female, which has acceptable values m, M, f, or F

2.

second variable is the percent score in course 1 and must be between 0 and 100 inclusive

3.

third variable is the percent score in course 2 and must be between 0 and 100 inclusive

4.

fourth variable is GPA and must be between 0.0 and 4.0 inclusive. iii.

Verify that each of the four variables is in the correct ranges. If any one of the four variables has a value outside the allowed ranges then

5.

print an error message indicating the piece of data that is in error and the line number (in the file) in which the error occurred.

6.

read the next line of data

7.

increment the lines read counter

8.

return to the beginning of the repeat block (line above beginning with While) iv.

Accumulate the statistics

1.

Add grade1 to the sum for the total students, and for male or female students. Increment appropriate counters

2.

Add grade 2 to the sum for the total students and for male or female students Increment appropriate counters

3.

Update maximum and minimum GPA for all students, female students and male students if necessary. Increment appropriate counters

Calculate all the necessary means by dividing by the number of students included in each mean. Be sure to check that the number of students is >0 before dividing. If the number of students is 0 then the mean is 0 (nothing has been added to the initial value) and no division needs to be done.

Print the table to display the calculated statistics.

Test files and output for grading:

Input File1 a 43 78 3.0 m 102 75 3.5

F -23 75 2.1 f 77 1450 3.3

M 88 -98 2.9 f 97 89 -1.0

M 66 88 4.9 f 0 88 3.8 m 98 0 3.5 f 69 82 3.60

M 88 55 3.60

F 53 67 2.83 m 47 76 3.41 f 99 100 3.88 f 98 87 3.80 m 43 23 1.44 m 98 56 3.66 m 78 100 3.33 f 90 88 3.93 m 100 100 4.0 f 77 55 3.05 f 99 0 3.9 f 36 0 2.2 f 75 0 2.8 m 0 0 3.6 m 0 0 4.0

Expected output

Error in M/F flag in line 1

Error in M/F flag in line 2

Error in grade 1 in line 3

Error in grade 1 in line 4

Error in grade 2 in line 5

Error in grade 2 in line 6

Error in GPA in line 7

Error in GPA in line 8

Course #1 Course #2 GPA

Total Number of Students 16 13 19

Mean Grades 78 75 3.39

GPA range 1.44 to 4.0

Number of Female Students 9 7 10

Mean Grades (female) 77 81 3.38

GPA range (female) 2.2 to 3.93

Number of Male Students 7 6 9

Mean Grades (male) 78 68 3.39

GPA range (male) 1.44 to 4.0

Listing import java.io.*; import java.util.StringTokenizer; import java.text.DecimalFormat; public class GradeStatistics

{

public static void main(String[] args) throws

IOException, FileNotFoundException

{

String char MaleorFemaleFlag; int grade1, grade2; int numGrade1, numGrade1Female, numGrade1Male; int numGrade2, numGrade2Female, numGrade2Male; int numGPA, numGPAFemale, numGPAMale, numLine; double int

MaleorFemaleStr, inputLine;

GPA; meanGrade1, meanGrade1Female, meanGrade1Male; int double double meanGrade2, meanGrade2Female, meanGrade2Male; meanGPA, meanGPAFemale, meanGPAMale; minGPA, minGPAFemale, minGPAMale; double maxGPA, maxGPAFemale, maxGPAMale;

StringTokenizer tokenizer;

// Declare an instance of class BufferedReader

// with identifier inFile. The argument of the

// constructor is an instance of the class

// FileReader. The argument of the constructor

// for the instance of class FileReader is the

// path to the input data file inData.txt

BufferedReader inFile = new BufferedReader( new FileReader("inData.txt") );

DecimalFormat twoDecimal = new DecimalFormat("0.00");

// Initialize the counters for the number of students

// in each group (male, female all) for each course

// and for the overall GPA numLine = 0; numGrade1 = 0; numGrade1Female = 0;

numGrade1Male numGrade2

= 0;

= 0; numGrade2Female = 0; numGrade2Male = 0; numGPA numGPAFemale numGPAMale

= 0;

= 0;

= 0;

//,Initialize the mean Values for the number of students

// in each group (male, female all) for each course

// and for the overall GPA meanGrade1 = 0; meanGrade1Female = 0; meanGrade1Male = 0; meanGrade2 = 0; meanGrade2Female = 0; meanGrade2Male = 0; meanGPA = 0.0; meanGPAFemale meanGPAMale

= 0.0;

= 0.0; maxGPA maxGPAFemale maxGPAMale minGPA minGPAFemale minGPAMale

= 0.0;

= 0.0;

= 0.0;

= 4.0;

= 4.0;

= 4.0;

// Read the first line in the file

// If there is data in the line inputLine null inputLine = inFile.readLine();

while(inputLine != null )

{ tokenizer = new StringTokenizer(inputLine); numLine++;

// Put the first token into the string

// MaleorFemaleString and convert the string

// to lower case

// Extract the flag that indicates male or female

// which is the first character MaleorFemaleString

MaleorFemaleStr = tokenizer.nextToken().toLowerCase();

MaleorFemaleFlag = MaleorFemaleStr.charAt(0);

// If the flag bit indicating male or female is not

// m or f then skip the line, print a message

// indicating the the line of data has been skipped

// then read the next line of data into string

// inputLine then skip to the end of this time

// through the while loop if( MaleorFemaleFlag != 'f' &&

MaleorFemaleFlag != 'm' )

{

System.out.println("Error in M/F flag in line "

}

+ numLine + "\n"); inputLine = inFile.readLine(); continue;

// Extract the characters of the second token and

// convert the characters to an integer grade1

//

// If grade1 is not between 0 and 100 inclusive

// 1) print an error message indicating grade1 is

// incorrect

// 2) read the next line of data into inputLine

// 3) skip to the biginning of the while loop

}

// grade1 = Integer.parseInt(tokenizer.nextToken()); if( grade1 > 100 || grade1 < 0)

{

System.out.println("Error in grade 1 in line " inputLine = inFile.readLine(); continue;

+ numLine + "\n");

// Extract the characters of the third token and

// convert the characters to an integer grade2

//

// If grade2 is not between 0 and 100 inclusive

// 1) print an error message indicating grade2 is

// incorrect

// 2) read the next line of data into inputLine

// 3) skip to the beginning of the while loop

}

// grade2 = Integer.parseInt(tokenizer.nextToken()); if( grade2 > 100 || grade2 < 0)

{

System.out.println("Error in grade 2 in line " inputLine = inFile.readLine(); continue;

+ numLine + "\n");

// Extract the characters of the fourth token and

// convert the resulting string to a double variable

// GPA

//

// If GPA is not between 0.0 and 4.0 inclusive

// 1) print an error message indicating GPA is

// incorrect

// 2) read the next line of data into inputLine

// 3) skip to the beginning of the while loop

//

GPA = Double.parseDouble(tokenizer.nextToken()); if( GPA > 4.00 || GPA < 0.00)

{

}

System.out.println("Error in GPA in line " inputLine = inFile.readLine(); continue;

+ numLine + "\n");

{

// if the student took course 1 (grade1>0) 1 add

// grade to meanGrade1 and to the correct mean

// meanGrade1Sex and increment appropriate counters if( grade1 > 0) meanGrade1 += grade1; numGrade1++; if( MaleorFemaleFlag == 'f')

{

}

} else

{

} meanGrade1Female += grade1; numGrade1Female++; meanGrade1Male += grade1; numGrade1Male++;

// if the student took course 2 (grade2>0) 1 add

// grade to meanGrade2 and to the correct mean

// meanGrade2Sex increment appropriate counters if( grade2 > 0)

{ meanGrade2 += grade2; numGrade2++; if( MaleorFemaleFlag == 'f')

{ meanGrade2Female += grade2; numGrade2Female++;

} else

{

} meanGrade2Male += grade2; numGrade2Male++;

} if( GPA < minGPA)

{

} if( GPA > maxGPA)

{

} maxGPA = GPA; meanGPA += GPA; numGPA++; if( MaleorFemaleFlag == 'f')

{ minGPA = GPA;

{

} else meanGPAFemale += GPA; numGPAFemale++; if( GPA < minGPAFemale)

{

} minGPAFemale = GPA; if( GPA > maxGPAFemale)

{

} maxGPAFemale = GPA; meanGPAMale += GPA; numGPAMale++; if( GPA < minGPAMale)

{

} minGPAMale = GPA; if( GPA > maxGPAMale)

{

} maxGPAMale = GPA;

}

}

//read next line of data inputLine = inFile.readLine();

// Calculate the mean grades and GPA's

// Before dividing by the number of students

// in the applicable group test to assure that

// that group has at least 1 member.

// If there are no memebers in the group the

// mean will be 0 (the initial value)

if( numGPA > 0)

{

}

meanGPA /= numGPA;

if(numGPAFemale > 0)

{

meanGPAFemale /= numGPAFemale;

}

if(numGPAMale >0)

{

}

meanGPAMale /= numGPAMale;

if(numGrade1 > 0)

{

meanGrade1 /= numGrade1;

}

if(numGrade1Male > 0)

{

meanGrade1Male

}

/= numGrade1Male;

if(numGrade1Female > 0)

{

meanGrade1Female /= numGrade1Female;

}

if(numGrade2 > 0)

{

meanGrade2

}

/= numGrade2;

if(numGrade2Male > 0)

{

meanGrade2Male /= numGrade2Male;

}

if(numGrade2Female > 0)

{

meanGrade2Female

}

/= numGrade2Female;

//Assemble and print the output table

System.out.println("\t\t\t\tCourse #1\t" +

"Course #2\tGPA");

System.out.println("Total Number of Students\t" + numGrade1 + "\t\t" + numGrade2 + "\t\t" + numGPA);

System.out.println("Mean Grades\t\t\t" + meanGrade1 + "\t\t" + meanGrade2

+ "\t\t" + twoDecimal.format(meanGPA));

System.out.println("GPA range\t\t\t\t\t\t\t"

+ minGPA + " to " + maxGPA);

System.out.println("Number of Female Students\t" + numGrade1Female + "\t\t" + numGrade2Female +

"\t\t" + numGPAFemale);

System.out.println("Mean Grades (female)\t\t" + meanGrade1Female + "\t\t" + meanGrade2Female

+ "\t\t" + twoDecimal.format(meanGPAFemale));

System.out.println("GPA range (female)\t\t\t\t\t\t"

+ minGPAFemale + " to " + maxGPAFemale);

System.out.println("Number of Male Students\t\t" +

numGrade1Male + "\t\t" +

numGrade2Male + "\t\t" +

numGPAMale);

System.out.println("Mean Grades (male)\t\t" + meanGrade1Male + "\t\t" + meanGrade2Male + "\t\t" +

} twoDecimal.format(meanGPAMale));

System.out.println("GPA range (male)\t\t\t\t\t\t"

+ minGPAMale + " to " + maxGPAMale);

}

6.

(30 points) Use a while loop to repeat the following series of steps until the user indicates that they do not wish to enter a new value of firstNum and secondNum.

Each specifically described output should be on its own line. a.

Prompt the user for two integers firstNum and secondNum. firstNum must be less than secondNum. Data should be checked and rerequested if secondNum <= firstNum b.

Use a for loop to output all odd integers between firstNum and secondNum. Within this loop also calculate the sum of the squares of all the odd integers between firstNum and secondNum. c.

Output the sum of the squares of all odd integers between firstNum and secondNum d.

Use a do…while loop to add all positive integers less than secondNum.

Output the sum of all positive integers less than secondNum. e.

On a single line, with no spaces between letters output

(secondNum-firstNum)%26 uppercase letters starting at ‘A’ in correct alphabetic order. Use a for loop. f.

Prompt the user and ask if they wish to repeat the calculations with another value of firstNum and secondNum. The requested answer to the question should be yes or no. The user may enter yes or no with any combination of upper and lower case letters. The entered string will be converted to lowercase (or uppercase). If the string is neither yes or no the question will be reasked. If the answer is no the program will terminate. If the answer is yes the program will return to part a of this algorithm.

Test Plan :

Test for the following conditions secondNum < firstNum should rerequest input secondNum > firstNum : all possible combinations of odd and even input of some other string than yes or no (should rerequest whether the user wants to run for another set of integers) secondNum = firstNum odd and even secondNum >= firstNum with secondNum –firstNum less that 26 and greater than 26

Detailed algorithm g.

Prompt the user for two integers firstNum and secondNum. firstNum must be less than secondNum. Data should be checked and rerequested if secondNum <= firstNum h.

Use a for loop to output all odd integers between firstNum and secondNum inclusive. Within this loop also calculate the sum of the squares of all the odd integers between firstNum and secondNum. i.

Output the sum of the squares of all odd integers between firstNum and secondNum j.

Use a do…while loop to add all positive integers less than secondNum.

Output the sum of all positive integers less than secondNum. k.

On a single line, with no spaces between letters output

(secondNum-firstNum)%26 uppercase letters starting at ‘A’ in correct alphabetic order. Use a for loop from 1 to (secondNum-firstNum)%26 .

Prompt the user and ask if they wish to repeat the calculations with another value of firstNum and secondNum. The requested answer to the question should be yes or no. The user may enter yes or no with any combination of upper and lower case letters.

Listing import java.io.*; public class Problem6

{

public static void main(String[] args) throws

IOException, FileNotFoundException

{

String Answer, inputLine; int firstNum, secondNum; int i, counter, sum, sumSq; char ch;

// Declare an instance of class BufferedReader

// with identifier keyboard. The argument of the

// constructor is an instance of the class

// InputStreamReader. The argument of the constructor

// for the instance of class InputStreamReader is the

// standard input System.in

BufferedReader keyboard = new BufferedReader( new InputStreamReader(System.in) );

//,Initialize the Answer and the values of

// the two integers firstNum and seoondNum firstNum = 0; secondNum = 0;

Answer = "yes";

while(Answer.equals("yes") )

{ while(firstNum >= secondNum)

{

System.out.print(" Input smallest integer: ");

System.out.flush(); inputLine = keyboard.readLine(); firstNum = Integer.parseInt(inputLine);

System.out.print(" Input largest integer: ");

System.out.flush(); inputLine = keyboard.readLine(); secondNum = Integer.parseInt(inputLine); if(firstNum >= secondNum)

{

System.out.println(

"Largest integer was less than” +

+ " smallest integer"

}

}

+ " \nplease reenter your values \n\n");

System.out.println();

// Use a for loop to output odd integers between

// firstNum and secondNum and to calculate the sum of

// the squares

// of all the odd integers between firstNum and secondNum sumSq = 0;

System.out.println("Odd numbers between " + firstNum

+ " and " + secondNum + " are"); for(i=firstNum; i<secondNum; i++)

{ if(i%2 == 1)

{

}

}

System.out.print(", " + i); sumSq += i*i;

System.out.println();

// Output the sum of the squares of the odd integers

// between firstNum and secondNum

System.out.println(

"The sum of squares of the odd integers between "

+ firstNum + " and " + secondNum + " is " + sumSq);

System.out.println(); do

{

// Use a do..while loop to add all positive integers

// less than secondNum sum = 0; counter = secondNum;

} counter--; sum += counter; while(counter > 0);

// Output thr sum of all positive integers <secondNum

System.out.println(

"The sum of all positive integers < " + secondNum + " is " + sum);

System.out.println();

// print secondNum-firstNum)%26 characters in

// alphabetical order starting with A ch = 'A'; for(i=0; i<((secondNum-firstNum)%26); i++)

{

}

System.out.print(ch + " "); ch++;

}

}

}

System.out.println();

}

// Ask the user if they wish to repeat the

// calculations for another pair of integers

//The answer requested is yes or no

Answer = ""; while( Answer.equals("") )

{

System.out.println(

"Another set of caculations yes/no?");

System.out.flush();

Answer = keyboard.readLine();

Answer = Answer.toLowerCase(); if ( Answer.equals("yes") )

{ secondNum = 0; firstNum = 0; break;

} else if (Answer.equals("no"))

{ break;

}

Answer = "";

Download