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

The following examples show how to use java.util.Scanner#hasNextDouble() . 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: 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 2
Source File: AirMapPolygon.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
public AirMapPolygon(String polygonGeometry) {
    if (!polygonGeometry.toUpperCase().startsWith("POLYGON")) {
        throw new IllegalArgumentException("Illegal linestring");
    }
    List<Coordinate> coordinates = new ArrayList<>();
    int startIndex = polygonGeometry.indexOf('('); //This is where the coordinates will start
    int endIndex = polygonGeometry.indexOf(')');
    Scanner in = new Scanner(polygonGeometry.substring(startIndex, endIndex));
    while (in.hasNextDouble()) {
        double lat = in.nextDouble();
        if (in.hasNextDouble()) {
            double lng = in.nextDouble();
            coordinates.add(new Coordinate(lat, lng));
        }
    }
    in.close();
    setCoordinates(coordinates);
}
 
Example 3
Source File: AirMapPath.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
public AirMapPath(String lineString) {
    if (!lineString.toUpperCase().startsWith("LINESTRING")) {
        throw new IllegalArgumentException("Illegal linestring");
    }
    List<Coordinate> coordinates = new ArrayList<>();
    int startIndex = lineString.indexOf('('); //This is where the coordinates will start
    int endIndex = lineString.indexOf(')');
    Scanner in = new Scanner(lineString.substring(startIndex, endIndex));
    while (in.hasNextDouble()) {
        double lat = in.nextDouble();
        if (in.hasNextDouble()) {
            double lng = in.nextDouble();
            coordinates.add(new Coordinate(lat, lng));
        }
    }
    in.close();
    setCoordinates(coordinates);
}
 
Example 4
Source File: CheckPanel.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
private double valueOf (String text)
{
    Scanner scanner = new Scanner(text);
    scanner.useLocale(Locale.getDefault());

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

    // Kludge!
    return Double.NaN;
}
 
Example 5
Source File: Main.java    From Particle-Swarm-Optimization with MIT License 6 votes vote down vote up
private static double getUserDouble (String msg) {
    double input;
    while (true) {
        Scanner sc = new Scanner(System.in);
        System.out.print(msg);

        if (sc.hasNextDouble()) {
            input = sc.nextDouble();

            if (input <= 0) {
                System.out.println("Number must be positive.");
            } else {
                break;
            }

        } else {
            System.out.println("Invalid input.");
        }
    }
    return input;
}
 
Example 6
Source File: App.java    From public with Apache License 2.0 5 votes vote down vote up
public static List<Double> loadFromFile(String filepath) throws FileNotFoundException {
    File file = new File(filepath);
    Scanner scanner = new Scanner(file);
    List<Double> numbers = new ArrayList<>();
    while (scanner.hasNextDouble()) {
        double number = scanner.nextDouble();
        numbers.add(number);
    }
    scanner.close();
    return numbers;
}
 
Example 7
Source File: Logarithm.java    From ThinkJavaCode with MIT License 5 votes vote down vote up
public static void scanDouble2(Scanner in) {
    System.out.print("Enter a number: ");
    if (!in.hasNextDouble()) {
        String word = in.next();
        System.err.println(word + " is not a number");
        return;
    }
    double x = in.nextDouble();
    printLogarithm(x);
}
 
Example 8
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 9
Source File: AirMapPoint.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
public AirMapPoint(String pointString) {
    int startIndex = pointString.indexOf('('); //This is where the coordinates will start
    int endIndex = pointString.indexOf(')');
    Scanner in = new Scanner(pointString.substring(startIndex, endIndex));
    if (in.hasNextDouble()) {
        double lat = in.nextDouble();
        if (in.hasNextDouble()) {
            double lng = in.nextDouble();
            setCoordinate(new Coordinate(lat, lng));
        }
    }
    in.close();
}
 
Example 10
Source File: Variable.java    From JOpenShowVar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
     * Parses a string encoded KRL variable to a JOpenShowVar Variable
     *
     * @param callback the Callback from the robot
     * @return the JOpenShowVar Variable
     * @throws NumberFormatException on parsing error
     */
    public static Variable parseVariable(Callback callback) throws NumberFormatException {
        String variable = callback.getVariableName();
        String value = callback.getStringValue();
        int id = callback.getId();
        long readTime = callback.getReadTime();
//        int option = callback.getOption();

        Scanner sc = new Scanner(value);
        Variable var;
        if (sc.hasNextInt()) {
            var = new Int(id, variable, sc.nextInt(), readTime);
            sc.close();
        } else if (sc.hasNextFloat()) {
            var = new Real(id, variable, (double) sc.nextFloat(), readTime);
            sc.close();
        } else if (sc.hasNextDouble()) {
            var = new Real(id, variable, sc.nextDouble(), readTime);
            sc.close();
        } else if (sc.hasNextBoolean()) {
            var = new Bool(id, variable, sc.nextBoolean(), readTime);
            sc.close();
        }else if (value.contains("#")) {
            var = new Enum(id, variable, sc.nextLine(), readTime);
            sc.close();
        } else if (value.contains("{")) {
            sc.close();
            var = new Struct(id, variable, Struct.parseString(value), readTime);
        } else {
            var = new Real(id, variable, Double.parseDouble(value), readTime);
            sc.close();
        }
        return var;
    }
 
Example 11
Source File: ReverseRoot_1001.java    From AlgoCS with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    int i = 0, t = 0;
    double a[] = new double[999999];
    Scanner x = new Scanner(System.in);
    a[i++] = Math.sqrt(x.nextDouble());
    t++;
    while (x.hasNextDouble()) {
        double d = x.nextDouble();
        a[i++] = Math.sqrt(d);
        t++;
    }
    for (int j = t - 1; j >= 0; j--) {
        System.out.printf("%.4f\n", a[j]);
    }
}
 
Example 12
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
private static double getFirst(Scanner scanner) {
    if (scanner.hasNextDouble()) {
        return scanner.nextDouble();
    }

    return Double.NaN;
}
 
Example 13
Source File: ScannerDemo.java    From JavaCommon with Apache License 2.0 5 votes vote down vote up
public static void scannerDemo2() {
	Scanner scan = new Scanner(System.in);

	double sum = 0;
	int m = 0;
	System.out.println("输入数字求平均,输入非数字结束!");
	while (scan.hasNextDouble()) {
		double x = scan.nextDouble();
		m = m + 1;
		sum = sum + x;
	}

	System.out.println(m + "个数的和为" + sum);
	System.out.println(m + "个数的平均值是" + (sum / m));
}
 
Example 14
Source File: SchemaBuilder.java    From db with GNU Affero General Public License v3.0 5 votes vote down vote up
public Object interpret(Object val) throws IllegalArgumentException {
    String s = val.toString();
    Scanner sc = new Scanner(s);

    return sc.hasNextInt() ? sc.nextInt()
            : sc.hasNextLong() ? sc.nextLong()
            : sc.hasNextDouble() ? sc.nextDouble()
            : sc.hasNextBoolean() ? sc.nextBoolean()
            : sc.hasNextBigInteger() ? sc.nextBigInteger()
            : sc.hasNextFloat() ? sc.nextFloat()
            : sc.hasNextByte() ? sc.nextByte()
            : sc.hasNext() ? sc.next()
            : s;
}
 
Example 15
Source File: DataCubeDimension.java    From db with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param val
 * @return
 * @throws IllegalArgumentException
 */
public Object interpret(Object val) throws IllegalArgumentException {
    String s = val.toString();
    Scanner sc = new Scanner(s);
    return sc.hasNextLong() ? sc.nextLong()
            : sc.hasNextInt() ? sc.nextInt()
            : sc.hasNextDouble() ? sc.nextDouble()
            : sc.hasNextBoolean() ? sc.nextBoolean()
            : sc.hasNextBigInteger() ? sc.nextBigInteger()
            : sc.hasNextFloat() ? sc.nextFloat()
            : sc.hasNextByte() ? sc.nextByte()
            : sc.hasNext() ? sc.next()
            : s;
}
 
Example 16
Source File: NumberUtils.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parse a double with a default value.
 *
 * @param str string to parse
 * @param def default double value
 * @return parsed double
 */
public static Double parseDouble(String str, Double def) {
    if (str == null) {
        return def;
    }
    Scanner scnr = new Scanner(str);
    if (!scnr.hasNextDouble()) {
        return def;
    }
    return scnr.nextDouble();
}
 
Example 17
Source File: NumberUtils.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param str string to check
 * @return whether the string is a double value
 */
public static boolean isDouble(String str) {
    if (str == null) {
        return false;
    }
    Scanner s = new Scanner(str.trim());
    if (!s.hasNextDouble()) {
        return false;
    }
    s.nextDouble();
    return !s.hasNext();
}
 
Example 18
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
private static double sumAll(Scanner scanner) {

        double sum = 0.0d;
        while (scanner.hasNextDouble()) {
            sum += scanner.nextDouble();
        }

        return sum;
    }
 
Example 19
Source File: AvroRecordConverter.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Converts the data from one schema to another. If the types are the same,
 * no change will be made, but simple conversions will be attempted for
 * other types.
 *
 * @param content
 *            The data to convert, generally taken from a field in an input
 *            Record.
 * @param inputSchema
 *            The schema of the content object
 * @param outputSchema
 *            The schema to convert to.
 * @return The content object, converted to the output schema.
 * @throws AvroConversionException
 *             When conversion is impossible, either because the output type
 *             is not supported or because numeric data failed to parse.
 */
private Object convertData(Object content, Schema inputSchema,
        Schema outputSchema) throws AvroConversionException {
    if (content == null) {
        // No conversion can happen here.
        if (supportsNull(outputSchema)) {
            return null;
        }
        throw new AvroConversionException("Output schema " + outputSchema
                + " does not support null");
    }

    Schema nonNillInput = getNonNullSchema(inputSchema);
    Schema nonNillOutput = getNonNullSchema(outputSchema);
    if (nonNillInput.getType().equals(nonNillOutput.getType())) {
        return content;
    } else {
        if (nonNillOutput.getType() == Schema.Type.STRING) {
            return content.toString();
        }

        // For the non-string cases of these, we will try to convert through
        // string using Scanner to validate types. This means we could
        // return questionable results when a String starts with a number
        // but then contains other content
        Scanner scanner = new Scanner(content.toString());
        scanner.useLocale(locale);
        switch (nonNillOutput.getType()) {
        case LONG:
            if (scanner.hasNextLong()) {
                return scanner.nextLong();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to long");
            }
        case INT:
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to int");
            }
        case DOUBLE:
            if (scanner.hasNextDouble()) {
                return scanner.nextDouble();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to double");
            }
        case FLOAT:
            if (scanner.hasNextFloat()) {
                return scanner.nextFloat();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to float");
            }
        default:
            throw new AvroConversionException("Cannot convert to type "
                    + nonNillOutput.getType());
        }
    }
}
 
Example 20
Source File: AvroRecordConverter.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Converts the data from one schema to another. If the types are the same,
 * no change will be made, but simple conversions will be attempted for
 * other types.
 *
 * @param content
 *            The data to convert, generally taken from a field in an input
 *            Record.
 * @param inputSchema
 *            The schema of the content object
 * @param outputSchema
 *            The schema to convert to.
 * @return The content object, converted to the output schema.
 * @throws AvroConversionException
 *             When conversion is impossible, either because the output type
 *             is not supported or because numeric data failed to parse.
 */
private Object convertData(Object content, Schema inputSchema,
        Schema outputSchema) throws AvroConversionException {
    if (content == null) {
        // No conversion can happen here.
        if (supportsNull(outputSchema)) {
            return null;
        }
        throw new AvroConversionException("Output schema " + outputSchema
                + " does not support null");
    }

    Schema nonNillInput = getNonNullSchema(inputSchema);
    Schema nonNillOutput = getNonNullSchema(outputSchema);
    if (nonNillInput.getType().equals(nonNillOutput.getType())) {
        return content;
    } else {
        if (nonNillOutput.getType() == Schema.Type.STRING) {
            return content.toString();
        }

        // For the non-string cases of these, we will try to convert through
        // string using Scanner to validate types. This means we could
        // return questionable results when a String starts with a number
        // but then contains other content
        Scanner scanner = new Scanner(content.toString());
        scanner.useLocale(locale);
        switch (nonNillOutput.getType()) {
        case LONG:
            if (scanner.hasNextLong()) {
                return scanner.nextLong();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to long");
            }
        case INT:
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to int");
            }
        case DOUBLE:
            if (scanner.hasNextDouble()) {
                return scanner.nextDouble();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to double");
            }
        case FLOAT:
            if (scanner.hasNextFloat()) {
                return scanner.nextFloat();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to float");
            }
        default:
            throw new AvroConversionException("Cannot convert to type "
                    + nonNillOutput.getType());
        }
    }
}