Skip to content

mnishiguchi/java_practice_code

Repository files navigation

java_practice_code

Primitive data types

Assignment to float

// incompatible types: possible lossy conversion from double to float
float length = 34.0;  // NG

float length = 34.0f; // Good
float length = 34;    // Good
float length = -34;   // Good

double length = 34.0  // Good

Type casting

==

Modulo

  • Be careful when dealing with negative numbers!
System.out.println(" -24 % -5 = " +  -24 % -5);  // -24 % -5 = -4

==

Number format

// Create a DecimalFormat object to format output.    
DecimalFormat dollar = new DecimalFormat("#,##0.00");
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat( pattern );
double number = 123456789.123;

String formatted = decimalFormat.format( number );
System.out.println( formatted );

==

Precedence

==

Misc ideas

    private static void drawSeparator() {
        System.out.println();  // Insert a new line
        for (int i = 0; i < 48; i++) {
            System.out.print("~");
        }
        System.out.println();  // Insert a new line
    }
    /**
     * Prompts the user for a double data.
     * @param A Scanner object.
     * @param A message for the prompt.
     * @return data of double type.
     */
    public static double propmtUserDouble(Scanner sc, String msg) {

        double data;

        // Print the prompt message.
        System.out.print(msg);

        // Validate the input.
        while (!sc.hasNextDouble()) {
            System.out.println("  Invalid input. Try again.");
            System.out.print("  >>> ");
            sc.next();  // Clear the input stream
        }

        // Read the input.
        data = sc.nextDouble();

        return data;
    }

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages