JAVA程序片段.doc_第1页
JAVA程序片段.doc_第2页
JAVA程序片段.doc_第3页
JAVA程序片段.doc_第4页
JAVA程序片段.doc_第5页
已阅读5页,还剩14页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

基本语法 / Addition program that displays the sum of two numbers. 3 import java.util.Scanner; / program uses class Scanner5 public class Addition 6 7 / main method begins execution of Java application 8 public static void main( String args ) 9 10 / create Scanner to obtain input from command window11 Scanner input = new Scanner( System.in ); 13 int number1; / first number to add 14 int number2; / second number to add 15 int sum; / sum of number1 and number217 System.out.print( Enter first integer: ); / prompt18 number1 = input.nextInt(); / read first number from user20 System.out.print( Enter second integer: ); / prompt21 number2 = input.nextInt(); / read second number from user23 sum = number1 + number2; / add numbers25 System.out.printf( Sum is %dn, sum ); / display sum27 / end method main29 / end class AdditionEnter first integer: 45Enter second integer: 72Sum is 117 public class GradeBook public void displayMessage() System.out.println( Welcome to the Grade Book! ); public class GradeBookTest public static void main( String args ) GradeBook myGradeBook = new GradeBook(); myGradeBook.displayMessage(); Welcome to the Grade Book! String nameOfCourse = input.nextLine(); / read a line of text depositAmount = input.nextDouble(); / obtain user input while ( input.hasNext() )58 59 grade = input.nextInt(); / read grade60 total += grade; / add grade to total61 +gradeCounter; / increment number of grades63 / call method to increment appropriate counter64 incrementLetterGradeCounter( grade );65 / end Figure 6.2. Math class methodsMethodDescriptionExampleabs( x )absolute value of xabs( 23.7 ) is 23.7abs( 0.0 ) is 0.0abs( -23.7 ) is 23.7 ceil( x )rounds x to the smallest integer not less than xceil( 9.2 ) is 10.0ceil( -9.8 ) is -9.0 cos( x )trigonometric cosine of x (x in radians)cos( 0.0 ) is 1.0 exp( x )exponential method exexp( 1.0 ) is 2.71828exp( 2.0 ) is 7.38906 floor( x )rounds x to the largest integer not greater than xfloor( 9.2 ) is 9.0floor( -9.8 ) is -10.0 log( x )natural logarithm of x (base e)log( Math.E ) is 1.0log( Math.E * Math.E ) is 2.0 max( x, y )larger value of x and ymax( 2.3, 12.7 ) is 12.7max( -2.3, -12.7 ) is -2.3min( x, y )smaller value of x and ymin( 2.3, 12.7 ) is 2.3min( -2.3, -12.7 ) is -12.7 pow( x, y )x raised to the power y (i.e., x y)pow( 2.0, 7.0 ) is 128.0pow( 9.0, 0.5 ) is 3.0 sin( x )trigonometric sine of x (x in radians)sin( 0.0 ) is 0.0sqrt( x )square root of xsqrt( 900.0 ) is 30.0 tan( x )trigonometric tangent of x (x in radians)tan( 0.0 ) is 0.0 / obtain user input14 System.out.print(15 Enter three floating-point values separated by spaces: );16 double number1 = input.nextDouble(); / read first double17 double number2 = input.nextDouble(); / read second double18 double number3 = input.nextDouble(); / read third doubleJava API packages (a subset).PackageDescriptionjava.appletThe Java Applet Package contains a class and several interfaces required to create Java appletsprograms that execute in Web browsers. (Applets are discussed in Chapter 20, Introduction to Java Applets; interfaces are discussed in Chapter 10, Object-Oriented Programming: Polymorphism.)java.awtThe Java Abstract Window Toolkit Package contains the classes and interfaces required to create and manipulate GUIs in Java 1.0 and 1.1. In current versions of Java, the Swing GUI components of the javax.swing packages are often used instead. (Some elements of the java.awt package are discussed in Chapter 11, GUI Components: Part 1, Chapter 12, Graphics and Java2D, and Chapter 22, GUI Components: Part 2.) java.awt.eventThe Java Abstract Window Toolkit Event Package contains classes and interfaces that enable event handling for GUI components in both the java.awt and javax.swing packages. (You will learn more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.) java.ioThe Java Input/Output Package contains classes and interfaces that enable programs to input and output data. (You will learn more about this package in Chapter 14, Files and Streams.) java.langThe Java Language Package contains classes and interfaces (discussed throughout this text) that are required by many Java programs. This package is imported by the compiler into all programs, so the programmer does not need to do so. The Java Networking Package contains classes and interfaces that enable programs to communicate via computer networks like the Internet. (You will learn more about this in Chapter 24, Networking.)java.textThe Java Text Package contains classes and interfaces that enable programs to manipulate numbers, dates, characters and strings. The package provides internationalization capabilities that enable a program to be customized to a specific locale (e.g., a program may display strings in different languages, based on the users country). java.utilThe Java Utilities Package contains utility classes and interfaces that enable such actions as date and time manipulations, random-number processing (class Random), the storing and processing of large amounts of data and the breaking of strings into smaller pieces called tokens (class StringTokenizer). (You will learn more about the features of this package in Chapter 19, Collections.) javax.swingThe Java Swing GUI Components Package contains classes and interfaces for Javas Swing GUI components that provide support for portable GUIs. (You will learn more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.) javax.swing.eventThe Java Swing Event Package contains classes and interfaces that enable event handling (e.g., responding to button clicks) for GUI components in package javax.swing. (You will learn more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.)2 / Shifted and scaled random integers. 3 import java.util.Random; / program uses class Random5 public class RandomIntegers 6 7 public static void main( String args ) 8 9 Random randomNumbers = new Random(); / random number generator10 int face; / stores each random integer generated12 / loop 20 times13 for ( int counter = 1; counter = 20; counter+ )14 15 / pick random integer from 1 to 6 16 face = 1 + randomNumbers.nextInt( 6 );18 System.out.printf( %d , face ); / display generated value20 / if counter is divisible by 5, start a new line of output21 if ( counter % 5 = 0 )22 System.out.println();23 / end for24 / end main25 / end class RandomIntegers掷骰子游戏import java.util.Random;5 public class Craps 6 7 / create random number generator for use in method rollDice 8 private Random randomNumbers = new Random();10 / enumeration with constants that represent the game status11 private enum Status CONTINUE, WON, LOST ; 13 / constants that represent common rolls of the dice14 private final static int SNAKE_EYES = 2;15 private final static int TREY = 3; 16 private final static int SEVEN = 7; 17 private final static int YO_LEVEN = 11; 18 private final static int BOX_CARS = 12; 20 / plays one game of craps21 public void play()22 23 int myPoint = 0; / point if no win or loss on first roll24 Status gameStatus; / can contain CONTINUE, WON or LOST26 int sumOfDice = rollDice(); / first roll of the dice28 / determine game status and point based on first roll29 switch ( sumOfDice )30 31 case SEVEN: / win with 7 on first roll 32 case YO_LEVEN: / win with 11 on first roll33 gameStatus = Status.WON;34 break;35 case SNAKE_EYES: / lose with 2 on first roll36 case TREY: / lose with 3 on first roll 37 case BOX_CARS: / lose with 12 on first roll 38 gameStatus = Status.LOST;39 break;40 default: / did not win or lose, so remember point41 gameStatus = Status.CONTINUE; / game is not over42 myPoint = sumOfDice; / remember the point 43 System.out.printf( Point is %dn, myPoint );44 break; / optional at end of switch45 / end switch47 / while game is not complete48 while ( gameStatus = Status.CONTINUE ) / not WON or LOST49 50 sumOfDice = rollDice(); / roll dice again52 / determine game status53 if ( sumOfDice = myPoint ) / win by making point54 gameStatus = Status.WON;55 else56 if ( sumOfDice = SEVEN ) / lose by rolling 7 before point57 gameStatus = Status.LOST;58 / end while60 / display won or lost message61 if ( gameStatus = Status.WON )62 System.out.println( Player wins );63 else64 System.out.println( Player loses );65 / end method play67 / roll dice, calculate sum and display results68 public int rollDice()69 70 / pick random die values71 int die1 = 1 + randomNumbers.nextInt( 6 ); / first die roll72 int die2 = 1 + randomNumbers.nextInt( 6 ); / second die roll74 int sum = die1 + die2; / sum of die values76 / display results of this roll77 System.out.printf( Player rolled %d + %d = %dn,78 die1, die2, sum );80 return sum; / return sum of dice81 / end method rollDice82 / end class Crapspublic class CrapsTest 5 6 public static void main( String args ) 7 8 Craps game = new Craps(); 9 game.play(); / play one game of craps10 / end main11 / end class CrapsTest数组:1.int array; / declare array named array array = new int 10 ; / create the space for array 2. int array = 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 ; 3. final int ARRAY_LENGTH = 10; / declare constant int array = new int ARRAY_LENGTH ; / create array / loop through rows of grades array for ( int studentGrades : grades ) / loop through columns of current row for ( int grade : studentGrades ) / if grade less than lowGrade, assign it to lowGrade if ( grade lowGrade ) lowGrade = grade; / end inner for / end outer for public static double average( double. numbers )2 / Using command-line arguments to initialize an array.4 public class InitArray 5 6 public static void main( String args ) 7 8 / check number of command-line arguments 9 if ( args.length != 3 )10 System.out.println(11 Error: Please re-enter the entire command, includingn +an array size, initial value and increment. );13 else14 15 / get array size from first command-line argument16 int arrayLength = Integer.parseInt( args 0 );17 int array = new int arrayLength ; / create array19 / get initial value and increment from command-line argument20 int initialValue = Integer.parseInt( args 1 );21 int increment = Integer.parseInt( args 2 ); 23 / calculate value for each array element 24 for ( int counter = 0; counter array.length; counter+ )25 array counter = initialValue + increment * counter; 27 System.out.printf( %s%8sn, Index, Value );29 / display array index and value30 for ( int counter = 0; counter array.length; counter+ )31 System.out.printf( %5d%8dn, counter, array counter );32 / end else33 / end main34 / end class InitArray public enum Book 6 7 / declare constants of enum type 8 JHTP6( Java How to Program 6e, 2005 ), 9 CHTP4( C How to Program 4e, 2004 ), 10 IW3HTP3( Internet & World Wide Web How to Program 3e, 2004 ),11 CPPHTP4( C+ How to Program 4e, 2003 ), 12 VBHTP2( Visual Basic .NET How to Program 2e, 2002 ), 13 CSHARPHTP( C# How to Program, 2002 ); 14 / Testing enum type Book. 3 import java.util.EnumSet;5 public class EnumTest 6 7 public static void main( String args ) 8 9 System.out.println( All books:n );11 / print all books in enum Book12 for ( Book book : Book.values() )13 System.out.printf( %-10s%-45s%sn, book,14 book.getTitle(), book.getCopyrightYear() );16 System.out.println( nDisplay a range of enum constants:n );18 / print first four books19 for ( Book book : EnumSet.range( Book.JHTP6, Book.CPPHTP4 ) )20 System.out.printf( %-10s%-45s%sn, book,21 book.getTitle(), book.getCopyrightYear() );22 / end main23 / end class EnumTestGUI/ Basic input with a dialog box. 3 import javax.swing.JOptionPane;5 public class NameDialog 6 7 public static void main( String args ) 8 9 / prompt user to enter name10 String name = 11 JOptionPane.showInputDialog( What is your name? );13 / create the message14 String message = 15 String.format( Welcome, %s, to Java Programming!, name );17 / display the message to welcome the user by name18 JOptionPane.showMessageDialog( null, message );19 / end main20 / end class NameDialog / Draws two crossing lines on a panel. 3 import java.awt.Graphics; 4 import javax.swing.JPanel;6 public class DrawPanel extends JPanel 7 8 / draws an X from the corners of the panel 9 public void paintComponent( Graphics g )10 11 / call paintComponent to ensure the panel displays correctly12 super.paintComponent( g );14 int width = getWidth(); / total width 15 int height = getHeight(); / total height17 / draw a line from the upper-left to the lower-right18 g.drawLine( 0, 0, width, height );20 / draw a line from the lower-left to the upper-right21 g.drawLine( 0, height, width, 0 );22 / end method paintComponent23 / end class DrawPanel / Application to display a DrawPanel. 3 import javax.swing.JFrame;5 public class DrawPanelTest 6 7 public static void main( String args ) 8 9 / create a panel that contains our drawing10 DrawPanel panel = new DrawPanel();12 / create a new frame to hold the panel13 JFrame application = new JFrame();15 / set the frame to exit when it is closedapplication.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );18 application.add( panel ); / add the panel to the frame 19 application.setSize( 250, 250 ); / set the size of the frame20 application.setVisible( true ); / make the frame visible 21 / end main22 / end class DrawPanelTest/ Test application that displays class Shapes. 3 import javax.swing.JFrame; 4 import javax.swing.JOptionPane; 5 6 public class ShapesTest 7 8 public static void main( String args ) 9 10 / obtain users choice11 String input = JOptionPane.showInputDialog(12 Enter 1 to draw rectanglesn +13 Enter 2 to draw ovals );15 int choice = Integer.parseInt( input ); / convert input to int17 / create the panel with the users input18 Shapes panel = new Shapes( choice );20 JFrame application = new JFrame(); / creates a new JFrameapplication.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );23 application.add( panel ); / add the panel to the frame24 application.setSize( 300, 300 ); / set the desired size25 application.setVisible( true ); / show the frame26 / end main27 / end class ShapesTest/ Demonstrates filled shapes.画笑脸 3 import java.awt.Color; 4 import java.awt.Graphics; 5 import javax.swing.JPanel;7 public class DrawSmiley extends JPanel 8 9 public void paintComponent( Graphics g )10 11 super.paintComponent( g );13 / draw the face14 g.setColor( Color.YELLOW ); 15 g.fillOval( 10, 10, 200, 200 );17 / draw the eyes18 g.setColor( Color.BLACK ); 19 g.fillOva

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论