smallest integers

advertisement
1. What is the output of the following segment?
int n = 35;
while( true ) {
if( n <= 1 ) break;
n = n/2;
System.out.println(n);
} // end while
17
8
4
2
1
2. What is the output of the following segment?
int i = 0;
int j = 12;
while( i < j ) {
i += 1;
j -= 1;
System.out.println(i + " " + j);
} // end while
1
2
3
4
5
6
11
10
9
8
7
6
3. Trace the execution of the following code fragments to determine their outputs.
double x = -1.0;
do
{
System.out.print(x);
x = x + 0.5;
} while ( x <= 1.0 );
-1.0 -0.5 0.0 0.5 1.0
for ( int r = 1; r <= 4; r++)
{
for ( int c = 1; c <= r; c++)
System.out.print(“*”);
System.out.println();
}
*
**
***
****
4. Write a loop (of any kind) that will generate the following output:
10 9 8 7 6 5 4 3 2 1 0
for ( int k = 10; k >= 0; k--)
System.out.print( k + “ “ );
5. Write a code segment inside main to do the following:
- Write a while loop to input Strings using methods from Scanner class
- Prompt the user whether to enter another String (no/n stop)
- Accumulate the Strings in a String variable out with a space between the Strings and
print out after the while loop
Scanner scan = new Scanner(System.in);
String output = “”;
while (true)
{
System.out.println(“Please enter a string”);
String output += scan.next();
System.out.print(“Do you want to enter another one
(yes/no)?”);
String temp = scan.next();
if(temp.equalsIgnoreCase(“no”) ||
temp.equalsIgnoreCase(“n”))
break;
}
System.out.println(output);
6. Write a loop to input numbers (ints) using methods from Scanner class until the user
enter -1. Sum the numbers in an int variable sum. Finally, print out the sum value of
all numbers except the last number, -1.
Scanner scan = new Scanner(System.in);
int sum = 0;
while (true)
{
System.out.println(“Please enter an integer (-1 to
stop)”);
int input = scan.nextInt();
if(input == -1) break;
sum += input;
}
7. Suppose numbers is an int array and contains several int values. Write a code segment
using a for loop to print out each number.
for(int i = 0; i < numbers.length; i++)
System.out.println(numbers[i]);
//foreach is much easilier to do this
8. Write a method
String concatenateAll(String [] words)
that accumulates all of the words in the String array words into a single String with a tab
between each word and returns the result.
String concatenateAll(String []words)
{
if(words.length == 0)
return null;
else
{
String result = “”;
for(int i = 0; i < words.length - 1; i++)
result += words[i] + “\t”;
result += words[length-1];
return result;
}
}
9. Design a class called Student. The class will have three private fields, a String field
representing Student first name, a String field for last name and an ArrayList<Integer>
field representing the list of scores that the student has. Include a constructor with first
name and last name as arguments, accessors, mutators, the equals methods ( objects of
the class are equal if the student names are equal ) and a toString method.
//File Student.java
import java.util.ArrayList;
import java.util.Iterator;
public class Student
{
private String fName;
private String lName;
private ArrayList<Integer> scores;
//Constructor
public Student (String fName, String lName)
{
this.fName = fName;
this.lName = lName;
scores = new ArrayList<Integer> ();
}
//Accessor
public String getFirstName()
{
return fName;
}
public String getLastName()
{
return lName;
}
public ArrayList<Integer> getScores()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Iterator iter = scores.iterator();
while(iter.hasNext())
{
temp.add((Integer)iter.next());
}
return temp;
//Wrong implementation
//return scores;
}
//mutator
public void setFirstName(String fName)
{
this.fName = fName;
}
public void setLastName(String lName)
{
this.lName = lName;
}
public void setScores(ArrayList<Integer> s)
{
Iterator iter = s.iterator();
while(iter.hasNext())
{
scores.add((Integer)iter.next());
}
//Wrong implementation
//scores = s;
}
public boolean equals(Student std)
{
if(fName.equals(std.getFirstName()) &&
lName.equals(std.getLastName()))
return true;
else
return false;
}
public String toString()
{
return fName + " " + lName + " : " + scores;
}
}
//File StudentTest
import java.util.ArrayList;
public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student("David", "Yang");
Student s2 = new Student("David", "Yang");
Student s3 = new Student("Yanxiang", "Yang");
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(100);
scores.add(99);
scores.add(95);
s1.setScores(scores);
System.out.println(s1);
scores.add(2, 98);
System.out.println(s1);
ArrayList<Integer> scoresTwo = s1.getScores();
scoresTwo.add(2, 90);
s2.setScores(scoresTwo);
System.out.println(s1);
System.out.println(s2);
if(s1.equals(s2))
System.out.println("Student s1 is equal to Student
s2");
else
System.out.println("Student s1 is not equal to
Student s2");
if(s1.equals(s3))
System.out.println("Student s1 is equal to Student
s3");
else
System.out.println("Student s1 is not equal to
Student s3");
}
}
10. Write a code fragment for each of the following.
Declare and create an array, list, to store n integers. (n is an integer variable)
int[] list = new int[ n ] ;
Create a random number generator, randy.
Random randy = new Random();
Write a loop that uses randy to fill the array list with randomly generated integers
between 20 and 80 (inclusive)
for ( int k = 0; k < list.length; k++ )
{
int number = randy.nextInt( 80 – 20 + 1) + 20;
list[ k ] = number;
}
Print the rounded average of the integers stored in array list.
int total = 0.0;
for ( int k = 0; k < list.length; k++ )
total += list[k];
double average =(int)((double)total/list.length + 0.5);
System.out.println( “Average “ + average );
Print the largest and smallest integers stored in array list.
int max = list[0];
int min = list[0];
for ( int k = 0; k < list.length; k++ )
{
if ( list[ k ] > max )
max = list[ k ];
if ( list[ k ] < min )
min = list[ k ];
}
System.out.println( “Smallest “ + min + “ Largest “ +
max );
11. Objects of the DataSet class may be used to accumulate various statistics about a set
of real (double) data values, for example, the test scores of students in a class. Give a
partial implementation of the DataSet class that allows the count, mean, maximum and
minimum of the data values to be calculated
public class DataSet
{
//Instance Variables
private double sum;
private double min;
private double max;
private int count;
//Constructor
public DataSet()
{
sum = 0.0;
min = 0.0;
max = 0.0;
count = 0;
}
//Mutator: add a data value to the data set
public void add( double item )
{
count++;
sum += item;
if ( count == 1 )
{ min = item; max = item;}
else if ( item < min )
min = item;
else if ( item > max )
max = item;
}
//Accessors
public int getCount() { return count; }
public double getMean() { return mean; }
public double getMinimum() { return min; }
public double getMaximum() { return max; }
}
Write an application that builds a DataSet object for the gpa’s of a set of students.
 First, input the individual gpa’s, and add them to the DataSet (negative value to
terminate loop).
 After entering all gpas, report whether the gpa is above, equal to, or below the
average gpa of the set.
public class ProcessGPAs
{
public static void main( String[] args )
{
Scanner inp = new Scanner( System.in );
DataSet set = new DataSet();
System.out.println(“Enter student GPA’s ending with
-1.0”);
double gpa = inp.nextDouble();
while ( gpa >= 0.0 )
{
set.add( gpa );
gpa = inp.nextDouble();
}
double mean = set.getMean();
System.out.println(“Output gpa status for all
students: ”);
while ( inp.hasNext() );
{
gpa = inp.nextDouble();
if ( gpa < mean )
System.out.println(gpa + “ is BELOW
average”);
else if ( gpa > mean )
System.out.println(gpa + “ is ABOVE
average”);
else
System.out.println(gpa + “ is average”):
}
}
}
Download