Finding the maximum out of three doubles from standard input - java

We have a java assignment where in we're supposed to develop a method that scans one line that is supposed to contain three double values and returns the largest. Throwing all possible exceptions is allowed.
Here is what I've done so far:
import java.util.Scanner;
public class s3dv {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double entered;
System.out.println("Enter 3 values to find the maximum:");
entered = input.nextDouble();
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
} // End getMaxValue method
}
I'm having an error at line 15.

change your code to
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
System.out.println("Enter 3 values to find the maximum:");
for(int i=0;i<3;i++){
entered[i] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i]; } } return maxValue;
}

You cannot give a double parameter to a method while it expects a double array. And also you request user to enter double value only once, you should repeat that procedure. Change your main method to this:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
int counter = 0;
while (counter != 3)
{
System.out.println("Enter a double value:");
entered[counter++] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
Your getMaxValue() method seems OK, however when entering doubles from console use comma(,) instead of dot(.), you might get InputMismatchException otherwise.

this main code will read the 3 double value in a single line, split them and pass it to the getMaxValue
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userLine, lineSplitted[];
System.out.println("Enter 3 values to find the maximum:");
userLine = input.nextLine();
lineSplitted=userLine.split(" ");
double entered[]=new double[lineSplitted.length];
for (int i=0; i<lineSplitted.length; i++) entered[i]=Double.valueOf(lineSplitted[i]);
System.out.println("Maximum is - " + getMaxValue(entered));
}

Related

How to validate scanner so only non negative doubles are added to array?

import java.util.Scanner;
public class ArrayReview {
public static void main(String[] args){
double[] doublesArray = createArray();
printArray(doublesArray);
}
//"input method" create array of 10 doubles
public static double[] createArray() {
Scanner userInput = new Scanner(System.in);
double[] array = new double[10];
System.out.println("Input 10 non-negative double numbers");
for(int i = 0 ; i < array.length ; i++) {
//input validation
while(!userInput.hasNextDouble()) {
userInput.nextLine(); //throws away bad input
System.out.println("Please input a valid double input");
}
if(userInput.hasNextDouble()) {
array[i] = userInput.nextDouble();
}
}
userInput.close();
return array;
}
//print all values in an array of doubles
public static void printArray(double[] array) {
for(int i = 0 ; i < array.length ; i++) {
System.out.print(array[i] + " ");
}
}
}
I need to validate all the users input so that only non negative numbers are allowed into the array. Currently I was able to check if the user inputs a letter or special character but negative numbers are still able to go into the array.
I've tried using the "<" operand in the while statement to see if the userInput<0 but i'm getting an error if i do that. Would I be better off making a method that is solely dedicated to checking if its a negative or not or is there an easier way?
You could extend the conditional expression of the while loop as follows:
for (int i = 0; i < array.length; i++) {
double value;
while (!userInput.hasNextDouble() || (value = userInput.nextDouble()) < 0) {
userInput.nextLine(); // throws away bad input
System.out.println("Please enter a valid, non-negative double value");
}
array[i] = value;
}
I tried using do-while instead of while. So I can access the input first.
public static double[] createArray() {
Scanner userInput = new Scanner(System.in);
double[] array = new double[10];
double value;
boolean isValid;
System.out.println("Input 10 non-negative double numbers");
for(int i = 0 ; i < array.length ; i++) {
//input validation
do {
value = userInput.hasNextDouble() ? userInput.nextDouble() : 0;
if(value > 0) {
array[i] = value;
isValid = true;
}else {
System.out.println("Please input a valid double input");
isValid = false;
}
}while(!isValid);
}
userInput.close();
return array;
}
My approach would be, in the for loop of your createArray method to first get the input, then use while loop to see if input is less than 0 in which case you will prompt the user to input a positive number. This will loop until a positive input is received.
I have tested it on my end and seem to get the results you are looking for.
Your createArray method should look something like this:
public static double[] createArray() {
Scanner userInput = new Scanner(System.in);
double[] array = new double[10];
System.out.println("Input 10 non-negative double numbers");
for(int i = 0 ; i < array.length ; i++) {
//input validation
double input = userInput.nextDouble();
while (input < 0) {
System.out.println("Please input a positive number");
input = userInput.nextDouble();
}
array[i] = input;
}
userInput.close();
return array;
}

passing an array as an argument; Setting up Array in Java with user input with Scanner Class

I am trying to take user input, place it into my array, display the array and then print all the values larger than the "n" values the user provides. I think I am close, but I can't get the user input to go to the array. I keep getting an error in eclipse when I call the method (main at very bottom) the "arrayValues" cannot be resolved to a variable:
import java.util.Arrays;
import java.util.Scanner;
public class LargerThanN {
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
public static void printGreaterThanN(int[] integerArray, int n) {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i]>n) {
System.out.println(integerArray[i]);
}
}
}
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
/**
* This method prints the array to the standard output
* #param array
*/
private static void displayArray( int[] integerArray) {
for (int i = `0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
int [] array ;
array = fillArrayWithUserInt();
Scanner sc = new Scanner(System.in);
fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
printGreaterThanN(array, n);
but now my output looks like:
How big will the array be?
4
Enter the 4 numbers now.
1 2 3 4
How big will the array be?
3
Enter the 3 numbers now.
1 2 3
1 2 3 4
To which number would you like to compare the rest? Your n value is:
2
3
4
Heads up, the following code does nothing in java...
public void set(int n, int value) {
n = value;
}
You seem to written code like this in many functions where a value should be returned.
For example, the function definition :
static void fillArrayWithUserInt(int[] integerArray, int arraySize, int arrayValues, int n)
Should really be written as :
static int[] fillArrayWithUserInt()
It could be implemented as follows
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
The above function will ask the user for the array size. Create the array with the given size. Then prompt the user to fill the array with the correct number of values. The array created in this process is then returned.
All you must handle differently now is finding the value to compare. This must be done outside the fillArrayWithUserInt function.
Like so :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
int n = sc.nextInt();
printGreaterThanN(array, n);
}
Lastly, you should not need to declare any static variables at the top of your class.
These lines can all be deleted :
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
Here is my solution check it out.
import java.util.Scanner;
public class LargerThanN {
static int[] integerArray = null;
static int n ;
public static void printGreaterThanN() {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i] > n) {
System.out.println(integerArray[i]);
}
}
}
public static void fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
}
/**
* This method prints the array to the standard output
*
* #param array
*/
private static void displayArray() {
for (int i = 0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
fillArrayWithUserInt();
displayArray();
printGreaterThanN();
}
}

Arrays - static method to return sum, but nothing is returned

Create a Java program that reads 10 numbers from the console Scanner
input = new Scanner(System.in); .Store the numbers as Floats in the array. Create static methods to perform the following actions on the array and returns the result.Add all the items in the array and return the result. Name this method"add".
So this is my code, but when the user inputs the 10 numbers, nothing is returned. Any suggestions?
public static void main(String[] args) {
float[] myArray = new float[10];
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("please enter number");
myArray[(i)] = input.nextFloat();
}
}
public static float add(float[] array) {
float sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
You are not calling the method :
public static void main(String[] args) {
float[] myArray = new float[10];
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("please enter number");
myArray[(i)] = input.nextFloat();
}
System.out.println(add(myArray)); // need to make this call
}
At the end of for loop you need to call the add method.
System.out.println(add(myArray));

How do you store integer into a variable and computeAvg in java?

I am trying to write a Java program that:
In the main method, prompt the user for an integer number.
Store the number in a variable called inputNum.
Pass the inputNum to a method called computeAvg.
In computeAvg, prompt the user to input double values as many times as inputNum. computeAvg method should calculate and return the average of real numbers that user entered.
Print the result in your main method.
This is my code
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
computeAvg();
}
public static void computeAvg() {
System.out.println(inputnum);
System.out.println("Enter double values as inputnum ");
int y;
y=keyboard.nextInt();
}
}
There are several changes to be done in your code:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
System.out.println("The average is"+computeAvg(inputnum));
}
public static double computeAvg(int y)
{
double[] arr = new double[y];
System.out.println(y);
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
double sum = 0;
for(double a:arr){
sum +=a;
}
System.out.println(sum);
double average = sum/arr.length;
return average;
}
First one is that the value you first taken as the user input must be passed to the method. Here I done it in computeAvg(inputnum) And expect this method to return a double value.
Second one is You should declare the method to return a value void means no return. change it to double
public static double computeAvg(int y)
take the parameter from the main method (value you taken from the user.)
If you need to store multiple values better solutions is array.(There are many methods bust for a beginner stick to arrays) crate a double array to take multiple double values.
double[] arr = new double[y];
next loop your code for the number of times the user input and take the double values.
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
next create a double value sum and get the addition and the divide it to get the average (another double value).
for(double a:arr){
sum +=a;
}
Finally return the average to the main method where it prints.
I used static Scanner keyboard = new Scanner(System.in); because I used the same scanner in both methods.
Feel free to ask any question regarding the code.
I hope the comments in the code are self explanatory for what the problem is asking and how the code works:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer? ");
// here you are asking for the number of double numbers that will be
// entered
int inputnum = keyboard.nextInt(); // asking for the int input (varibale
// is stored in inputnum)
System.out.println("Average for all " + inputnum + " numbers is: "
+ computeAvg(inputnum));
}
public static double computeAvg(int inputnum) {
Scanner keyboard = new Scanner(System.in);
double eachInput = 0.0;
double sumInputs = 0.0;
for (int counter = 1; counter <= inputnum; counter++) {
System.out.println("Please enter a double as input #" + counter
+ ": ");
eachInput = keyboard.nextDouble(); // asking for double input
sumInputs += eachInput; // adding up each input
}
// calculating and returning average
return sumInputs / (double) inputnum;
}

Creating an Array List

I would like to take my current program and separate the averging function in to a method out side of the main method. I would like to store the numbers grabbed with the scanner in to an array list and then use my averaging method to grab those number and average the numbers together. then Output the average in place of the current System.out.println your average is..
Please help me illustrate this. I am having trouble understanding how all this comes together.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
{
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
}
//added an import here
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
//main difference is the average calculation is done within a method instead of main
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
double sum = 0;
int count = 0;
System.out.println("Enter a number to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) //input until user no longer wants to give input
{
if (count == 21)
{
break; //this command here jumps out of the input loop if there are 21
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble()); //simply adding to the array list
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr); //go to method calculate average, expect a double to be returned
System.out.println("Your average is: " + average);
}
private static Double calculate_average( ArrayList<Double> myArr ) //method definition
{
Double Sum = 0.0;
for (Double number: myArr) //for loop that iterates through an array list
{
Sum += number; //add all the numbers together into a sum
}
return Sum / myArr.size(); //return the sum divided by the number of numbers in the array list
}
}
This should help. Best of luck :)
Average avg = new Average();
... avg.add(scan2.nextDouble());
System.out.println("Your average is: " + Average.result());
public class Average {
void add(double x) { ... }
double result() { ... }
}
The thinking up the implementation I leave to you.
Here is some example code
private static void hoot(List<Double> kapow)
{
... do all the stuffs
}
public static void main(final String[] arguments)
{
List<Double> blam = new ArrayList<Double>();
blam.add(1.1);
blam.add(1.2);
blam.add(1.3);
hoot(blam);
}

Categories

Resources