basic java programming csci 392 week two. stuff that is the same as c++ for loops and while loops...
TRANSCRIPT
Basic Java Programming
CSCI 392
Week Two
Stuff that is the same as C++
for loops and while loopsfor (int i=0; i<10; i++)
if elseif (count != 10)
increment, decrement, etcresult *= factorial--;
switch statementsswitch (answer) { case 'y': case 'Y': some stuff break; default:}
Java Statements Not in C++
Labeling blocks of codeouterloop: for (int i=0;…) for (int j=0; … if (something_bad) break outerloop;
Exception Handlingtry { value = x/y; } catch (ArithmeticException exceptvar) { System.out.println("Math Error"); }
Basic Data Types
Boolean boolean - 1 bit
Integers byte - 8 bits short - 16 bits int - 32 bits long - 64 bits
Characters char - 16 bits
Floats float double
Strings String still be careful when comparing
Boolean - So what?
This C++ feature is not legal in Java:
int factorial, result = 1;. . .while (factorial) result *= factorial--;
But neither is this common C++ error:
if (count = 10) // not legal Java
Variable Declaration Oddities
You must initialize a variable before it can be used, so most declarations include an initialization.
You can set a "constant's" value at run time.final int count = getCount();
Arrays require both a definition and declaration. int[] myarray;myarray = new int[25];
int[] myarray = new int[25];
char[] name = {'B', 'o', 'b'};
Type Checking
You can assign small sized variables into bigger variables, but big variables don't fit into small variables.
int X = 99;
long Y = 0;
Y = X; // legal
X = Y; // not legal
X = (int) Y; // legal
Comments
Just like C/* multi-line */
// single line
Except…/** document comment **/ not thrown away by compiler
Simple Output
Printing to "Standard Output"System.out.print ("Hello " + name );
System.out.println ();
Formatted OutputNumberFormat layout = NumberFormat.getNumberInstance();layout.setMaximumFractionDigits(4); double x = 12.3, y = 45.6;String outstr = layout.format(x/y);System.out.println("x/y = " + outstr);
Input - not so simple
import java.io.* ;
public class array_test_1 { public static void main(String[] args) throws Exception { InputStreamReader stdio = new InputStreamReader(System.in); BufferedReader instream = new BufferedReader (stdio); int count;
System.out.print ("Enter an integer: "); String indata = instream.readLine(); count = Integer.parseInt (indata); for (int i=0; i<count; i++) System.out.print (i + " "); System.out.println(); }}
improvement: catch the NumberFormatException