Download presentation
Presentation is loading. Please wait.
Published byWilla Sullivan Modified over 6 years ago
1
Java Coding Extra David Davenport Computer Eng. Dept.,
Misc bits ‘n pieces Last updated: 17/11/2016 ~ added slide for Character methods, added left align to printf Previously: 26/10/2016 Includes: printf int/int division overflow/underflow type casting round/truncate Math class methods ?String class methods? ? Move Data Types from JavaCoding to here too? David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
2
IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.
3
Another sort of output…
The Java printf statement System.out.printf( formatString, listOfValues); where formatString ~ String with embedded formatSpecifiers listOfValues ~ comma-separated list of values that replace formatSpecifiers in formatString “d” is for decimal integer! (use o for octal & x for hexadecimal) “e” forces exponential form of float. formatSpecifiers Can specify field width &/or no of dp’s %d ~integer %s ~ string %f ~ real %3d ~integer %5s ~ string %10f ~ real %10.2f ~ real use %n for newline!
4
printf examples… System.out.printf( “Welcome to Java”);
System.out.printf( “Radius is %d”, radius); System.out.printf( “The area of a circle of ” “radius %d is %f %n” “and the circumference is %f”, radius, area, circumference); System.out.printf( “Hello %s.”, username); System.out.printf( “%-8”, count); Note: need %% to output a ‘%’ character! %n is newline! ( OS independent ~ uses system line separator) Also has Date, time, etc. For full format String syntax & options, see: Note: Two versions, one with, one without, Locale: public PrintStream printf( String format, Object... args) public PrintStream printf( Locale l, String format, Object... args) Use “-” for left alignment within specified field width (default is right alignment)
5
Math methods (≡ functions)
Math.abs(x) ~ returns absolute value of x Math.sqrt( x) ~ returns square root x Math.min( x, y) ~ returns minimum of x or y Math.max( x, y) ~ returns maximum of x & y Math.sin(x), Math.cos(x), Math.tan(x) … Math.toRadians(x) Math.toDegrees(x) Math.round(x) ~ returns integer Math.random() ~ returns real btw 0.0 & < 1.0! Lots of other methods… see documentation! Most of the Math class methods have multiple overloaded versions so they work with integer and real types, returning the appropriate type. Constants… Math.PI Math.E
6
caution: In Java, Strings are special non-primitive types!
String methods s1.equals( s2) ~ boolean s1.compareTo(s2) ~ int (so need to compare result with 0) s.length() ~ returns number char’s in s s.charAt(i) ~ returns char at index i in s (first character has index 0) s.substring( start, end) ~ returns String with char’s of s from start to end-1 s.toUpperCase() ~ returns String with all capitals s.toLowerCase() ~ returns String with all lowercase Note the different way of calling String methods (using String variable rather than class name!) other (static) methods? eg. int parseInt( s) ?in String or Integer? caution: In Java, Strings are special non-primitive types!
7
see Java API documentation for more details!
Character methods The following static methods take character, ch, (as either a char or int) and return boolean… Character.isDigit( ch) Character.isLetter( ch) Character.isSpaceChar( ch) Character.isLowerCase( ch) Character.isUpperCase( ch) Use String methods to convert to uppercase/lowercase Use these methods rather than the old-fashioned ASCII comparisions, such as (ch >= ‘0’ && ch <= ‘9’) Characters are still quite complicated & messy in Java. (char’s use the Unicode standard, but it is by no means straightforward). The primitive char type can be put into int and vice versa with typecast! See the Java documentation… see Java API documentation for more details!
8
Numeric odds ‘n ends… Assuming: int i; & double d;
d = i; // ok, i = d; // not ok! i = (int) d; // typecast, truncates! i = (int) Math.round(d); // rounds Numeric overflow & underflow… Integer.MAX_VALUE // ?? i = * ; All int values can be represented as doubles but reverse not true, decimal part would be lost! so compiler stops you doing something silly By typecasting, you (the programmer) take responsibility!
9
Numeric odds ‘n ends… expression result type gotcha…
real if one or both operands are real integer if both operands are integer gotcha… 5 / 2 2 (not 2.5!) 5.0 / 2 2.5 i = 5 / 2; // gives 2 d = 5 / 2; // gives 2.0, not 2.5! d = (double) 5 / 2; // gives 2.5
10
Named constants… (1) Defining memory locations as constants
final double PI = 3.142; final int STANDARD_TAXRATE = 20; ensures they cannot be changed, eg. PI = 2.5; // won’t compile! makes for clearer code… circumference = * radius; circumference = 2 * * radius; circumference = 2 * PI * radius;
11
Or simply change the constant value and recompile each time!
Named constants (2) and simple reliable changes… (just edit & recompile) final int STANDARD_TAXRATE = 25; even if values used in multiple places… Without risk of affecting other identical values! Global search & replace just doesn’t cut it! Or simply change the constant value and recompile each time! x = 2 * 6 + 1; y = x / 2; z = x + y + 6; x = 2 * 2 + 1; y = x / 2; z = x + y + 2; x = 2 * 5 + 1; y = x / 2; z = x + y + 5; final int FIXIT = 5; x = 2 * FIXIT + 1; y = x / 2; z = x + y + FIXIT; search & replace 5 with 6 then 6 with 2 then 2 back to 5… oops!
12
Escape sequences… String literals are enclosed in quotes
System.out.println( “…..” ); s = “…..”; But what if text includes quotes? s = “David said “hi” to the class”; Solution use special character sequence… s = “David said \“hi\” to the class”; Useful escape sequences Note: “\n” probably does not output OS dependant eoln MS-Windows \r\n Unix \n Mac (old?) \r Java can auto change output based on OS and language of machine being used. History: The terms CR-LF (\r\n) come from old typewriter days… the paper was mounted on a carriage which moved across page to next position after each key was pressed. At the end of the line, the typist had to return the carriage to the start of the line and rotate it to move down to the next line. Hence carriage-return and line-feed. Tab is for tab-stop / tabular, for arranging information into columns. \” ” \\ \ \t tab \n new line? \r return
13
Using Scanner for input…
Gotchas… Reading nextLine after numeric input No nextChar(), use… Char ch = scan.nextLine().charAt(0); testing for correct input type… if ( !scan.hasNextInt() ) System.out.println(“Error: not an integer!”); else i = scan.nextInt(); Turkish/English input… (using comma vs. decimal point)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.