Not getting the actual output for the following code: - java

import java.util.*;
public class Main {
Scanner input = new Scanner (System.in);
int n = 0, tn = 0, time = 0;int sum=0;
int t = input.nextInt(); //no. of test cases
for (int i =0; i<t; i++)
{
n = input.nextInt();//no. of timings
for (int j = 0; j<n; j++)
{
tn = input.nextInt(); //individual time
sum=0;
sum+=tn;
sum*=2;
}
System.out.println(t+". "+sum);
}
}
}
My output
output I am supposed to get
Can anyone tell me where I went wrong?

1.) You are setting every time sum=0 while taking new input so you are losing the previous values hence last time
sum=30
sum= 30*2 = 60
so reset the sum=0 when you are done with your first case input
2.) You need to do the multiplication after you add-up all the values so simply do the multiplication when you have the sum of all individual time values
for (int i = 0; i < t; i++) {
n = input.nextInt();// no. of timings
for (int j = 0; j < n; j++) {
tn = input.nextInt(); // individual time
// add all values first
sum += tn;
}
// multiply the total of values with 2
System.out.println(i + ". " + (sum * 2));
// now set sum=0 for next case
sum = 0;
}
Test case Output :
2
3
10
20
30
2. 120 // output of first case
2
100
50
2. 300 // output of second case

Related

i am keep getting an error Index out of bounds for length when I run this program [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
public static void main(String[] args) {
int sumEven = 0;
int sumOdd = 0;
Scanner scan = new Scanner(System.in);
// getting user's input
System.out.println("Enter the number:");
int num = scan.nextInt();
//converting int number to array
String a = Integer.toString(num);
int[] newNum = new int[a.length()];
for (int i=0; i<a.length(); i++){
newNum[i] = a.charAt(i);
}
// checking the element is even or odd
for (int i = 0; i<num; i++){
if (newNum[i] % 2 ==0){
sumEven = sumEven + newNum[i];
}else{
sumOdd = sumOdd + newNum[i];
}
}
// printing the output
System.out.println("Sum of Even Numbers: "+sumEven);
System.out.println("Sum of Odd Numbers: "+sumOdd);
}
In your second loop,num might not the same with the length of newNum,so just need to change below
for (int i = 0; i<newNum.length; i++){ // change from num to newNum.length
if (newNum[i] % 2 ==0){
sumEven = sumEven + newNum[i];
}else{
sumOdd = sumOdd + newNum[i];
}
and in your first loop, make sure you can get int value correct
String a = Integer.toString(num);
int[] newNum = new int[a.length()];
for (int i=0; i<a.length(); i++){
newNum[i] = a.charAt(i)-'0'; // make sure we can get int
}
}
There are some mistakes in your code-
newNum[i] = a.charAt(i); this will convert the integer character to it's ASCII values. In case if you type 5 it will become 53 and if you enter 6 it will become 54.
When you are checking whether the element is even or odd. for (int i = 0; i<num; i++) and this is the main reason for getting ArrayIndexOutOfBounds so you need to run loop till the array length.
public static void main(String[] args) {
int sumEven = 0, sumOdd = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number:");
int num = scan.nextInt();
String a = Integer.toString(num);
int[] newNum = new int[a.length()];
for (int i=0; i<a.length(); i++){
newNum[i] = Integer.parseInt(String.valueOf(a.charAt(i)));
}
for (int i = 0; i<newNum.length; i++){
if (newNum[i] % 2 == 0){
sumEven = sumEven + newNum[i];
}else{
sumOdd = sumOdd + newNum[i];
}
}
System.out.println("Sum of Even Numbers: "+sumEven);
System.out.println("Sum of Odd Numbers: "+sumOdd);
}
What you are doing wrong is
for (int i = 0; i<num; i++){
if (newNum[i] % 2 ==0){*
What's happening : for example user enters num=19, the above for loop is supposed to run 19 times, and for each time in loop, you are using 'i' as index of array newNum which is of size 2 only. so when the loop reaches index 2, it gives you error.
You can : either post the full problem so I can help you with what you are trying to achieve OR you can try to adjust your code according to your needs as the error is identified.
You should dry run this program.
Suppose your num = 50
a = "50" ;
//var a is a string whose length =2
//then the length of newNum is 2
newNum = 2;
but you are trying to access up to 50 place in the loop that why it is coming
I think you are understanding what I am saying.

System.out.println is not printing output

Here is my code to find even Fibonacci numbers and to add them:
package a;
import java.util.*;
public class A {
//this about finding Even Fibonacci numbers and adding them to sum.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int[] n = new int[t];
int[] nn = new int[t];
int i,j,sum;
for(int a0 = 0; a0 < t; a0++){
n[a0] = in.nextInt();
}
nn[0]=1;
for(i = 0 ; i<t;i++){
sum = 0;
for(j= 1;j<n[i];j++){
nn[j] = j+nn[j-1];
if(nn[j]%2==0)
{
sum += nn[j];
}
}
System.out.println(sum); //this is not printing the output
}
}
}
Sample Input
2
10
100
Sample Output
10
44
The problem is that this line System.out.println(sum); is not printing anything.
Any ideas?
In your code you have
for(int a0 = 0; a0 < t; a0++){
n[a0] = in.nextInt();
}
The problem is that the program is waiting for you to enter t integers. I don't know what values you want there, but change it to something more like this
for(int a0 = 0; a0 < t; a0++){
n[a0] = 0;//But instead of 0 the actual number that you want to set for the value.
}
I hope you find this helpful!
I do not see a problem here. Just took the code, compiled and executed it. After specifying the value for t and also providing t input values, I saw an output on the console.
stefan#linux-3047:~$ java A
5 (t)
1 (1st of 5 values)
2 (2nd of 5 values)
3 (3rd of 5 values)
4 (4th of 5 values)
5 (5th of 5 values)
0 (System.out.println)
2 (System.out.println)
6 (System.out.println)
6 (System.out.println)
6 (System.out.println)
Multiple problems exist here.
One error at line 25 if the t for example is 5:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at application.A.main(A.java:25)
Added some System.out.println(...) to see how you can fix it cause i don't know the code you want to add:
package application;
import java.util.*;
public class A {
// This about finding Even Fibonacci numbers and adding them to sum.
public static void main(String[] args) {
System.out.println("Enter a number below:\n");
Scanner in = new Scanner(System.in);
int t = in.nextInt();
System.out.println("You entered..." + t+"\n");
// Arrays
int[] n = new int[t];
int[] nn = new int[t];
int i, j, sum;
// First For Loop
for (int a0 = 0; a0 < t; a0++) {
System.out.println("Enter a number a0..");
n[a0] = in.nextInt();
System.out.println("You entered ao=:" + a0+"\n");
}
nn[0] = 1;
// Second For Loop
for (i = 0; i < t; i++) {
sum = 0;
for (j = 1; j < n[i]; j++) {
nn[j] = j + nn[j - 1];
if (nn[j] % 2 == 0) {
sum += nn[j];
}
}
// this is not printing the output
System.out.println("Sum is:="+sum);
}
}
}

2D Array with Number Averages

Here is the original question:
Write a program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
I edited the code now to show my new nested for loops at the bottom. These are supposed to compute the average of the entered numbers, however, I am not sure why it does not work?
You can use two variables, one for the row, and one for the column:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
This logic is weird and never can be met
while (count < 3) {
while (count < 9) {
at the moment that count is bigger than 3 you will never see again the while at count<9
you should think again and reorder the conditional check of that value..
while (count < 9) {
while (count < 3) {
could make more sense...
You could rewrite this segment:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...to
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
... which simultaneously populates your matrix and computes the mean.
Alternatively you can have one loop;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
Think about it in terms of English or pseudo code first, it will be surprisingly easier.
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
In codes:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
If you can get the average of just one row, congratulations, your work is more than half done. Simply repeat the above process for all other rows with another loop. (This explains why you need 2 loops. One for the columns, the other for the rows).
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
In codes:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
To get values from row and col:
int row = scores.length;
int col = scores[0].length;

JAVA displaying an array as matrix and random numbers are equal to the minimum

I have to write a JAVA program where a user set the number of columns and rows of a 2d array. Then he should choose a minimum and a maximum. After that, the array is filled randomly.
I writed this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class array2d
{
public static void main (String[] args) throws java.lang.Exception
{
int rows, col, min, max;
Scanner scan1 = new Scanner(System.in);
System.out.println("Enter number of rows and columns:");
rows = scan1.nextInt();
col = scan1.nextInt();
int[][] a = new int[rows][col];
System.out.println("Enter min and max:");
min = scan1.nextInt();
max = scan1.nextInt();
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
a[i][j] = min - (int)Math.random()*(max-min+1);
}
}
//Display on the screen
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
System.out.print(a[i][j]+ " ");
}
}
...
}
}
Then we should run a program to see if the first number of each row is a divisor of all the row:
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
if(a[i][0]%a[i][j]==0)
{
System.out.println(a[i][j]);
}
else
System.out.println("None");
}
}
That's working properly, but the generated array on my computer is displayed like that (CMD output):
And as you see in the picture, all randomly filled random are equal to the minimum specified.
So how can I display this array as like matrix and why the random numbers are showing like this.
Math#random return a number between 0.0-1.0, but less then 1.0. This does in fact make your calculation look like the following min-0, since you are parsing it as int. Due to this you are allways saying 0*(max-min+1).
In order to achive what you want you need to add braces and add to min.
For your representation problem, add a System.out.println after you finished the inner loop.
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++) {
a[i][j] = min + (int)(Math.random()*(max-min+1)); // You need brackets and add it to min
}
}
//Display on the screen
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++){
System.out.print(a[i][j]+ " ");
}
System.out.println(); // You need a linebreak
}
All slots of your array get filled wit the 10 value in your example, min in general :
a[i][j] = min - (int)Math.random()*(max-min+1);
yields
a[i][j] = 10 - (int)Math.random()*(10);
Math.random() returns a double greater than or equal to 0.0 and less than 1.0 , so rounded to an int, it is 0 .
so
a[i][j] = 10 - (0*(10)); // this yields 10, the value of "min"
Where you have:
a[i][j] = min - (int)Math.random()*(max-min+1);
You actually mean:
a[i][j] = min + (int) (Math.random()*(max-min+1));
The first one casts Math.random() to an int (giving zero), then multiplies it by (max-min+1) (giving zero), then subtracts it from min (giving min).
The second one multiples Math.random() by an int (giving a random double in the range [0,max-min+1) ), then casts it to an int (giving a random int in the range [0,max-min] ), and then adds min (giving a random int in the range [min,max] ).

Java: Array with loop

I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written.
But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
If all you want to do is calculate the sum of 1,2,3... n then you could use :
int sum = (n * (n + 1)) / 2;
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:
int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
sum += (i+1);
results[i] = sum;
}
Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]
To populate the array:
int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
numbers[i] = i+1;
}
and then to sum it:
int ans = 0;
for (int i = 0; i < numbers.length; i++) {
ans += numbers[i];
}
or in short, if you want the sum from 1 to n:
( n ( n +1) ) / 2
If your array of numbers always is starting with 1 and ending with X then you could use the following formula:
sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.
int i = 100;
// Implement the fomrulae n*(n+1)/2
int sum = (i*(i+1))/2;
System.out.println(sum);
int[] nums = new int[100];
int sum = 0;
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
{
nums[i] = i + 1;
sum += n;
}
System.out.println(sum);
The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.
Public Class Program
{
public static void main(String args[])
{
//Array Intialization
int my[] = new int[6];
for(int i=0;i<=5;i++)
{
//Storing array values in array
my[i]= i;
//Printing array values
System.out.println(my[i]);
}
}
}

Categories

Resources