Adding numbers of a list together - java

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());
}
}

Related

Using loops for both input and output

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

passing an array as an argument; Setting up Array in Java with user input with Scanner Class

I am trying to take user input, place it into my array, display the array and then print all the values larger than the "n" values the user provides. I think I am close, but I can't get the user input to go to the array. I keep getting an error in eclipse when I call the method (main at very bottom) the "arrayValues" cannot be resolved to a variable:
import java.util.Arrays;
import java.util.Scanner;
public class LargerThanN {
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
public static void printGreaterThanN(int[] integerArray, int n) {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i]>n) {
System.out.println(integerArray[i]);
}
}
}
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
/**
* This method prints the array to the standard output
* #param array
*/
private static void displayArray( int[] integerArray) {
for (int i = `0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
int [] array ;
array = fillArrayWithUserInt();
Scanner sc = new Scanner(System.in);
fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
printGreaterThanN(array, n);
but now my output looks like:
How big will the array be?
4
Enter the 4 numbers now.
1 2 3 4
How big will the array be?
3
Enter the 3 numbers now.
1 2 3
1 2 3 4
To which number would you like to compare the rest? Your n value is:
2
3
4
Heads up, the following code does nothing in java...
public void set(int n, int value) {
n = value;
}
You seem to written code like this in many functions where a value should be returned.
For example, the function definition :
static void fillArrayWithUserInt(int[] integerArray, int arraySize, int arrayValues, int n)
Should really be written as :
static int[] fillArrayWithUserInt()
It could be implemented as follows
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
The above function will ask the user for the array size. Create the array with the given size. Then prompt the user to fill the array with the correct number of values. The array created in this process is then returned.
All you must handle differently now is finding the value to compare. This must be done outside the fillArrayWithUserInt function.
Like so :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
int n = sc.nextInt();
printGreaterThanN(array, n);
}
Lastly, you should not need to declare any static variables at the top of your class.
These lines can all be deleted :
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
Here is my solution check it out.
import java.util.Scanner;
public class LargerThanN {
static int[] integerArray = null;
static int n ;
public static void printGreaterThanN() {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i] > n) {
System.out.println(integerArray[i]);
}
}
}
public static void fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
}
/**
* This method prints the array to the standard output
*
* #param array
*/
private static void displayArray() {
for (int i = 0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
fillArrayWithUserInt();
displayArray();
printGreaterThanN();
}
}

ArrayList<Integer>, trying to find average of entered values

Trying to find the average of the integers entered as input into the list.
Cant figure out how, im getting an error saying that it can't find symbol in
in the line total = total + in;
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt());
{
total = total + in;
count = count + 1;
}
double x = total / count;
print.println("The average is: " + x);
}
}
also, is there an easy way to output the numbers above average divided with a comma?
Remove the semi-colon after the for loop:
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
The reason in is not defined for the compiler is that the semi-colon would de-scope its definition by acting as an empty body of the for loop.
Remove ; from your loop.
for (int in = scan.nextInt(); in > 0; in = scan.nextInt());
change to
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
You shouldn't have ; after for loop...
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())//remove ; here
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
You have added semicolon ; so it's become empty body for for loop. you have to remove the semicolon after for (int in = scan.nextInt(); in > 0; in = scan.nextInt()) line in your code.
Modified Code : I am providing code after modification.
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt()){
total = total + in;
count = count + 1;
}
double x = total / count;
print.println("The average is: " + x);
}
}
The above code requires two changes:
1.You need to remove the semicolon after for loop which is making loop useless and all the iterations you want to do won't take place.
2.The second change is you need to cast one of the variables total or count to double to avoid truncation else your results will always be integers.
The modified code is as follows:
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
{
total = total + in;
count = count + 1;
}
double x = (double)total / count;
print.println("The average is: " + x);
}
}

How to get input to array simply in Java?

Like c++ we can use this.
a[5];
copy(istream_iterator<int>(cin),istream_iterator<int>(),a);
Is there some simple way to get array from input in Java?
You can use the simple way like it
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
}
//print the array
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
How about simply using System.console().readLine("Array (use , as separator)? ").split(",")? Then convert it to an int[] array (there are tons of util libraries to do that).

how to take user input in Array using java?

how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();

Categories

Resources