i still new at coding, and i am wonder if anyone could help me with java code.
additionally, explaining how to deal with this issue.
here is my code below:
import java.util.Scanner;
public class SumAverage {
public static void main(String[] args) {
// create a Scanner to obtain input from the command window
Scanner input = new Scanner(System.in);
int number1, number2, sum;
System.out.print("Enter first integer: "); // prompt
number1 = input.nextInt(); // read 1st number from user
System.out.print("Enter second integer: "); // prompt
number2 = input.nextInt(); // read 2nd number from user
sum = number1 + number2;
double average = (double) sum / 2;
String message = "Sum is";
System.out.printf("%s %d\n", message, sum);
System.out.printf("Average is %.2f\n", average);
} // end main method
} // end class SumAverage
Related
I'm trying to store the sum of 2 numbers inside a while loop so that once the loop ends multiple sums can be added up and given as a total sum, however I am rather new to Java and am not sure how to go about doing this.
I'm trying to use an array but I'm not sure if it is the correct thing to use. Any help would be greatly appreciated.
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}
There is a data container called ArrayList<>. It is dynamic and you can add as many sums as you need.
Your example could be implemented like this:
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++)
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}
From what I see, you come from a background of C# (Since I see capital letter naming on all variables). Try to follow the java standards with naming and all, it will help you integrate into the community and make your code more comprehensible for Java devs.
There are several ways to implement what you want, I tried to explain the easiest.
To learn more about ArrayList check this small tutorial.
Good luck!
Solution with array:
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[count]=AddedNum;
count++;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}
This solution is not dynamic. There is risk that length of array defined on beginning will not be enough large.
I am learning Java and am having a very simple problem.
How to print the final sum from a while loop?
if I enter integers 10 10 40
the output I get is
10
20
60
but am only trying to get the final 60.
This answer can also relate to printing the final anything in a while loop as I just can't seem to get this.
my sample code below...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
System.out.println("The Sum is: " + total);
}
}
Your main problem is that you have put the print statement inside the loop.
Also, in.hasNextDouble() doesn't make sense for input from the keyboard; it is useful when you are reading data from a file or a Scanner for some string. You can use an infinite loop (e.g. while(true){...}) and break it when there is no input from the user.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up, press Enter without any input to exit: ");
double total = 0;
while (true) {
String input = in.nextLine();
if (input.isBlank()) {
break;
}
total += Double.parseDouble(input);
}
System.out.println("The Sum is: " + total);
}
}
A sample run:
Enter a sequence of numbers to sum up, press Enter without any input to exit:
10
20
30
The Sum is: 60.0
A demo of a Scanner for a string:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner("10 20 30");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
}
Output:
The Sum is: 60.0
The problem lies in: System.out.println("The Sum is: " + total);
If you would like for only the final sum to be printed it needs to be outside of the while loop.
Please, print the total outside of the loop and it will work fine !
Code:
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{
public static void main(String[] args)
{
System.out.println("Enter 3 numbers: ");
Scanner input = new Scanner (System.in);
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1=input.nextInt();
num2=input.nextInt();
num3=input.nextInt();
avg=(double)(num1+num2+num3)/3.0;
System.out.println("The average is: " + decimalFormat.format(avg));
}
}
I don't know what you find hard here. I think you are looking for this:
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1= Integer.valueOf(JOptionPane.showInputDialog("Enter #1"));
num2= Integer.valueOf(JOptionPane.showInputDialog("Enter #2"));
num3= Integer.valueOf(JOptionPane.showInputDialog("Enter #3"));
avg=(double)(num1+num2+num3)/3.0;
JOptionPane.showMessageDialog(null, "The average is: " + decimalFormat.format(avg));
Please note that this code could be written better but for the sake of answering I just replaced the JOptionPane in your code where you need them.
It's really not that much harder. On the input side, using one of the showInputDialog(...) methods of JOptionPane is almost an exact replacement for input.nextInt();. The only difference it that showInputDialog(...) returns the user's input as String, not an int, so you'll have to use Integer.parseInt to convert the returned String into an int. As for the output, showMessageDialog(...) is an almost exact replacement for System.out.println(...); just use the --- as the message text argument.
public static void main(String[] args) {
int num, count=0;
double total =0, avg;
for(int i = 1; i <= 3; i++){
num = Integer.valueOf(JOptionPane.showInputDialog("Enter number "+ count++));
total += num;
}
avg = total / count;
JOptionPane.showMessageDialog(null, "The average is: " + (double)Math.round(avg * 100) / 100);
}
/*
*AverageOfThreeNumnber.java
*calculating the Average Of Four Numnberand diaply the output
*using JOptionpane method in java
*/
import javax.swing.JOptionpane;
public class AverageOfThreeNumbers {
public static void main(String[] args) {
int fristNumber; // FRIST INTEGER NUMBER
int SecondNumber; // SECOND INTEGER NUMBER
int ThridNumber; // THRID INTEGER NUMBER
int sum; // SUM OF THE FOUR INTEGER NUMBERS
double avarage; // AVERAGE OF THE FOUR NUMBERS
String input; // INPUT VALUE
String result; // OUTPUT GENERATING STRING
// ACCEPT INTEGER NUMBERS FROM THE USER
input = JOptionpane.showInputDialog(null, "Enter frist nmuber: ");
FristNumber=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Second nmuber: ");
SecondNumberr=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Thrid nmuber: ");
ThridNumber=Integer.parse.Int(Input);
//CALCULATE SUM
sum = fristNumber + SecondNumber + ThridNumber;
//CALCULATE AVERAGE
average = sum/4.0
//BUILD OUTPUT STRING AND DISPLAY OUTPUT
result = "Average of" + fristNumber + ", " + SecondNumber + " And " + ThridNumber +" is = " + average;
JOptionpane.showMessageDialog(null, result, "Average of 3 Numbers", JOptionpane.INFORMATION_MESSAGE);
}
}
I am trying to make a simple calculator program where a user enters two values, the method add() is called from the Operations class and the values are added and the result is displayed. And then I am using a do while loop in which the user keeps entering values which are added to the last total and the result is displayed. It has to keep running unless the user enters some input which is not of the type double.
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number: ");
double number = input.nextDouble();
System.out.println("Enter the second number: ");
double number2 = input.nextDouble();
double total = Operations.add(number, number2);
System.out.println(total);
System.out.println("Enter the number again: );
number2 = input.nextDouble();
do {
total = Operations.add(total, number2);
System.out.println(total);
System.out.println("Enter the number again: ");
number2 = input.nextDouble();
} while (input.hasNextDouble());
System.out.println("Exit.");
}
}
And here is the Operations class
public class Operations {
public static double add(double n1, double n2) {
return n1 + n2;
}
}
It adds the first two values, and displays the result. Then it asks for the value again, user inputs, and it displays the result. But from here on there is a problem somewhere which I have tried so hard to figure out but couldn't do so. So please look over my code and tell me where the problem is. Its something in the do while loop which I am doing wrong.
Output:
Enter the first number:
5
Enter the second number:
2
7.0
Enter the number again:
1
8.0
Enter the number again please:
2
Here the program is running but does nothing when I press 2. If for example I press 6 again, it will still add 2 (which I entered before) to the total and display that
6
10.0
Enter the number again please:
Your issue lies with the order in which things are occurring. You want to prompt and input at the beginning of the do-while:
do {
System.out.println("Enter the number again: ");
number2 = input.nextDouble();
total = Operations.add(total, number2);
System.out.println(total);
} while (input.hasNextDouble());
This makes the first re-prompt and re-input redundant, so your final class looks like:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number: ");
double number = input.nextDouble();
System.out.println("Enter the second number: ");
double number2 = input.nextDouble();
double total = Operations.add(number, number2);
System.out.println(total);
do {
System.out.println("Enter the number again: ");
number2 = input.nextDouble();
total = Operations.add(total, number2);
System.out.println(total);
} while (input.hasNextDouble());
System.out.println("Exit.");
}
Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
A method that accepts two integer parameters and returns their average.
A method that accepts three integer parameters and returns their average.
A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.