Making a calculator that does operation of x number of numbers - java

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];

Related

Adding the code for ascending order of user input

import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
line = in.nextLine();
System.out.print("Input Number 1: " );
line = in.nextLine();
System.out.print("Input Number 2: ");
line = in.nextLine();
System.out.print("Input Number 3: " );
line = in.nextLine();
System.out.print("Input Number 4: ");
line = in.nextLine();
System.out.print("Input Number 5: " );
line = in.nextLine();
}
public static void sortAscending (double[]arr)
{
Arrays.sort(arr);
System.out.printf("Sorted arr[] = %s",
Arrays.toString(arr));
}}
I am stuck on what the code is for putting the what the user inputs in ascending order. I have looked up and tried multiple resources on ascending order but nothing seems to work. I tried:
System.out.print("Input number 1: "+(i+1+":");
to try and add the inputs instead of writing all of them out but i was an unknown variable.
You should use an array to store input and a loop to read input.
System.out.print("How many numbers you want to input?: ");
int num = in.nextInt();
double[] arr = new double[num];
for(int i = 0; i < num; i++){
arr[i] = in.nextDouble();
}
sortAscending(arr);
You have to create an array. Then put the stuff you are reading into the array and after that call your method.
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
sortAscending(values);
Note that the name sortAscending is not accurate, it is not just sorting (and then returning the result or in-place), but also printing. So maybe you should rename it to sortAndPrintAscending. Or just sort it and let your main method to the printing.
Or drop it completely, the method does not really serve any purpose as it is just calling Arrays.sort, might as well do that in main:
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
Arrays.sort(values);
System.out.println("Sorted: " + Arrays.toString(values));

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.

Using Double.parseDouble( ) within I/O

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

2 or more digit numbers with delimiters in java

I have this basic program that works pretty well when entering single digit numbers. But when calculating an expression with multiple digits, like 1337 - 456 + 32, the program doesn't move on...it acts likes I did nothing.
It doesn't freeze or output an error message, it just stops.
here's the code:
import java.io.*;
import java.util.*;
public class Tester {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter number: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*");
int sum = 0;
int temp = 0;
int intbefore = 0;
if (sc.hasNext("\\-")) {
sc.next();
if (sc.hasNextInt()) {
intbefore = sc.nextInt();
int temper = intbefore * 2;
intbefore = intbefore - temper;
}
}
if (sc.hasNextInt()) {
intbefore = sc.nextInt(); //now its at the sign (intbefore = 5)
}
sum = intbefore;
while (sc.hasNext()) {
if(sc.hasNext("\\+")) { //does it have a plus sign?
sc.next(); //if yes, move on (now at the number)
System.out.println("got to the next();");
if(sc.hasNextInt()) { //if there's a number
temp = sc.nextInt();
sum = sum + temp; //add it by the sum (0) and the sum of (5) and (4)
System.out.println("added " + sum);
}
}
if(sc.hasNext("\\-")) {
sc.next();
System.out.println("got to the next();");
if (sc.hasNextInt()) {
temp = sc.nextInt();
sum = sum - temp; //intbefore - temp == 11
System.out.println("intbefore: " + intbefore + " temp: " + temp);
System.out.println("subtracted " + sum); // subtracted by 11
}
}
}
System.out.println("Sum is: " + sum);
}
}
Help with why this happens and what to do to fix it?
(I'm using netbeans if that helps)
Also, I'm assuming that the input has a space between each number Ex: 123 + -23 - 5
I tried to execute your code and this is what i found.
Suppose your input was 12+1.
Not sc.hasNextInt() will give you 1 which you are assigning to intbefore.
Next the while loop in your code is going to infinite loop cos sc.hasNext() will always be true (and returning 2 in this case ) and it doesn't match the two if conditions inside the while loop thus making your code run in infinite loop. Now go ahead and work on that. All the best.
Try to change the dilimeter as "\\s+" in the first place or just use the default one

Categories

Resources