import java.util.Scanner;
public class basic{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter raduis : ");
for(int i=0;i<=2;i++)
float num = sc.nextFloat();
for(int i=0;i<=2;i++){
System.out.println(num[i]);
}
}
}
How can we take input from the user using loops and add all the user input and show's the output, for example, I have to take 3 user inputs (54, 6, 432), add all of them, and then show the output(432). I have tried but then I stuck.
You can use a variable (sum). You first initialize it to 0. And in the loop immediately after you get the input from the user for each value, add the input to this variable. Such a variable is sometimes referred to as an accumulator and the operation can be termed as an accumulation or reduce. If you want to store the values to display them later, you can use an array to store the values while they are being input and being summed. Also, in Java, the usual naming convention for class names is PascalCase, so consider naming it Basic:
import java.util.Scanner;
public class Basic {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
float sum = 0;
float[] array;
System.out.println("Enter the number of values: ");
int count = sc.nextInt();
array = new float[count];
for(int i=0;i< count;i++) {
System.out.println("Enter value " + i+1 + ": ");
float num = sc.nextFloat();
array[i] = num;
sum += num;
}
System.out.print("You have entered: ");
for(int i = 0; i < count;i++) {
System.out.print(array[i] + " ");
}
System.out.println("The sum of these numbers is " + sum);
}
}
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter raduis : ");
int num[],sum=0;
num = new int[3];
for(int i=0;i<=2;i++){
num[i] = sc.nextInt();
sum=sum+num[i];
}
System.out.println(sum);
}
}
You can do this in too many ways, it depends on the case, etc.
Keep it simple solution
A simple solution could be creating a new variable sum to make the sum of everything, and just iterate the loop once:
System.out.println("Enter raduis : ");
float sum = 0; // create a new variable to make the sum later
for(int i=0; i<=2; i++) {
float num = sc.nextFloat();
sum += num; // sum the current 'sum' value and 'num'
}
System.out.println("Result is: " + sum); // show the result
Keep it clean solution
If for some reason you are required to execute this logic into separated parts, you can use an array of values to collect the raduis and then, make the sum operation over the values of that array.
I suggest you use a method for that cause it will help you to uncouple the logic of asking numbers and make the sum operation very easy.
float[] askRaduis(int size) {
System.out.println("Enter raduis :");
float[] result = new float[size]; // create an array of floats
for(int i=0; i<=size; i++) { // Iterate until reaching 'size'
float num = sc.nextFloat();
result[i] = num; // save the iteration number at the array
}
return result;
}
Then, with this method, you can ask the numbers and later process the sum operation. Something like this:
float[] raduis = askRaduis(3); // Specify the amount of 'raduis' you want to ask.
float sum = 0; // create a new variable to make the sum later
for(float number : raduis ) { // this is a foreach loop it will iterate values of an array
sum += num; // sum the current 'sum' value and 'num'
}
System.out.println("Result is: " + sum); // show the result
Related
I'm new to Stack Overflow So please go easy on me :D
I'm having some problems solving this problem, because of my data is stored inside of an array I need a way to be able to put the same data inside of a variable because I need to do some operation to get the average score, the first thing that I try to do was making a variable and giving it the array as the value but it was not allowing me to do anything, I've spent quite a lot of times on it and I still cannot like understand how to fix it, so if you could please help me out with this problem.
So to summarise what I'm trying to do is get the number of students that I have stored in i and the percentage Of the students that should be in array[i], this is to obtain the average score for the number of students, so the Sum Of Percentages / number of Students * 100 = Average Percentage of Score.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
System.out.println("Hello MJ ");
Scanner sc= new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i<studenti;i++)
{
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i]= Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
for (int i=0; i<studenti;i++)
{
System.out.println((array[i])+"%");
}
System.out.println("\nThe Average Score is: " + average + "%");
int average = (persentegesOfStudents)/students;6
}
Note that in order to get the average, you need to sum the scores, and then to divide by the number of students. Your second for loop looks like the right place to handle the sum, and in addition you need to declare the average variable before printing it. Here is some suggestion (see my comments):
public static void main(String args[]) {
System.out.println("Hello MJ ");
Scanner sc = new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i < studenti; i++) {
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i] = Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
int sum = 0; // Added a variable for sum
for (int i = 0; i < studenti; i++) {
System.out.println((array[i]) + "%");
sum += array[i]; // maintaining sum
}
int average = sum / array.length; // calculating the average
System.out.println("\nThe Average Score is: " + average + "%");
}
Note that you can make the average more accurate if you work with it as float and not integer.
Use a stream to process data. Convert your array to intSream
IntStream stream = Arrays.stream(arr);
intSream have many funtions like average, min , max, sum etc.
3
100 8
15 245
1945 54
The numbers above, first is the amount of pairs, and then I want to add line by line, and have been stuck for hours. Can someone please help me?
import java.util.Scanner;
import java.util.ArrayList;
public class sumInLoops2 {
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables: ");
int cases = in.nextInt();
int sum = 0;
for(int i = 0; i < cases; i++) {
list1.add(in.nextInt());
list2.add(in.nextInt());
System.out.println(list1);
System.out.println(list2);
}
You are overcomplicating things. If you don't need to store the read values, only output the sum, then you don't need all the lists.
import java.util.Scanner;
public class sumInLoops2 {
public static void main(String[] args)
{
// ArrayList<Integer> list1 = new ArrayList<Integer>();
// ArrayList<Integer> list2 = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables: ");
int cases = in.nextInt();
for(int i = 0; i < cases; i++) {
int val1 = in.nextInt();
int val2 = in.nextInt();
int sum = val1 + val2;
System.out.println(val1 + " + " + val2 + " = " + sum );
}
}
}
If you need to store the results, make a helper object (eg LineSum) with properties val1, val2, sum, and put that in one output list.
As #thst said stated, if there is no need to store the data being inputted by the user, don't over complicate things and just output the result you need. However if your intention is to learn how to output matching number pairs within those separate lists.
Whenever you want to access a item inside a List you use the lists get() method which returns the item at that index. So in your case to print out the matching pairs added together.
for (int i = 0; i < cases; i++)
{
int num1 = list1.get(i);
int num2 = list2.get(i);
int sum = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + sum);
}
A fast example using Java8(best way,give it a try):
import java.util.Arrays;
import java.util.Scanner;
public class Java8Way {
public static void main(String[] args) {
//Create a Scanner Object
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables(separated by a space): ");
//what the following is doing
//Arrays.asList(in.nextLine().split(" ")->Splits the line that user gave to individual strings
//makes a list from them using method asList(..); from
//Arrays Class
//mapToInt(Integer::valueOf)-> makes a stream an map each string to and integer
//sum()->a special kind of reduce function which sums all the Integer elements
System.out.println("Your sum is...:"+Arrays.asList(in.nextLine().split(" ")).stream()
.mapToInt(Integer::valueOf)
.sum());
}
}
import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]
The code below shows my progress, but I cannot print the numbers that were entered. I don't know where to put println("you entered the following numbers") in the loop so that it'll show up when the loop stops.
import java.util.Scanner;
public class aufgabe5 {
public static void main(String[] args) {
int x;
Scanner input = new Scanner(System.in);
System.out.println("How much numbers do you want to enter?");
x = input.nextInt();
int j = 1;
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[x];
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + j++ + ". number:");
numbers[i] = scanner.nextInt();
}
System.out.println("You entered following numbers");
System.out.println(x);
}
}
Change x like
System.out.println(x);
to Arrays.toString(int[]) like
System.out.println(Arrays.toString(numbers));
Edit
To print the array reversed,
String str = Arrays.toString(numbers).replace(", ", " ,");
str = str.substring(1, str.length() - 1);
System.out.println(new StringBuilder(str).reverse().insert(0, "[")
.append("]"));
Intialize the String before the loop, then keep adding the values to it.
After the loop finishes you can print the whole thing.
String someVar="You entered following numbers: ";
for(int 1=0;i<array.length;i++)
{
someVar=someVar+numbers[i]+",";
}
System.out.println(someVar);
Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}