Using Double.parseDouble( ) within I/O - java

I'm trying to write a program that gets a series of five double String values from a user and then attempt to convert those Strings to a double using the Double.parseDouble() method. The trouble I'm having is that I have to enter two values before the next "Please enter a number" pops up. Here is the output I've been getting:
Please enter a number 1: 4
3
Please enter a number 2: 5
4
Please enter a number 3: 3
4
Please enter a number 4: 5
6
Please enter a number 5: 4
2
The average is: 3.8
Here is my code:
import java.io.*;
import java.util.Scanner;
public class theman {
public static void main(String[] args) throws IOException{
// Variables
int counter;
int userEntries = 5;
double sum = 0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
// Creating a new Scanner
Scanner scanner = new Scanner(System.in);
// Loop for the five entries
for (counter = 1; counter <= userEntries; counter++) {
String input = "";
System.out.print("Please enter a number " + counter + ": ");
input = br.readLine();
double number = Double.parseDouble(input);
sum += scanner.nextDouble();
}
// Print statements
System.out.println("The average is: " + sum / userEntries);
} // End of method header
} // End of class header
What is the best way to correct this problem? I'm assuming it's because of the sum += scanner.nextDouble(); but I need it to increment so I really can't delete it.

You already have the double, so there's no need to use Scanner.nextDouble(). The nextDouble() method scans the next token of the input as a double. What you should be doing is sum += number.

final int userEntries = 2;
Scanner in = new Scanner(System.in);
double sum = 0.0;
for (int counter = 1; counter <= userEntries; ++counter) {
System.out.printf("Please enter a number %d: ", counter);
sum += in.nextDouble();
}
System.out.printf("The average is: %.2f%n", sum / userEntries);

Here's an updated code -
import java.io.*;
import java.util.Scanner;
public class theman {
public static void main(String[] args) throws IOException{
// Variables
int counter;
int userEntries = 5;
double sum = 0;
// Creating a new Scanner
Scanner scanner = new Scanner(System.in);
// Loop for the five entries
for (counter = 1; counter <= userEntries; counter++) {
System.out.print("Please enter a number " + counter + ": ");
sum += scanner.nextDouble();
}
// Print statements
System.out.println("The average is: " + sum / userEntries);
} // End of method header
} // End of class header

Related

Making a calculator that does operation of x number of numbers

package com.company;
import java.util.*;
import java.lang.*;
public class ENCRYPTED {
public static void main (String args[]) {
//Declaring scanner
Scanner sc = new Scanner(System.in);
//Declaring Arrays
double[] numbers = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
String[] op = {"+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+",};
double[] ans = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
//Getting Number of Numbers
System.out.println(" How many numbers to add/subtract ? : ");
int nofns = sc.nextInt();
// for loop that executes to get the numbers
for (int i = 0; i < nofns; i++) {
System.out.println("Enter Number " + i + " : ");
numbers[i] = sc.nextDouble();
System.out.println("Enter Operator for number " + i + " : ");
op[i] = sc.next();
ans[i] = numbers[i] + numbers[i+1];
System.out.println(ans[i]);
System.out.println(numbers[i]);
System.out.println(op[i]);
}
}
}
this is a program I made that takes in x numbers of numbers and stores them in the array (numbers) and operators (op). I want to store the operations done (-,+,*,/) on the ans array. I want to get a logic for this program that does the operations and stores them in the array. so these are my question.
How do I write this
Write this : (This taken from numbers array:5) ((This taken from op array)-) (This taken from numbers array:4) = (Stored and printed in ans aray)1
thanks for all for reading this
EDIT: "I just discovered the method for adding and substracting but I still want to find the multiplication and division, Sorry for not commenting the code"
THIS IS THE IMPROVED CODE
package com.company;
import java.util.*;
import java.lang.*;
public class ENCRYPTED {
public static void main (String args[]) {
//Declaring scanner
Scanner sc = new Scanner(System.in);
//Declaring Arrays
double[] numbers = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
String[] op = {"+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+",};
double[] ans = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
double sum=0;
//Getting Number of Numbers
System.out.println(" How many numbers to add/subtract ? : ");
int nofns = sc.nextInt();
// for loop that executes to get the numbers
for (int i = 0; i < nofns; i++) {
System.out.println("Enter Number " + i + " : ");
numbers[i] = sc.nextDouble(); //Ex : 5
// System.out.println("Enter Operator for number " + i + " : ");
// op[i] = sc.next(); //Ex: +
System.out.println("Enter Number " + i + " : ");
numbers[i+1] = sc.nextDouble(); //Ex : 6
ans[i] = numbers[i] + numbers[i+1];
System.out.println("Answer is " + ans[i]);
if (i == nofns) {
break;
}
}
for(int i=0; i<nofns; i++){
sum = sum + ans[i];
}
System.out.println("Elements of the sums are: "+Arrays.toString(ans));
System.out.println("Sum of the numbers :: "+sum);
}
}
IF anyone can suggest the method for multiplication and division, thanks for the help
"OUTPUT:
Number one : 4
Number Two : -2
and : 2"
NOTE: YOU NEED TO SUFFIX "-" SIGN BEFORE THE NUMBER TO SUBSTRACT IT
This looks like homework so I'll go at a high level. In general, you want to handle each of the 4 cases you have. Those cases are (+-*/) and maybe teh default case where you have invalid input. Then, based on what the value of op[i] you will perform the corresponding item instead of unconditionally adding like this: ans[i] = numbers[i] + numbers[i+1];

How to ensure certain requirements are met in my Java Program

public class FileAddClient {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanfile = new Scanner(System.in);
System.out.println("What is the exact name of your file?");
String doc = scanfile.next();
Scanner scanint = new Scanner(new File(doc));
int number1 = scanint.nextInt(), number2 = scanint.nextInt(),
number3 = scanint.nextInt(), number4 = scanint.nextInt(),
number5 = scanint.nextInt(), number6 = scanint.nextInt();
int sum = number1 + number2 + number3 + number4 + number5 + number6;
System.out.println("The sum of the numbers that typed is " + sum);
}
}
How can I ensure that the user enters at least 2 numbers into the file and that the only data types in the file are numbers? I am not sure how to navigate through this problem. I tried making a while loop, but, unfortunately, that is not working. Any help would be appreciated.
The method .nextInt() will throw an exception (specifically an InputMismatchException) in case the input is not an int or there is none.
You can handle that exception with a try-catch block, like this:
try {
// ... use nextInt ...
}
catch(InputMismatchException e) {
// print error message
}
My solution to this uses a while loop. The hasNextInt() function just checks if the input is of type int.
public class FileAddClient {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanfile = new Scanner(System.in);
System.out.println("What is the exact name of your file?");
String doc = scanfile.next();
Scanner scanint = new Scanner(new File(doc));
int count = 0;
int sum = 0; //total sum of numbers
while ( scanint . hasNextInt() ) { //makes sure that the input is of type int
count ++; //counts the number of correct inputs
sum += scanint.nextInt();
}
if ( count < 2 ) // file has one number or zero numbers
System.out.println ( "File has less numbers than expected. Please fix it." );
else if ( count > 6 ) //file has more than 6 numbers
System.out.println ( "File has more than 6 numbers." );
else // file has two numbers or more
System.out.println("The sum of the numbers that typed is " + sum);
}
}

How to find the average in a do-while loop

I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;

Getting a sum from a while loop

I am trying to get the sum of even numbers between 2 and a value entered by the user. I managed to get as far as printing out the even numbers but how would I get it to print just a sum of the even numbers? Rather than listing out all of the even numbers?
At the end it should look like this:
Entered value: 20
Sum of even numbers between 2 and 20: 110
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int i = 2;
while (i <= value)
{
if (i%2 == 0){
text = (text + i);
if (i< value)
text = (text + ", ");
else
text = (text + ". ");
}
i++;
}
//Output
System.out.println(text);
}
}
}
Edit:
Final answer:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int sum = 0;
for (int i = 2; i <= value; i +=2){
sum += i;
}
//Output
System.out.print(text);
System.out.println(sum);
}
}
}
Use a for loop. With a for loop, you can customize the "step" of your internal loop variable (i). This also removes the need to check for even-ness.
int sum = 0;
for (int i = 2; i < value; i+=2) {
sum += i;
}
System.out.println(sum);
On a side note, you should probably avoid the use of while(true) because it's going to require the use of an explicit break to exit the program. You should instead use some sort of boolean control variable.

Only allowing numbers to be taken from user input in java

I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);

Categories

Resources