Java Code Examples for java.util.Scanner#nextDouble()

The following examples show how to use java.util.Scanner#nextDouble() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PresentValue.java    From levelup-java-exercises with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

		// Scanner object to get input
		Scanner keyboard = new Scanner(System.in);

		// Desired future value
		System.out.print("Future value? ");
		double futureValue = keyboard.nextDouble();

		// Annual interest rate.
		System.out.print("Annual interest rate? ");
		double annualInterestRate = keyboard.nextDouble();

		// Number of years investment to draw interest
		System.out.print("Number of years? ");
		int numberOfYears = keyboard.nextInt();

		// close scanner
		keyboard.close();

		double present = calculatePresentValue(futureValue, annualInterestRate,
				numberOfYears);

		// Display the result to user
		System.out.println("You need to invest $" + present);
	}
 
Example 2
Source File: CheckPanel.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
private double valueOf (String text)
{
    Scanner scanner = new Scanner(text);
    scanner.useLocale(Locale.US);

    while (scanner.hasNext()) {
        if (scanner.hasNextDouble()) {
            return scanner.nextDouble();
        } else {
            scanner.next();
        }
    }

    // Kludge!
    return Double.NaN;
}
 
Example 3
Source File: Exercise_02_03.java    From Intro-to-Java-Programming with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	// Create a Scanner object
	Scanner input = new Scanner(System.in);

	// Create constant value
	final double METERS_PER_FOOT = 0.305;

	// Prompt user to enter a number in feet
	System.out.print("Enter a value for feet: ");
	double feet = input.nextDouble();

	// Convert feet into meters
	double meters = feet * METERS_PER_FOOT;

	// Display results
	System.out.println(feet + " feet is " + meters + " meters");
}
 
Example 4
Source File: Exercise_02_17.java    From Intro-to-Java-Programming with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);

	// Prompt the user to enter a temperature between -58F and 
	// 41F and a wind speed greater than or equal to 2.
	System.out.print("Enter the temperature in Fahrenheit " +
		"between -58ºF and 41ºF: ");
	double temperature = input.nextDouble();
	System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
	double speed = input.nextDouble();

	// Compute the wind chill index
	double windChill = 35.74 + 0.6215 * temperature -
							 35.75 * Math.pow(speed, 0.16) +
							 0.4275 * temperature * Math.pow(speed, 0.16);

	// Display result
	System.out.println("The wind chill index is " + windChill);
}
 
Example 5
Source File: Exercise_02_15.java    From Intro-to-Java-Programming with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);

	// Prompt the user to enter two points
	System.out.print("Enter x1 and y1: ");
	double x1 = input.nextDouble();
	double y1 = input.nextDouble();
	System.out.print("Enter x2 and y2: ");
	double x2 = input.nextDouble();
	double y2 = input.nextDouble();

	// Calucate the distance between the two points
	double distance = Math.pow(Math.pow(x2 - x1, 2) +
							Math.pow(y2 - y1, 2), 0.5);

	// Display result
	System.out.println("The distance between the two points is " + distance);
}
 
Example 6
Source File: Pearson_Correlation_Coefficient_I.java    From HackerRank-solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    /* Save input */
    Scanner scan = new Scanner(System.in);
    int size = scan.nextInt();
    double [] xs = new double[size];
    double [] ys = new double[size];
    for (int i = 0; i < size; i++) {
        xs[i] = scan.nextDouble();
    }
    for (int i = 0; i < size; i++) {
        ys[i] = scan.nextDouble();
    }
    scan.close();
    
    System.out.println(pearson(xs, ys));
}
 
Example 7
Source File: Validate.java    From ThinkJavaCode with MIT License 6 votes vote down vote up
public static double scanDouble() {
    Scanner in = new Scanner(System.in);
    boolean okay;
    do {
        System.out.print("Enter a number: ");
        if (in.hasNextDouble()) {
            okay = true;
        } else {
            okay = false;
            String word = in.next();
            System.err.println(word + " is not a number");
        }
    } while (!okay);
    double x = in.nextDouble();
    return x;
}
 
Example 8
Source File: Exercise_03_23.java    From Intro-to-Java-Programming with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);

	// Prompt the user to enter a point (x, y)
	System.out.print("Enter a point with two coordinates: ");
	double x = input.nextDouble();
	double y = input.nextDouble();

	// Check whether the point is within the rectangle
	// centered at (0, 0) with width 10 and height 5
	boolean withinRectangle = (Math.pow(Math.pow(x, 2), 0.5) <= 10 / 2 ) ||
									  (Math.pow(Math.pow(y, 2), 0.5) <= 5.0 / 2);

	// Display results
	System.out.println("Point (" + x + ", " + y + ") is " +
		((withinRectangle) ? "in " : "not in ") + "the rectangle");
}
 
Example 9
Source File: Exercise_05_31.java    From Intro-to-Java-Programming with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	// Create a Scanner
	Scanner input = new Scanner(System.in);

	// Prompt the user to enter an amout, the 
	// annual percentage yield and the number of months 
	System.out.print("Enter the initial deposit amount: ");
	double amount = input.nextDouble();
	System.out.print("Enter annual percentage yield: ");
	double percentageYield = input.nextDouble();
	System.out.print("Enter maturity period (number of months): ");
	int months = input.nextInt();

	// Display header
	System.out.println("Month  CD Value");
	// Compute and display CD worth for the number of months
	for (int m = 1; m <= months; m++) {
		amount += amount * (percentageYield / 1200);
		System.out.printf("%-7d%.2f\n", m, amount);
	}
}
 
Example 10
Source File: SpeedOfSound.java    From levelup-java-exercises with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

		double distance = 0.0; // Distance
		String medium; // To hold "air", "water", or "steel"
		
		// Create a Scanner object for keyboard input.
		Scanner keyboard = new Scanner(System.in);

		// Get the user's medium of choice.
		System.out.print("Enter one of the following: air, water, or steel: ");
		medium = keyboard.nextLine();

		// Get the distance.
        System.out.print("Enter the distance the sound wave will travel: ");
        distance = keyboard.nextDouble();
        
        // calculate 
        double distanceTravelled = getDistanceTraveledInSeconds(medium, distance);
        
        // display output
        System.out.println("It will take " + distanceTravelled + " seconds.");
		
        keyboard.close();
	}
 
Example 11
Source File: Solution.java    From HackerRank with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    double d = sc.nextDouble(); 
    sc.nextLine(); 
    String s = sc.nextLine();

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}
 
Example 12
Source File: FahrenheitToCelsius.java    From BUPTJava with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  Scanner input = new Scanner(System.in);

  System.out.print("Enter a degree in Fahrenheit: ");
  double fahrenheit = input.nextDouble(); 

  // Convert Fahrenheit to Celsius
  double celsius = (5.0 / 9) * (fahrenheit - 32);
  System.out.println("Fahrenheit " + fahrenheit + " is " + 
    celsius + " in Celsius");  
}
 
Example 13
Source File: Exercise_03_28.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);	// Create Scanner object

	// Prompt the user to enter the center x, y coorginates,
	// width, and height of two rectangles
	System.out.print("Enter r1's center x-, y-coordinates, width and height: ");
	double r1x = input.nextDouble();
	double r1y = input.nextDouble();
	double r1Width = input.nextDouble();
	double r1Height = input.nextDouble();
	System.out.print("Enter r2's center x-, y-coordinates, width and height: ");
	double r2x = input.nextDouble();
	double r2y = input.nextDouble();
	double r2Width = input.nextDouble();
	double r2Height = input.nextDouble();

	// Determine whether the second rectangle is inside the first
	if	((Math.pow(Math.pow(r2y - r1y, 2), .05) + r2Height / 2 <= r1Height / 2) && 
		(Math.pow(Math.pow(r2x - r1x, 2), .05) + r2Width / 2 <= r1Width / 2) &&
		(r1Height / 2 + r2Height / 2 <= r1Height) &&
		(r1Width / 2 + r2Width / 2 <= r1Width))
		System.out.println("r2 is inside r1");
	else if ((r1x + r1Width / 2 > r2x - r2Width) ||
				(r1y + r1Height / 2 > r2y - r2Height))
		System.out.println("r2 overlaps r1");
	else
		System.out.println("r2 does not overlap r1");
}
 
Example 14
Source File: Validate.java    From ThinkJavaCode with MIT License 5 votes vote down vote up
public static double scanDouble2() {
    Scanner in = new Scanner(System.in);
    while (true) {
        System.out.print("Enter a number: ");
        if (in.hasNextDouble()) {
            break;
        }
        String word = in.next();
        System.err.println(word + " is not a number");
    }
    double x = in.nextDouble();
    return x;
}
 
Example 15
Source File: Exercise_06_36.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
/** Main Method */
public static void main(String[] args) {
	Scanner input = new Scanner(System.in); // Create a Scanner

	// Prompt the user to enter the number of sides 
	// and the side of a regular polygon
	System.out.print("Enter the number of sides: ");
	int n = input.nextInt();
	System.out.print("Enter the side: ");
	double side = input.nextDouble();

	// Display the area of the regular polygon
	System.out.println("The area of the polygon is " + area(n, side));

}
 
Example 16
Source File: Solution.java    From HackerRank-Solutions with The Unlicense 5 votes vote down vote up
public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int m = scan.nextInt();
        int n = scan.nextInt();

        double [][] X = new double[n][m + 1];
        double [][] Y   = new double[n][1];

        for (int row = 0; row < n; row++) {
            X[row][0] = 1;
            for (int col = 1; col <= m; col++) {
                X[row][col] = scan.nextDouble();
            }
            Y[row][0] = scan.nextDouble();
        }

        /* Calculating B */
        double [][] xtx    = multiply(transpose(X),X);
        double [][] xtxInv = invert(xtx);
        double [][] xty    = multiply(transpose(X), Y);
        double [][] B      = multiply(xtxInv, xty);

        int sizeB = B.length;

        /* Calculating values for "q" feature sets */
        int q = scan.nextInt();
        for (int i = 0; i < q; i++) {
            double result = B[0][0];
            for (int row = 1; row < sizeB; row++) {
                result += scan.nextDouble() * B[row][0];
            }
            System.out.println(result);
        }

        scan.close();
    }
 
Example 17
Source File: Exercise_08_12.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	// Create a Scanner
	Scanner input = new Scanner(System.in);

	// Tax rates
	double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35};

	// The brackets for each rate for all the filing statuses
	int[][] brackets = {
		{8350, 33950, 82250, 171550, 372950},  // Single filer
		{16700, 67900, 137050, 20885, 372950}, // Married jointly
															// -or qualifying widow(er)
		{8350, 33950, 68525, 104425, 186475},  // Married separately
		{11950, 45500, 117450, 190200, 372950} // Head of household
	};
		
	// Prompt the user to enter filing status
	System.out.print("(0-single filer, 1-married jointly or " +
		"qualifying widow(er), 2-married separately, 3-head of " +
		"household) Enter the filing status: ");
	int status = getStatus();

	// Prompt the user to enter taxable income
	System.out.print("Enter the taxable income: ");
	double income = input.nextDouble();


	// Display the result
	System.out.printf("Tax is $%6.2f\n", 
		computeTax(brackets, rates, status, income)); 
}
 
Example 18
Source File: SavingsAccountClass.java    From levelup-java-exercises with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {

		// Create a Scanner object for keyboard input.
		Scanner keyboard = new Scanner(System.in);

		// Ask user to enter starting balance
		System.out.print("How much money is in the account?: ");
		double startingBalance = keyboard.nextDouble();

		// Ask user for annual interest rate
		System.out.print("Enter the annual interest rate:");
		double annualInterestRate = keyboard.nextDouble();

		// Create class
		SavingsAccountClass savingAccountClass = new SavingsAccountClass();
		SavingsAccount savingsAccount = savingAccountClass.new SavingsAccount(
				startingBalance, annualInterestRate);

		// Ask how long account was opened
		System.out.print("How long has the account been opened? ");
		double months = keyboard.nextInt();

		double montlyDeposit;
		double monthlyWithdrawl;
		double interestEarned = 0.0;
		double totalDeposits = 0;
		double totalWithdrawn = 0;

		// For each month as user to enter information
		for (int i = 1; i <= months; i++) {

			// Get deposits for month
			System.out.print("Enter amount deposited for month: " + i + ": ");
			montlyDeposit = keyboard.nextDouble();
			totalDeposits += montlyDeposit;

			// Add deposits savings account
			savingsAccount.deposit(montlyDeposit);

			// Get withdrawals for month
			System.out.print("Enter amount withdrawn for " + i + ": ");
			monthlyWithdrawl = keyboard.nextDouble();
			totalWithdrawn += monthlyWithdrawl;

			// Subtract the withdrawals
			savingsAccount.withdraw(monthlyWithdrawl);

			// Add the monthly interest
			savingsAccount.addInterest();

			// Accumulate the amount of interest earned.
			interestEarned += savingsAccount.getLastAmountOfInterestEarned();
		}

		// close keyboard
		keyboard.close();

		// Create a DecimalFormat object for formatting output.
		DecimalFormat dollar = new DecimalFormat("#,##0.00");

		// Display the totals and the balance.
		System.out.println("Total deposited: $" + dollar.format(totalDeposits));
		System.out
				.println("Total withdrawn: $" + dollar.format(totalWithdrawn));
		System.out
				.println("Interest earned: $" + dollar.format(interestEarned));
		System.out.println("Ending balance: $"
				+ dollar.format(savingsAccount.getAccountBalance()));
	}
 
Example 19
Source File: Calculator.java    From Java-9-Cookbook with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception{
	Scanner reader = new Scanner(System.in);
	Integer choice = 0 ;
	do{
		Command command = null;
		choice = acceptChoice(reader);
		switch(choice){
			case 1:
				System.out.println("Enter the number");
				command = new PrimeCheckCommand(reader.nextInt());
			break;
			case 2:
				System.out.println("Enter the number");
				command = new EvenCheckCommand(reader.nextInt());
			break;
			case 3:
				System.out.println("How many primes?");
				command = new SumPrimesCommand(reader.nextInt());
			break;
			case 4:
				System.out.println("How many evens?");
				command = new SumEvensCommand(reader.nextInt());
			break;
			case 5: 
				System.out.println("How many odds?");
				command = new SumOddsCommand(reader.nextInt());
			break;
			case 6:
				System.out.println("Enter principal, rate and number of years");
				command = new SimpleInterestCommand(reader.nextDouble(), 
					reader.nextInt(), reader.nextInt());
			break;
			case 7:
				System.out.println("Enter principal, rate, number of compunds per year " + 
					"and number of years");
				command = new CompoundInterestCommand(reader.nextDouble(), 
					reader.nextInt(), reader.nextInt(), reader.nextInt());
			break;
		}
		if ( command != null ){
			command.execute();
		}
	}while(choice < 8 && choice > 0);
}
 
Example 20
Source File: CalculationsForGraphingCalculator.java    From Mathematics with MIT License 3 votes vote down vote up
public static void main(String[] args) {

		System.out.println(
				"Welcome to the data points calculator! This program creates a table of values based on a given formula.");
		System.out.println();
		System.out.print("Please insert your equation in terms of x. Separate each term with a space (Ex: x^2 + 2*x + 3   You MUST include all signs (2x should be 2*x)): y = ");

		Scanner scan = new Scanner(System.in);
		String formula = scan.nextLine();
		String revisedFormula = formula;
		
		System.out.println();

		System.out.print("Left bound of your domain? ");
		double leftBound = scan.nextDouble();

		System.out.println();

		System.out.print("Right bound of your domain? ");
		double rightBound = scan.nextDouble();

		System.out.println();

		System.out.print("Step of your function (the increments at which the function is evaluated at: ");
		double step = scan.nextDouble();

		System.out.println("     x     " + "          y");
		System.out.println("_____________________________");
		
		for (double i = leftBound; i <= rightBound; i += step) {

			String input = Double.toString(i);
			revisedFormula = formula.replaceAll("x", input);
			System.out.println(input + "     |     " + eval(revisedFormula));
			
		}
		
		scan.close();

	}