0% found this document useful (0 votes)
15 views5 pages

Java Programming Exercises Overview

The document contains a series of Java programming exercises focused on using conditional statements, loops, and graphical output with JOptionPane. It includes examples of comparison, average calculation, logical operators, and drawing shapes. Each exercise demonstrates specific programming concepts and techniques in Java.

Uploaded by

jiblavalle
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views5 pages

Java Programming Exercises Overview

The document contains a series of Java programming exercises focused on using conditional statements, loops, and graphical output with JOptionPane. It includes examples of comparison, average calculation, logical operators, and drawing shapes. Each exercise demonstrates specific programming concepts and techniques in Java.

Uploaded by

jiblavalle
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

}

Exer #10
Using if statements, relational operators, ___________________________________________
and equality operators Exer #11
//Average
import [Link]; import [Link];

public class Comparison { public class Average1 {


public static void main( String args[] ) public static void main( String args[] )
{ {
String firstNumber, // first string entered by user int total=0,
secondNumber, // second string entered by user gradeCounter=0,
result; // a string containing the output gradeValue,
int number1, // first number to compare average;
number2; // second number to compare String grade;

// read first number from user as a string while ( gradeCounter < 10 ) {


firstNumber = grade = [Link](
[Link]( "Enter first integer:" ); "Enter integer grade: " );

// read second number from user as a string gradeValue = [Link]( grade );


secondNumber =
[Link]( "Enter second total = total + gradeValue;
integer:" );

// convert numbers from type String to type int gradeCounter = gradeCounter + 1;


number1 = [Link]( firstNumber ); }
number2 = [Link]( secondNumber );
average = total / 10;
// initialize result to the empty string [Link](null, "Class average is
result = ""; " + average, "Class Average",
JOptionPane.INFORMATION_MESSAGE );
if ( number1 == number2 )
[Link]( 0 );
result = number1 + " == " + number2; }
}
if ( number1 != number2 ) _____________________________________________
result = number1 + " != " + number2; Exer#12
// An addition program
if ( number1 < number2 )
result = result + "\n" + number1 + " < " + number2; import [Link]; // import class
JOptionPane
if ( number1 > number2 )
result = result + "\n" + number1 + " > " + number2; public class Addition {
public static void main( String args[] )
if ( number1 <= number2 ) {
result = result + "\n" + number1 + " <= " + number2; String firstNumber, // first string entered by user
secondNumber; // second string entered by user
if ( number1 >= number2 ) int number1, // first number to add
result = result + "\n" + number1 + " >= " + number2; number2, // second number to add
sum; // sum of number1 and number2
// Display results
[Link]( // read in first number from user as a string
null, result, "Comparison Results", firstNumber = [Link]( "Enter
JOptionPane.INFORMATION_MESSAGE ); first integer" );

[Link]( 0 ); // read in second number from user as a string


}
secondNumber = [Link]( "Enter "\ntrue && false: " + ( true && false ) +
second integer" ); "\ntrue && true: " + ( true && true );

// convert numbers from type String to type int output += "\n\nLogical OR (||)" +
number1 = [Link]( firstNumber ); "\nfalse || false: " + ( false || false ) +
number2 = [Link]( secondNumber ); "\nfalse || true: " + ( false || true ) +
"\ntrue || false: " + ( true || false ) +
// add the numbers "\ntrue || true: " + ( true || true );
sum = number1 + number2;
output += "\n\nBoolean logical AND (&)" +
// display the results "\nfalse & false: " + ( false & false ) +
[Link]( null, "The sum is " + "\nfalse & true: " + ( false & true ) +
sum + " units", "Results", "\ntrue & false: " + ( true & false ) +
JOptionPane.WARNING_MESSAGE ); "\ntrue & true: " + ( true & true );

[Link]( 0 ); // terminate the program output += "\n\nBoolean logical inclusive OR (|)" +


} "\nfalse | false: " + ( false | false ) +
} "\nfalse | true: " + ( false | true ) +
_____________________________________________ "\ntrue | false: " + ( true | false ) +
Exer #13 "\ntrue | true: " + ( true | true );
//Row
import [Link]; output += "\n\nBoolean logical exclusive OR (^)" +
"\nfalse ^ false: " + ( false ^ false ) +
public class remov { "\nfalse ^ true: " + ( false ^ true ) +
public static void main( String args[] ) "\ntrue ^ false: " + ( true ^ false ) +
{ "\ntrue ^ true: " + ( true ^ true );
String output = "";
output += "\n\nLogical NOT (!)" +
y: "\n!false: " + ( !false ) +
for ( int row = 1; row <= 20; row++ ) { "\n!true: " + ( !true );
output += "\n";
[Link]( output );
for ( int column = 1; column <= 20; column++ ) { [Link]( null, scroller,
"Truth Tables", JOptionPane.INFORMATION_MESSAGE
if ( column > row ) );
continue y; [Link]( 0 );
output += "* "; }
} }
} _____________________________________________
Exer #15
[Link]( // Using the continue statement with a label
null, output,"Testing continue with a label", import [Link];
JOptionPane.INFORMATION_MESSAGE );
[Link]( 0 ); public class ContinueLabelTest {
} public static void main( String args[] )
____________________________________________ {
Exer #14 String output = "";
// Demonstrating the logical operators
nextRow: // target label of continue statement
import [Link].*; for ( int row = 1; row <= 5; row++ ) {
output += "\n";
public class LogicalOperators {
public static void main( String args[] ) for ( int column = 1; column <= 10; column++ ) {
{
JTextArea outputArea = new JTextArea( 17, 10 ); if ( column > row )
JScrollPane scroller = new JScrollPane( outputArea ); continue nextRow; // next iteration of
String output = ""; // labeled loop

output += "Logical AND (&&)" + output += "* ";


"\nfalse && false: " + ( false && false ) + }
"\nfalse && true: " + ( false && true ) + }
[Link]( null, output );
[Link]( [Link]( 0 );
null, output,"Testing continue with a label", }
JOptionPane.INFORMATION_MESSAGE ); }
[Link]( 0 );
}
}

____________________________________________
Exer # 16
import [Link];
import [Link];
public class BreakLabelTest { import [Link];
public static void main( String args[] )
{ public class WhileCounter extends JApplet {
String output=""; public void paint( Graphics g )
{
x: { int counter = 0; // initialization
for ( int row = 0; row <= 10; row++ ) {
for ( int column = 0; column <= 6 ; column++ ) { while ( counter++ <= 5 ) { // repetition condition
[Link]( 10, 10*counter, 250, counter * 10 );
if ( row == 4 ) //++counter; // increment
break x; }
}
output += "x "; }
} _______________________________________________

output += "\n"; import [Link];


} import [Link];

public class ForCounter extends JApplet {


// output += "\nLoops terminated normally"; public void paint( Graphics g )
// } {
// Initialization, repetition condition and incrementing
[Link]( // are all included in the for structure header.
null, output,"break with a label", for ( int counter = 1; counter <= 10; counter++ )
JOptionPane.INFORMATION_MESSAGE ); [Link]( 10, 10, 250, counter * 10 );
[Link]( 0 ); }
} }
} Exer #18
// Calculating compound interest
_____________________________________________ import [Link];
Exer #17 import [Link];
// Using the continue statement in a for structure import [Link];
import [Link];
public class Interest {
public class ContinueTest { public static void main( String args[] )
public static void main( String args[] ) {
{ double amount, principal = 1000000.0, rate = .05;
String output = "";
DecimalFormat precisionTwo = new DecimalFormat( "$
for ( int count = 1; count <= 10; count++ ) { ##,###,##0.00" );
if ( count == 5 ) JTextArea outputTextArea = new JTextArea( 11, 20 );
continue; // skip remaining code in loop
// only if count == 5 [Link]( "Year\tAmount on deposit\
n" );
output += count + " ";
} for ( int year = 1; year <= 10; year++ ) {
amount = principal * [Link]( 1.0 + rate, year );
output += "\nUsed continue to skip printing 5"; [Link]( year + "\t" +
[Link]( amount ) + "\n" ); {
} int counter = 1;

[Link]( do {
null, outputTextArea, "Compound Interest", [Link]( 110 - counter *10, 110 - counter * 10,
JOptionPane.INFORMATION_MESSAGE ); counter * 20, counter * 20 );
++counter;
[Link]( 0 ); // terminate the application } while ( counter <= 10 );
} }
} }
_____________________________________________
Exer #19 Exer #20
// Drawing shapes // Using the break statement in a for structure
import [Link]; import [Link];
import [Link].*;
public class BreakTest {
public class SwitchTest extends JApplet { public static void main( String args[] )
int choice; {
String output = "";
public void init() int count;
{
String input; for ( count = 1; count <= 10; count++ ) {
if ( count == 5 )
input = [Link]( break; // break loop only if count == 5
"Enter 1 to draw lines\n" +
"Enter 2 to draw rectangles\n" + output += count + " ";
"Enter 3 to draw ovals\n" ); }

choice = [Link]( input ); output += "\nBroke out of loop at count = " + count;
}
[Link]( null, output );
public void paint( Graphics g ) [Link]( 0 );
{ }
for ( int i = 0; i < 10; i++ ) { }
switch( choice ) {
case 1: ___________________________________________
[Link]( 10, 10, 250, 10 + i * 10 );
break;
case 2:
[Link]( 10 + i * 10, 10 + i * 10,
50 + i * 10, 50 + i * 10 );
break;
case 3:
[Link]( 10 + i * 10, 10 + i * 10,
50 + i * 10, 50 + i * 10 );
break;
default:
[Link](
null, "Invalid value entered" );
} // end switch
} // end for
} // end paint()
} // end class SwitchTest

________________________________________

import [Link];
import [Link];

public class DoWhileTest extends JApplet {


public void paint( Graphics g )

Common questions

Powered by AI

Labeled loops, such as those used in 'ContinueLabelTest' and 'BreakLabelTest', allow greater control within nested loops by directing flow to the specific labeled part of a code block. In 'ContinueLabelTest', the 'continue nextRow;' statement skips the remaining statements and proceeds with the next iteration of the outer loop ('nextRow'). In contrast, 'BreakLabelTest' utilizes a label 'x:' to terminate both the inner and outer loops when 'row == 4', demonstrating a break from multiple loops simultaneously. This control structure enhances readability and manages complex loop controls more succinctly .

The 'BreakTest' program uses a break statement within a for loop that iterates from 1 to 10. It immediately breaks the loop when the counter reaches 5, thereby terminating the loop prematurely. The output is numbers from 1 to 4, followed by a message indicating that the loop broke at count = 5. This demonstrates a controlled exit from a loop based on a specific condition, which can be used to optimize operations by preventing unnecessary iterations once a predefined state is achieved .

The 'Comparison' program reads two integers from user input and uses if statements to compare them using equality and relational operators. The program initializes an empty string 'result' and adds comparisons: equality (==), inequality (!=), less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=). The potential outputs include lines that indicate whether the first integer is equal to, not equal to, less than, greater than, less than or equal, or greater than or equal to the second integer, displayed in message dialogs .

The 'DoWhileTest' applet employs a do-while loop to draw ovals, ensuring the loop executes its block at least once by checking its condition after drawing. It starts with counter=1, drawing the first oval before evaluating 'counter <= 10', which controls subsequent iterations. The key distinction from a while loop is that a do-while loop guarantees execution of the loop body at least once, even if the termination condition is false at the outset, which is crucial for scenarios requiring minimum guaranteed execution .

The 'Average1' program calculates the average by initializing 'total' and 'gradeCounter' variables to zero and using a while loop to iterate until ten grades are entered. It reads grades as strings, converts them to integers, and accumulates their sum in 'total'. The average is computed by dividing 'total' by 10. The program assumes exactly ten grades will be entered and uses integer division for the average, which may result in a loss of precision if the average is not a whole number .

The 'LogicalOperators' program uses a JTextArea to compile and display results of various logical operations, including logical AND (&&), logical OR (||), boolean logical inclusive OR (|), boolean logical exclusive OR (^), and logical NOT (!). It evaluates and prints combinations of true and false using each operator. For instance, it shows that 'true && true' results in 'true' whereas 'false && true' results in 'false'. The program helps understand the behavior of these operators through tabulated truth tables .

Both 'WhileCounter' and 'ForCounter' are Java applets used for drawing lines with the AWT 'drawLine' method in a graphical window. 'WhileCounter' uses a while loop to repeatedly draw lines starting from 'y' positions incrementing by ten until a condition is met, emphasizing repetition control external to the loop. In contrast, 'ForCounter' uses a for loop where initialization, condition, and increment are encapsulated within the loop header, illustrating compact syntax and ease of managing iteration directly inside the loop structure. Both utilize AWT methods to perform graphical operations based on loop iterations .

The 'Interest' program calculates compound interest using the formula 'amount = principal * Math.pow(1.0 + rate, year)' over ten years. Starting with a principal of 1,000,000.0 and an interest rate of 5%, it iterates yearly, computing the amount on deposit by applying the compounding effect using Math.pow(), which raises the base of '1 + rate' to the power of the current year. This illustrates the principle of compound interest in finance, where accumulated interest also earns interest over time, leading to exponential growth of the principal .

The 'SwitchTest' applet uses a switch statement to decide which shape to draw based on user input. The 'choice' input determines the case executed: drawing lines, rectangles, or ovals by iterating ten times. Each case corresponds to a Graphics method (drawLine, drawRect, or drawOval), and the default case handles invalid input with an error message. This structured decision-making process using switch statements enhances readability and efficiency in executing block-specific code based on distinct user-specified conditions .

In the 'Addition' program, user inputs for two numbers are initially received as strings using 'JOptionPane.showInputDialog'. These inputs are then converted from strings to integers using 'Integer.parseInt' to allow arithmetic operations. After conversion, the program calculates the sum of the integers and displays the result in a message dialog with a custom message including the word 'units', using 'JOptionPane.showMessageDialog' with a warning message type .

You might also like