i am working on a program to add numbers using an array. I have completed a lot of it but am troubled at the last part adding the actual numbers in the code. Here is my code.
public static void main (String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
int n= input.nextInt();
int[] x= new int[n];
System.out.println("Enter Array nums");
for(int i=0;i<n;i++){
x[i]= input.nextInt();
}
}
You just need to initial variable with 0 which will have a sum of all values and then while taking a input the values are added into the variable initialized for holding the total values in the same for loop.
Given below is the code for the same.
public static void main(String args[]){
Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
int n= input.nextInt();
int[] x= new int[n];
System.out.println("Enter Array nums");
int total=0;
for(int i=0;i<n;i++){
x[i]= input.nextInt();
total=total+x[i];
}
System.out.println("total"+total);
}
Why not just write some code to add numbers?
import java.util.Scanner;
class X {
public static void main (String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
int n= input.nextInt();
int[] x= new int[n];
System.out.println("Enter Array nums");
for(int i=0;i<n;i++){
x[i]= input.nextInt();
}
int sum = 0;
for(int i=0;i<n;i++){
sum+= x[i];
}
// to print the result, uncomment the line below
//System.out.println(sum);
}
}
here is a method that will add up your array for you:
public int totalArray(int[] someArray) {
int reply = 0;
for (int value : someArray) reply += value;
return reply;
}
Related
I have to take the size of the array from user input and store it
and also I tried to store values in array ac to size but when I run the program, for loop executes once after its showing an error of boundary exception
import java.util.Scanner;
public class Odd {
int size;
int a[] = new int[size];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Size of array");
size = sc.nextInt();
for (int i = 0; i < size; i++) {
System.out.println("enter " + i + "th element");
a[i] = sc.nextInt();
}
System.out.println("your array is");
for (int i = 0; i < size; i++) {
System.out.print(a[i] + " ");
}
}
}
When you write
public class Odd
{
int size;
int a[]=new int[size];
then whenever Odd is constructed, a is created to be an array with size equal to the current value of size, which is 0.
When you then write
size=sc.nextInt();
the size of a does not change to the new value of the size variable.
There are several things wrong with your code.
First, the static method main is not able to access size and a because they are instance variables. You would need to make them static or make them local variables in the main method.
Second, size is zero. You create the array without knowing what the user will enter for size. The array has a size of zero.
Third, you don't need the variable size since you don't really use it anywhere else.
import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
int[] a = new int[sc.nextInt()];
for(int i=0;i<a.length;i++){
System.out.println("enter "+i+"th element");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}
Move the array initialization to inside main method as the size is required while creating array.
public class Odd {
static int size;
static int a[];
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
size=sc.nextInt();
a = new int[size];
for(int i=0;i<size;i++)
{
System.out.println("enter "+i+"th element");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i=0;i<size;i++)
{
System.out.print(a[i]+" ");
}
}
}
and here is the output
Enter Size of array
3
enter 0th element
1
enter 1th element
2
enter 2th element
3
your array is
1 2 3
When the array is created, the value of size is defaultly 0. Do this for better results:
public class Odd
{
int size;
int a[];
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
size=sc.nextInt();
a = new int[size];
Then whatever you have to do you can do...
You don't actually need these member variables.
import java.util.Scanner;
public class SizeArray {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Size of array: ");
int size = sc.nextInt();
int a[] = new int[size];
for(int i = 0; i < size;i ++) {
System.out.print("enter "+ i +"th element: ");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i = 0; i < size; i++) {
System.out.print(a[i]+" ");
}
sc.close();
}
}
You can just put in the main function instead of modifying them after creation.
Output:
Enter Size of array: 4
enter 0th element: 1
enter 1th element: 2
enter 2th element: 3
enter 3th element: 4
your array is
1 2 3 4
BTW please write your code in more readable format.
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr= new int[k-1];
System.out.print("Enter array :");
for(int i=0;i<=(k-1);i++)
{
Scanner sc1 = new Scanner(System.in);
arr[i] =sc1.nextInt();
}
for(int element :arr)
{
System.out.println("Print array");
System.out.println(element);
}
}
I am giving output using Scanner class. But is not printing the array.
You don't need to declare the Scanner again inside the loop. Another thing that you should do to be sure of your code, is to have this condition on the loop if i < arr.length. Lastly, I moved the "Print array" message outside the last for.
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr = new int[k];
System.out.print("Enter array :");
for(int i=0; i<arr.length; i++) {
arr[i] =sc1.nextInt();
}
System.out.println("Print array");
for(int element :arr){
System.out.println(element);
}
}
}
There are two problems with this code,
1. You don't need to create a new Scanner object for each user input.
2. You are declaring an array size of k-1 and then asking user input k times.
public static void main(String[] args) {
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k = sc.nextInt();
int[] arr = new int[k]; // To store k elements, you need k sized array
System.out.print("Enter array :");
for (int i = 0; i <= (k - 1); i++) {
// Scanner sc1 = new Scanner(System.in); / / Not required here
arr[i] = sc.nextInt();
}
System.out.println("Print array");
for (int element : arr) {
System.out.println(element);
}
}
There is only one problem in your code you are declaring the size of array as k-1 instead declare it for k elements.You just need to give each inputs in new line. For more refer this :Scanner class.
And your for each loop is correct and working.
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr= new int[k];//it was giving java.lang.ArrayIndexOutOfBoundsException
System.out.print("Enter array :");
for(int i=0;i<=(k-1);i++)
{
Scanner sc1 = new Scanner(System.in);//not required
arr[i] =sc1.nextInt();//use arr[i] =sc.nextInt();
}
for(int element :arr)
{
System.out.println("Print array");
System.out.println(element);
}
}
}
Above code will work. But you don't need new scanner objects for taking input, creating only single object will work.
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args) {
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k = sc.nextInt();
int[] arr = new int[k];
System.out.print("Enter array :");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
sc.close();
System.out.println("Print array");
for (int element : arr) {
System.out.println(element);
}
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; i < arr.length; j++) {
arr[i] = arr[j];
count++;
}
System.out.println(arr[i] + " " + count);
}
}
}
My school homework is to declare array with 100 variables.
The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.
So far I got:
public static void runTask1() {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
for (int i = 0; i < tab.length; i++);
System.out.println("Enter number for array ");
tab [] = read.nextInt();
Please help. I'm a total newbie in programming.
You should do your homework yourself ;)
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int idx=0;
do{
System.out.println("Number for array idx "+idx);
try{
tab[idx] = read.nextInt();
}catch(Exception e){
System.out.println("Wrong input");
}
if(tab[idx]<0) break;
idx++;
}while(idx<100)
Not compiled, just wrote it here.
Try that
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int index = 0;
while(index < tab.length){
System.out.println("Enter number for array ");
tab[index]= read.nextInt();
if(tab[index]<1) break;
index++;
}
System.out.println(Arrays.toString(tab));
}
Below is the code. After entering the array, the console just goes blank and does not further output the array:
import java.util.Scanner;
public class advancedArrays {
public static void main(String[] args) {
System.out.println("Provide us the size of the array:");
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
int i = 0;
int[] array = new int[value];
System.out.println("Enter the array:");
Scanner input = new Scanner(System.in);
while(input.hasNextInt()) {
array[i] = input.nextInt();
i++;
}
System.out.println("Array entered:");
for(i=0;i<value;i++)
{
System.out.println(array[i]);
}
input.close();
scanner.close();
}
}
Output:
Provide us the size of the array:
5
Enter the array:
1 2 3 4 5
you are stuck in the "reading the array" part because of this
while (input.hasNextInt()) {
array[i] = input.nextInt();
hint: you know the size of the array, then why don't you do a for loop same as you did for printing out the array's content?? like:
for (int j = 0; j < value; j++) {
array[i] = scanner.nextInt();
i++;
}
The problem is that with the while loop that you keep it waiting for more integers, it is better to convert to a normal for loop with condition on the entered array size value.
Also there is no need to use two scanner objects
public static void main(String[] args) {
System.out.println("Provide us the size of the array:");
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
int i = 0;
int[] array = new int[value];
System.out.println("Enter the array:");
for (int j = 0; j < value; j++) {
if (scanner.hasNextInt()) {
array[i] = scanner.nextInt();
i++;
}
}
System.out.println("Array entered:");
for (i = 0; i < value; i++) {
System.out.println(array[i]);
}
scanner.close();
}
package Main;
import java.util.Scanner;
public class advancedArrays {
public static void main(String[] args) {
System.out.println("Provide us the size of the array:");
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
int i = 0;
int[] array = new int[value];
System.out.println("Enter the array:");
Scanner input = new Scanner(System.in);
while(input.hasNextInt()) {
array[i] = input.nextInt();
i++;
//Changed Code
if (i == value) {
break;
}
}
System.out.println("Array entered:");
for(i=0;i<value;i++)
{
System.out.println(array[i]);
}
input.close();
scanner.close();
}
}
Fixed code, you were stuck reading your inputs for your array because you never checked if your inputs were the length of your array.
Fixed code.
if (i == value) {
break;
}
Scanner scan = new Scanner(System.in);
double numbers = scan.nextDouble();
double[] avg =..????
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
You can get all the doubles with this code:
List<Double> numbers = new ArrayList<Double>();
while (scan.hasNextDouble()) {
numbers.add(scan.nextDouble());
}
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
int num[]=new int[10];
int average=0;
int i=0;
int sum=0;
for (i=0;i<num.length;i++) {
System.out.println("enter a number");
num[i]=in.nextInt();
sum=sum+num[i];
}
average=sum/10;
System.out.println("Average="+average);
}
}
**Simple solution**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size;
System.out.println("Enter the number of size of array");
size = sc.nextInt();
int[] a = new int[size];
System.out.println("Enter the array element");
//For reading the element
for(int i=0;i<size;i++) {
a[i] = sc.nextInt();
}
//For print the array element
for(int i : a) {
System.out.print(i+" ,");
}
}
For the values of the array given by separated with space " " you can try this cool one liner Java 8 & onwards suppported streams based solution:
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
For int array you can try:
Scanner scan = new Scanner(System.in);
int[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToInt(Integer::parseInt)
.toArray();
With filter() method you can also avoid more than one spaces in between the inputs.
Complete code reference:
import java.util.Scanner;
import java.util.Arrays;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
for(double each: arr){
System.out.print(each + " ");
}
}
}
Input: 1 2 3 4 5 6 7 8 9
Output: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
If you observe carefully, there are extra spaces in between the input randomly, that has also been handled with line .filter(x -> !x.equals("")) so as to avoid blank inputs ("")
import java.util.Scanner;
class Array {
public static void main(String a[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
System.out.println("Enter the Element "+num+" of an Array");
double[] numbers = new double[num];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
for (int i = 0; i < numbers.length; i++)
{
if ( (i%3) !=0){
System.out.print("");
System.out.print(numbers[i]+"\t");
} else {
System.out.println("");
System.out.print(numbers[i]+"\t");
}
}
}
double [] avg = new double[5];
for(int i=0; i<5; i++)
avg[i] = scan.nextDouble();
This is a program to show how to give input from system and also calculate sum at each level and average.
package NumericTest;
import java.util.Scanner;
public class SumAvg {
public static void main(String[] args) {
int i,n;
System.out.println("Enter the number of inputs");
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
int a[] = new int [n];
System.out.println("Enter the inputs");
for(i=0;i<n;i++){
a[i] = sc.nextInt();
System.out.println("Inputs are " +a[i]);
}
int sum = 0;
for(i=0;i<n;i++){
sum = sum +a[i];
System.out.println("Sums : " +sum);
}
int avg ;
avg = sum/n;
System.out.println("avg : " +avg);
}
}
List<Double> numbers = new ArrayList<Double>();
double sum = 0;
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
double value = scan.nextDouble();
numbers.add(value);
sum += value;
}
double average = sum / numbers.size();
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter size of an array");
int n=s.nextInt();
double arr[] = new double[n];
System.out.println("Please enter elements of array:");
for (int i=0; i<n; i++)
{
arr[i] = s.nextDouble();
}
}
If you don't know the size of the array, you need to define, when to stop reading the sequence (In the below example, program stops when the user introduces 0 and obviously, last zero shouldn't be taken into account).
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main (String[]args)
{
System.out.println("Introduce the sequence of numbers to store in array. Each of the introduced number should be separated by ENTER key. Once you're done, type in 0.");
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
boolean go = true;
while (go) {
int value = scanner.nextInt();
numbers.add(value);
if (value == 0) {
go = false;
numbers.remove(numbers.size() - 1);
}
}
System.out.println(numbers);
}
}
Scanner scan = new Scanner (System.in);
for (int i=0; i<=4, i++){
System.out.printf("Enter value at index"+i+" :");
anArray[i]=scan.nextInt();
}
import java.util.Scanner;
public class sort {
public static void main(String args[])
{
int i,n,t;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of array");
n=sc.nextInt();
int a[] = new int[n];
System.out.println("Enter elements in array");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
t=a[1];
for(i=0;i<n;i++)
{
if(a[i]>t)
t=a[i];
}
System.out.println("Greates integer is" +t);
}
}