Java Code Samples

6 Programming Instructions

Input

java-string-input-(get-name)

import java.util.Scanner;

public class SampleClass {
	public static void main(String[] args) {
		// Set variables
		String name, age_str;
		int age, weight;
		// Create a Scanner input object
		Scanner user_input = new Scanner(System.in);
		
		// Get user's name
		System.out.print("\nYour name: ");
		name = user_input.next();
		
		// Get user's age (using .next())
		System.out.print("\nYour age, please: ");
		age_str = user_input.next();
		
		// convert age from String to integer
		age = Integer.parseInt(age_str);
		
		// Get user's weight using .nextInt()
		System.out.print("\nHow much do you weigh? ");
		weight = user_input.nextInt(); 
		
		// Test the output:
		System.out.println("\nNice to meet you, " + name + ".");
		System.out.println("You are " + age + " years old.");
		System.out.println("In 5 years, you will be " + (age + 5) + 
				" years old.");
	}
}

Output

Math

sampleclass.java

public class SampleClass {

	public static void main(String[] args) {
		/* The Math class & some of its functions */
		System.out.println( "The absolute value of -128 is " + Math.abs(-128));
		System.out.println( "Between 27 and 25, " + Math.max(27, 25) +
				" is greater.");
		System.out.println( "Between 27 and 25, " + Math.min(27, 25) +
				" is lesser.");
		System.out.println( "\nPi as a double is: " + Math.PI);
		System.out.println( "3.5 rounded is : " + Math.round(3.5));
		System.out.println( "The square root of 42 is " + Math.sqrt(42));
		System.out.println( "The square root of 9 is " + (int) Math.sqrt(9));
	}
}

sampleclass.java

public class SampleClass {

	public static void main(String[] args) {

		// Random (note the differences in the output):
		double rand = Math.random();
		System.out.println( "\nMath chose " + rand + 
				" for it's random number.");
		System.out.println( "A random number between 0 and 9 is " + Math.random()*10);
		System.out.println( "A random integer between 1 and 10 is " + 
				(int) (Math.random()*10 + 1)); // Note the parentheses

	}
}