Rookie Java question - Scanner, int and user input - java

Hello there fellow Overflowers!
I'm getting started with Java and want to create a small program where it's possible to type in 5 numbers and get the sum and average printed out.
The program runs and does it's job, but I feel that there must be a way smarter method / way then what I've done.
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("5 random numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int num4 = input.nextInt();
int num5 = input.nextInt();
int sum = num1 + num2 + num3 + num4 + num5;
int avg = (num1 + num2 + num3 + num4 + num5)/5;
System.out.println("Sum is" + sum + " and the average is " + avg);```
Is it possible to declare all the numbers in one line or something?

You can use BufferedReader. Try this. Here, you need to mention all numbers in a single line.
Ex: 1 2 3 4 5
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] values = line.split(" ");
int[] arr = new int[values.length];
int sum=0;
for (int i = 0; i < values.length; i++) {
arr[i] = Integer.parseInt(values[i]);
sum+=arr[i];
}
double avg = sum/arr.length;
System.out.println("Sum is" + sum + " and the average is " + avg);

Related

Adding 2 integers in 1 User input

I want to make the user input 2 integers in 1 input like this
Enter two integers: 2 2 // sum = 4
Here is my sample code:
Scanner s = new Scanner(System.in);
int x, num1, num2, sum;
System.out.print("*Enter 2 integer: ");
x = s.nextInt();
int sum = num1 + num2;
System.out.println(" Sum = "+ sum);
Is it possible to add 2 integers without using variables num1 and num2?
I want the output to be like this.
Enter two integers: 2 2
sum = 4
Add any number of integers:
Scanner s = new Scanner(System.in);
System.out.print("Enter some integers: ");
int sum = 0;
while (s.hasNextInt()) {
sum += s.nextInt();
}
System.out.println(" Sum = " + sum);
Case 1:
If you have only 2 values then follow the below code
import java.util.*;
class Add {
public static void main(String[] args) {
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("*Enter 2 integer: ");
for(int i = 0; i < 2; i++)
sum += scan.nextInt();
System.out.println(" Sum = "+ sum);
}
}
Case 2:
If you have some More than 2 numbers but you have an idea about how many numbers to sum then follow the below code.
import java.util.*;
class Add {
public static void main(String[] args) {
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("*Enter how many integers to sum: ");
int iterate = scan.nextInt();
System.out.print("*Enter " + iterate + " integer: ");
while(iterate-- > 0)
sum += scan.nextInt();
System.out.println(" Sum = "+ sum);
}
}

Java - How to only count the inputted positive numbers

I am trying to find sum and averags of user inputed numbers and i also Need my program to only sum the positive numbers entered.
It needs to calculate only the positive numbers sum and ignore the negative inputs, would i put my num=0 or not?
import java.util.Scanner;
public class J12ForSumPos {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int maxNumbers, i, num, average;
int sum = 0;
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for (i = 1; i <= maxNumbers; i = i + 1) {
System.out.print("Enter Value " + i + ": ");
num = console.nextInt();
sum = sum + num;
}
average = sum / maxNumbers;
if (sum >= 0) {
System.out.println();
System.out.println("Sum: " + sum);
System.out.println();
System.out.println("Average: " + average);
System.out.println();
} else {
System.out.println("Sum is: " + sum * 0);
System.out.println();
System.out.println("Cannot Calculate Average - no positives entered");
}
}
}
You can try something like this:
Scanner console = new Scanner(System.in);
int maxNumbers = 0;
int totalSum = 0; // Sum of all numbers (positive and negative)
int totalAverage = 0; // Average of all numbers (positive and negative)
int positiveSum = 0; // Sum of all positive numbers
int positiveAverage = 0; // Average of all positive numbers
int positiveNumberCount = 0; // Amount of positive numbers entered
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for(int i=1; i<=maxNumbers; i=i+1)
{
System.out.print("Enter Value " + i + ": ");
int num = console.nextInt();
if(num >= 0) {
positiveSum = positiveSum + num;
positiveNumberCount = positiveNumberCount + 1;
}
totalSum = totalSum + num;
}
positiveAverage = positiveSum / positiveNumberCount;
totalAverage = totalSum / maxNumbers;
It's up to you to decide whether or not to include 0 as a positive or a negative number, or exclude it. In my example it's being treated as a positive number.

Code in Java to add two numbers is printing out sum backwards?

The following Java program (prints out addition problem of two given numbers) is printing the answer backwards ( for example, 563 instead of 365). How would I modify it so that it prints out the correct answer?
Note: I know that Im completing this problem in an unnecessarily complicated manner, but this is because we are only allowed to use primitive data types.
Thankyou.
//getting the number from user
Scanner linput = new Scanner(System.in);
System.out.print("Enter the first number:");
num = linput.nextInt();
System.out.println ("Enter the second number:");
num2 = linput.nextInt();
System.out.println (num);
System.out.println ("+");
System.out.println(num2);
System.out.println ("=======");
//making a copy of the input number
temp = num;
temp2 = num2;
//counting digits in the input number
while(num > 0)
{
num = num / 10;
count++;
}
while(num2 > 0)
{
num2 = num2 / 10;
count2++;
}
int answer = 0;
while(temp > 0 && temp2>0)
{
digit = temp % 10;
temp = temp / 10;
count--;
digit2 = temp2 % 10;
temp2 = temp2 / 10;
count2--;
answer = digit+digit2;
System.out.print(answer);
}
You problem statement is very unclear. If it's just simple addition of two numbers then you've really overcomplicated your implementation.
Scanner input = new Scanner(System.in);
System.out.print("Enter the first number:");
int num = input.nextInt();
System.out.print("Enter the second number:");
int num2 = input.nextInt();
System.out.print(num + " + " + num2 + " = " + (num + num2));
I totally agree with all comments that this is over complicated to do a sum. But the answer to the initial question why the result is printed backwards is that that you calculate the sum from right to left (units, tens, hundreds, ...) but print them left to right (default behavior of print)

Why does not this code run?

In the code you need to take 100 straight-angle triangles and print the biggest triangle. What am I not doing right?
import java.util.Scanner;
public class rthji {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = 0;
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
int num5 = 0;
System.out.println("Insert the length of the small side of the triangle");
num = in.nextInt();
System.out.println("Insert the length of the big of the triangle");
num1 = in.nextInt();
System.out.println("Insert the length of the last side of the triangle");
num2 = in.nextInt();
for (int i = 1; 1 >= 10; i++) {
System.out.println("Insert the length of the small side of the triangle");
num3 = in.nextInt();
System.out.println("Insert the length of the big of the triangle");
num4 = in.nextInt();
System.out.println("Insert the length of the last side of the triangle");
num5 = in.nextInt();
if (num3 * num3 + num5 * num5 != num4 * num4) {
num3 = num4 = num5 = 0;
} else if (num3 > num && num1 < num4 && num2 < num5) {
num = num3;
num1 = num4;
num2 = num5;
}
System.out.println("The ribs of the largest triangle are:" + num1 + (",") + num2 + (",") + num3);
}
}
}
Your for loop has a error and it should be changed to
for(int i=1;1<=10;i++)
In your case you are using 1 >= 10 which is logically wrong so your loop worries that it cannot go ahead because 1 is less than 10
Change your for loop like below
for(int i=1; i<=10; i++)

control structure, repetition exercise: How to get the sum of the digits of a number?

Guys can you please help me answer this exercise using for loop without using string methods.
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should output the individual digits of 3456 as 3 4 5 6 and the sum as 18,and output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the code:
package MyPackage;
import java.util.*;
public class Integer
{
public static void main(String args[])
{
Scanner console = new Scanner (System.in);
int input;
int sum = 0;
int num1 = 0;
int counter = 1;
String num = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input))
{
input = input * (-1);
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
}
else
{
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
Iterating all the digits from right to left is easy enough - you just keep dividing by 10 and keeping the remainder.
Since you need to print them from left to right, but there don't seem to be any constraint on the memory usage, you could just keep them in a list, and print it backwards:
int num = ...; // inputed from user
List<Integer> digits = new LinkedList<>();
int sum = 0;
// Extract the digits and the sum
while (num != 0) {
int digit = num % 10;
digits.add (digit);
sum += digit;
num /= 10;
}
// Print backwards:
System.out.print ("The digits are: ");
for (int i = digits.size() - 1; i >= 0; --i) {
System.out.print (digits.get(i) + " ");
}
System.out.println();
System.out.println("Their sum is: " + sum);

Categories