CS99

Fundamental Programming Concepts
Summer 2001

 

Lab 4: Solutions


Part I: Find the errors

Lab4a.java

/*
* CS99 Lab 4a
* Author: your name here
* NetID: your NetID here
* Date: today's date
*
* Lab4a solicits a temperature (in degrees Farenheit) from the user and
* converts it degrees Celsius.
*/
public class Lab4a {
    public static void main ( String[] args ) {

TokenReader in = new TokenReader( System.in );    

System.out.print("Enter a temperature in degrees Farenheit: ");

double farenheit = in.readDouble();

/* Convert temperature */

double celsius = (5.0/9)*(farenheit - 32);

System.out.println( farenheit + "F = " + celsius + "C" );

}

}


Part II: Simple if-else programs
Part A:

/**
* CS99 Lab 4b
* Author: your name here
* NetID: your NetID here
* Date: today's date
*
* Accept two integers and determine if the second is a multiple of the first."
*/
public class Lab4b
{
    public static void main( String[] args )
    {

TokenReader in = new TokenReader( System.in );

System.out.print( "Enter a non-negative number: " );

int num1 = in.readInt();    

System.out.print( "Enter another non-negative number: " );

int num2 = in.readInt();  

if ( num1%num2 == 0 )

System.out.println( "The first number is a multiple of the second." );

else

System.out.println( "The first number is not a multiple of the second." );
}

}

Part B:

/**
* CS99 Lab 4b
* Author: your name here
* NetID: your NetID here
* Date: today's date
*
* Accept two integers and determine which is larger."
*/
public class Lab4b
{
    public static void main( String[] args )
    {

TokenReader in = new TokenReader( System.in );

System.out.print( "Enter a non-negative number: " );

int num1 = in.readInt();    

System.out.print( "Enter another non-negative number: " );

int num2 = in.readInt();  

if ( num2 > num1 )

System.out.println( "The first number is smaller than the second." );

else

System.out.println( "The first number is larger than the second." );
}

}

Part C:

/**
* CS99 Lab 4b
* Author: your name here
* NetID: your NetID here
* Date: today's date
*
* Accept two integers and which, if any, is larger"
*/
public class Lab4c
{
    public static void main( String[] args )
    {

TokenReader in = new TokenReader( System.in );

System.out.print( "Enter a non-negative number: " );

int num1 = in.readInt();    

System.out.print( "Enter another non-negative number: " );

int num2 = in.readInt();  

if ( num1 > num2 )

System.out.println( "The first number is larger than the second." );

else if ( num 2 > num 1 )

System.out.println( "The second number is larger than the first." );

else

System.out.println( "The numbers are equal." );  

}

}