Homework/Program #5 Solutions



Similar documents
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Programming with Java GUI components

Sample CSE8A midterm Multiple Choice (circle one)

Advanced Network Programming Lab using Java. Angelos Stavrou

Using Files as Input/Output in Java 5.0 Applications

Using A Frame for Output

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Chapter 2 Introduction to Java programming

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

Assignment No.3. /*-- Program for addition of two numbers using C++ --*/

Graphical User Interfaces

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Object Oriented Software Design

Object-Oriented Programming in Java

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

CS 335 Lecture 06 Java Programming GUI and Swing

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Swing. A Quick Tutorial on Programming Swing Applications

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Introduction to Programming

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

AP Computer Science Java Mr. Clausen Program 9A, 9B

Lösningsförslag till tentamen

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

13 File Output and Input

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

J a v a Quiz (Unit 3, Test 0 Practice)

AP Computer Science Java Subset

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Topic 11 Scanner object, conditional execution

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

In this Chapter you ll learn:

Introduction to the Java Programming Language

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Course Intro Instructor Intro Java Intro, Continued

Install Java Development Kit (JDK) 1.8

JAVA ARRAY EXAMPLE PDF

Tutorial Reference Manual. Java WireFusion 4.1

Extending Desktop Applications to the Web

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

Using Two-Dimensional Arrays


Essentials of the Java(TM) Programming Language, Part 1

AP Computer Science Static Methods, Strings, User Input

Arrays in Java. Working with Arrays

OBJECT ORIENTED PROGRAMMING LANGUAGE

Object Oriented Software Design

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Tema: Encriptación por Transposición

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

An Overview of Java. overview-1

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Continuous Integration Part 2

Unit 6. Loop statements

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

public class demo1swing extends JFrame implements ActionListener{

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

public static void main(string[] args) { System.out.println("hello, world"); } }

AP Computer Science File Input with Scanner

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

How to Install Java onto your system

Creating a Simple, Multithreaded Chat System with Java

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

D06 PROGRAMMING with JAVA

CS 106 Introduction to Computer Science I

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Iteration CHAPTER 6. Topic Summary

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

JiST Graphical User Interface Event Viewer. Mark Fong

Comp 248 Introduction to Programming

OBJECT ORIENTED PROGRAMMING IN JAVA EXERCISES

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Chapter 3. Input and output. 3.1 The System class

WRITING DATA TO A BINARY FILE

Data Structures Lecture 1

Assignment # 2: Design Patterns and GUIs

Building a Multi-Threaded Web Server

CS170 Lab 11 Abstract Data Types & Objects

Analysis Of Source Lines Of Code(SLOC) Metric

Transcription:

Homework/Program #5 Solutions Problem #1 (20 points) Using the standard Java Scanner class. Look at http://natch3z.blogspot.com/2008/11/read-text-file-using-javautilscanner.html as an exampleof using the Scanner class and opening a file for reading. Modify the TextApplet example on page 296 in your book to do the following: 1. Change the applet to a program using the usual technique. 2. The text input box should be relabeled Filename 3. When you type a valid filename into the box and hit enter on your keyboard, your program should read the file indicated and display its contents in the JTextArea (scrollable text area next to Output ) using Scanner. 4. If the file is not found (this is what is called throwing an exception ), the JTextArea should clear the contents and display File Not Found!. This clear and display logic would replace the e.printstacktrace() in the blogspot example. Exceptions have not yet been covered in class,you should simply mimic the try except logic of the blogspot example. 5. Pressing the Clear Output button should clear the JTextArea. import objectdraw.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.scanner; import java.io.*; class TextApplet extends Controller implements ActionListener private static final int ROWS = 10; // rows in TextArea private static final int COLS = 30; // cols in text field & area private JTextField Filename; // Input field private JTextArea output; // output area private JButton clear; // button to clear output public void begin() Container contentpane = getcontentpane(); JPanel toppanel = new JPanel(); // prepare text field & label JLabel inlabel = new JLabel("Filename:"); Filename = new JTextField(COLS); Filename.addActionListener(this); toppanel.add(inlabel); toppanel.add(filename); contentpane.add(toppanel,borderlayout.north); JPanel centerpanel = new JPanel(); // prepare text area & label JLabel outlabel = new JLabel("Output:"); output = new JTextArea(ROWS, COLS); output.seteditable(false); centerpanel.add(outlabel); centerpanel.add(new JScrollPane(output)); contentpane.add(centerpanel,borderlayout.center);

JPanel bottompanel = new JPanel(); // create button clear = new JButton("clear output"); clear.addactionlistener(this); bottompanel.add(clear); contentpane.add(bottompanel,borderlayout.south); validate(); // add text to area if user hits return, else erase text area public void actionperformed(actionevent evt) if (evt.getsource() == Filename) try File file = new File(Filename.getText()); Scanner scanner = new Scanner(file); scanner.usedelimiter(system.getproperty("line.separator")); while (scanner.hasnext()) output.append(scanner.next()+"\n"); scanner.close(); catch (FileNotFoundException e) output.settext(""); output.settext("file Not Found!"); else // clear button pressed output.settext(""); public static void main(string args[]) new TextApplet().startController(600,400);

Problem #2 (10 points) Modify your code from Problem #1 to (It is highly suggested to make it a different Program) 1. Add an additional button labeled Count placed next to the clear output button 2. Add an additional JLabel That will display the number of characters of the text that is currently displayed in the JTextArea. This label should be updated when the Count button is pressed by the user. You should use a panel with a FlowLayout for the buttons and label. Include code Include screen output when what is displayed is the java source code that answers this problem (i.e. your program). Your screenshot should be taken after the Count button has been pressed. import objectdraw.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.scanner; import java.io.*; class TextAppletCount extends Controller implements ActionListener private static final int ROWS = 10; // rows in TextArea private static final int COLS = 30; // cols in text field & area private JTextField Filename; // Input field private JTextArea output; // output area private JButton clear; // button to clear output private JButton count; private JLabel countlabel; public void begin() Container contentpane = getcontentpane(); JPanel toppanel = new JPanel(); // prepare text field & label

JLabel inlabel = new JLabel("Filename:"); Filename = new JTextField(COLS); Filename.addActionListener(this); toppanel.add(inlabel); toppanel.add(filename); contentpane.add(toppanel,borderlayout.north); JPanel centerpanel = new JPanel(); // prepare text area & label JLabel outlabel = new JLabel("Output:"); output = new JTextArea(ROWS, COLS); output.seteditable(false); centerpanel.add(outlabel); centerpanel.add(new JScrollPane(output)); contentpane.add(centerpanel,borderlayout.center); JPanel bottompanel = new JPanel(); // create button clear = new JButton("clear output"); count = new JButton("Count"); countlabel=new JLabel(); clear.addactionlistener(this); count.addactionlistener(this); bottompanel.setlayout(new FlowLayout()); bottompanel.add(clear); bottompanel.add(count); bottompanel.add(countlabel); contentpane.add(bottompanel,borderlayout.south); validate(); // add text to area if user hits return, else erase text area public void actionperformed(actionevent evt) if (evt.getsource() == Filename) try File file = new File(Filename.getText()); Scanner scanner = new Scanner(file); scanner.usedelimiter(system.getproperty("line.separator")); while (scanner.hasnext()) output.append(scanner.next()+"\n"); scanner.close(); catch (FileNotFoundException e) output.settext(""); output.settext("file Not Found!"); else if(evt.getsource()== count) countlabel.settext("count:"+output.getdocument().getlength()); else // clear button pressed output.settext("");

public static void main(string args[]) new TextAppletCount().startController(600,400); Problem #3 (10 points) JAEA Exercise 13.6.1 Modify so that the corrected isprime method is invoked as part of main program called Prime. Prime takes an integer argument from the command line and properly determines if anumber is prime. Include code Include output of running Prime with input values of 17, 27, 37, 47, 57, 81 class Prime public static boolean isprime(int n) int divisor =n-1; boolean evenlydivisible=false; while(divisor>1 &&!evenlydivisible) evenlydivisible=((n%divisor)==0); divisor--; return!evenlydivisible; public static void main(string args[]) if(args.length==1) System.out.println("is Prime:"+isPrime(Integer.parseInt(args[0]))); else System.out.println("Incorrect Input!");

Problem #4 (10 points) Fun with for loops In each of the following, create a valid for( ; ; ) statement to achieve the desired results of the following two-line code segment: for ( ; ; ) System.out.println(i); example: print out integers from 1 to 10 ans: for (i = 1; i <= 10; i++) (a) print out integers from 10 to 1 (b) print out 2k k=0,1,2,3,... 20 (c) print out every seventh integer starting at 14 ending at 98 (d) print out the numbers from 1 to 41 that are NOT evenly divisible by 3 (e) print out the numbers 1,3,6,10,15,21,28,36,45,55 (Hint: int j = i = 1; is a legal statement that initializes both i and j to 1) (a) for(i=10;i>=1;i--) (b) for(i=1;i<=math.pow(2,20);i=i*2) alternate solution for (i = 1; i <= 1 << 20; i*=2) (c) for(i=14;i<=98;i=i+7) (d) for(i=1;i<=41;i=i+i%3) (e) for(int j=i=1;i<=55;j=j+1,i=i+j) alternate solution for(int j=i=1; j++ <= 10; i += j) Problem #6 (10 points) (a) what is the fundamental difference between do... while(); and a while() loops? do... while() loop -- The condition is checked each time after executing the loop body. While() loop The condition is checked each time before executing the loop body. A do... while() loop always executes the body of the loop at least once. A while() loop may never execute the body of the loop; (b) Write a pair of nested for loops that print the multiplication tables for 1 through 10 for (int i=1;i<=10;i++) for(int j=1;j<=10;j++) System.out.print(i*j+" ");

System.out.println(); (c) Look up the definition of the break; statement. What does the following code print out? (attempt this without compiling the code!) int n = 0; for (int i = 1; i <= 5; i++) System.out.print( i + : ); for (int j = 1 ; j <= 5 ; j++) n++; if (j * i >= 15) break; System.out.print(j * i + ); System.out.println( ); System.out.println( Iterations: + n); 1: 1 2 3 4 5 2: 2 4 6 8 10 3: 3 6 9 12 4: 4 8 12 5: 5 10 Iterations: 22 (d) Look up the definition of the continue; statement. What does the following code print out? (attempt this without compiling the code!) int n = 0; for (int i = 1; i <= 5; i++) System.out.print( i + : ); for (int j = 1 ; j <= 5 ; j++) n++; if (j * i >= 15) continue; System.out.print(j * i + ); System.out.println( ); System.out.println( Iterations: + n); 1: 1 2 3 4 5 2: 2 4 6 8 10 3: 3 6 9 12 4: 4 8 12 5: 5 10 Iterations: 25

(e) What is different about the two outputs? Explain why one line of code results in very similar but not identical output? Number of iterations in case of break is 22 and incase of continue is 25 outputs are similar but not identical because a) break will exit the loop b) continue will skip the statements following continue and move to next iteration.