Average of numbers program outputting incorrect result - java

Am trying to write simple program to find average of 3 int values, but it always seems to get the average wrong
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num1 + num3)/3));
}
}
Help is greatly appreciate

Besides having num1 twice and missing num2, as already mentioned above, you will always get integer-results only, e.g. for num1 = 1, num2 = 2 and num3 = 2 your code will plot 1 as result instead of 1.667. You might enforce double-results in your output by writing
System.out.println("The average is:"+ ((num1 + num2 + num3) / 3.0));

It's supposed to be:
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num2 + num3)/3));
}
}
You accidentally added num1 twice, and forgot num2.

Related

Java loops- display every integer between two integers

I am new to coding and have been trying to understand loops. I am working on a sample project that says to Write an application that prompts a user for two integers and displays every integer between them. Display a message if there are no integers between the entered values. Make sure the program works regardless of which entered value is larger. I for the most part have it but am having an issue with the output.
import java.util.Scanner;
public class Practice2 {
public static void main(String[] args) {
int num1;
int num2;
Scanner input= new Scanner(System.in);
System.out.println("Input one integer");
num1= input.nextInt();
System.out.println("Enter another integer");
num2= input.nextInt();
while(num1<num2) {
num1 += 1;
System.out.println(num1);
}
while(num2<num1){
num2+=1;
System.out.println(num2);
}
}
}
A sample output would be
Input one integer
1
Enter another integer
9
Then this is the output
2
3
4
5
6
7
8
9
As you are incrementing value first so you can try this approach
import java.util.Scanner;
public class Practice2 {
public static void main(String[] args) {
int num1;
int num2;
Scanner input= new Scanner(System.in);
System.out.println("Input one integer");
num1= input.nextInt();
System.out.println("Enter another integer");
num2= input.nextInt();
while(num1<num2-1) {
num1 += 1;
System.out.println(num1);
}
while(num2<num1-1){
num2+=1;
System.out.println(num2);
}
}
}
You can use a for-loop for this purpose. Though you would need to include some logic to ensure that num1 is the smaller of the two numbers.
Note the num1 + 1 is there to make the first number non-inclusive.
A for-loop is broken down into 3 components
start: i = num1 + 1
condition: i <= num2
ensure i is less than or equal to num2
action: i++
after each iteration, i will be incremented by 1
import java.util.Scanner;
public class Practice2 {
public static void main(String[] args) {
int num1;
int num2;
Scanner input= new Scanner(System.in);
System.out.println("Input one integer");
num1 = input.nextInt();
System.out.println("Enter another integer");
num2 = input.nextInt();
for (int i = num1 + 1; i <= num2; i++) {
System.out.println(num2);
}
}
}
I used this method to get a perfect score.
import java.util.Scanner;
public class Inbetween {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
int x, y, X, Y;
X = input.nextInt();
Y = input.nextInt();
if (Y+1 == X || X+1 == Y ){
System.out.print("There are no integers between " + X + " and " + Y);
}else if (Y>X){
for(x=X+1; x<Y; ++x)
System.out.print(x+" ");
}else if (X>Y){
for(y=Y+1; y<X; ++y)
System.out.print(y+" ");
}
}
}

Doing a yes or no where yes continues but terminates after asking

After putting all the numbers input the loop terminates and the program ends, after asking whether to continue or not.
import java.util.Scanner;
public class coding {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner (System.in);
String choose;
int i;
double ans;
do {
int num1= in.nextInt();
int num2= in.nextInt();
int num3= in.nextInt();
int num4 = in.nextInt();
int num5 = in.nextInt();
ans = (num1+num2+num3+num4+num5)/5;
System.out.println(ans);
//in.nextLine();
System.out.println("Continue the program Yes or N?");
choose = in.nextLine();
}while (choose.equalsIgnoreCase("Yes"));
}
the program will continue on Yes and will end on N, so you need to change it the while condition to this: !choose.equalsIgnoreCase("N") to check while its not true then iterate.
secondly you used choose = in.nextLine(); which cause error on next iteration, which you need to change it to choose = in.next(); to run without error.
choose = in.nextLine(); it cause to store the enter value in next call of in.nextInt() and throw an error.
Scanner in = new Scanner(System.in);
String choose;
int i;
double ans;
do {
int num1 = in.nextInt();
int num2 = in.nextInt();
int num3 = in.nextInt();
int num4 = in.nextInt();
int num5 = in.nextInt();
ans = (num1 + num2 + num3 + num4 + num5) / 5;
System.out.println(ans);
// in.nextLine();
System.out.println("Continue the program Yes or N?");
choose = in.next();
} while (!choose.equalsIgnoreCase("N"));

How can I read any user input from the scanner library?

I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!

Unsure what to use for a sentinel controlled while loop - Java

I'm currently a beginner in Java Programming.
I'm having a little bit of trouble with my while loop that has a sentinel value.
Everything works until I add the while loop, however it's required so I can exit when the value '999' is entered.
I'm also not sure what to add for the 'if' values.
Any help would be appreciated!
import java.util.Scanner;
public class SumAverage {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.printf("Please Enter the first number%n");
int num1 = keyboard.nextInt();
System.out.printf("Please enter the second number%n");
int num2 = keyboard.nextInt();
System.out.printf("Please enter the third number%n");
int num3 = keyboard.nextInt();
int sum = num1 + num2 + num3; //calculates sum
int average = (num1 + num2 + num3) / 3; //calculates average
while (num1 != ) {
if (sum > 1)
System.out.printf("Sum: %s %nAverage: %s", sum, average);
else if (sum < 1)
System.out.printf("Sum: %s %nAverage: %.2f", sum, average);
}
}
}
You can do it in the following manner:
import java.util.Scanner;
public class SumAverage {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
int input,sum,avg,count;
do{
System.out.printf("Please enter number" + (count+1) + "%n");
input = keyboard.nextInt()
sum += input;
count += 1;
avg = sum/count;
}while(input != 999);
//Do whatever is to be done once sentinel is input.
}
You can modify the while loop as follows
while(num1 !=999 || num2 !=999 || num3 !=999)
|| is used as OR operator. So whenever any input value is 999 the loop wont execute.

How to recognize what math operation I am inputing? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am trying to make a simple calculator which can add, substract, divide and multiply any two numbers.
The way it works is that I ask for a number, then I ask for a sign (+,-,*,/) , and then I ask for the second number. The math should be done accordingly afterwards.
However I can't get the 'math sign' to be recognized properly by the program.
Here is my code:
package practice1;
import java.util.Scanner;
public class maiin {
public static void main(String[] args){
System.out.println("it works.");
double num1;
double num2;
String sign;
double total;
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
num1 = input.nextDouble();
System.out.println("Enter a +,-,/,* sign: ");
sign = input.nextLine();
input.nextLine();
System.out.println("Enter another number: ");
num2 = input.nextDouble();
if (sign.equals("+")){
total = num1 + num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("-")) {
total = num1 - num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("/")) {
total = num1 / num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("*")) {
total = num1 * num2;
System.out.println("Your total is: " + total);
} else {
System.out.println("Please enter the a proper sign");
}
When I run the program, I always get "Please enter the a proper sign".
Thank you in advanced.
I think you need to change
sign = input.nextLine();
input.nextLine();
to
sign = input.nextLine();
sign.nextLine();

Categories

Resources