I'm brand new to programming, so please bear with me. I need to create a program using while loops, one String array, and three double arrays. My output should be something like this:
java Average 4
Joe 3 5 2
Tim 4 1 5
Jane 6 3 2
Jack 8 3 5
Jill 5 4 9
Mike 6 7 3
Ctrl-Z
Joe 3 5 2 3.33
Tim 4 1 5 3.33
Jane 6 3 2 3.67
Jack 8 3 5 5.33
I'm basically needing a program to read input with names, and three numbers. The output should print the names and numbers I inputted and then the average of each set of numbers. I'm able to create a class file, but after I press Ctrl+z, the program doesn't output anything.
public class Average {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
String [] names = new String [n];
double [] a = new double [n];
double [] b = new double [n];
double [] c = new double [n];
int counter = 0;
while (counter < n) {
String [] run = StdIn.readAllStrings();
double [] value = StdIn.readAllDoubles();
counter++;
}
int i = 0;
double sum = 0.0;
while (!StdIn.isEmpty()) {
double value = StdIn.readDouble();
sum += value;
n++;
double average = sum / n;
StdOut.print(names);
StdOut.print(value);
StdOut.printf("%.2f", average);
}
}
}
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(Pattern.compile("\n"));
scanner.forEachRemaining(s -> {
if(s.replace(" ","").equals(""))return;
System.out.println(s+" "+Arrays.stream(s.split(" ")).skip(1).mapToInt(Integer::parseInt).average().orElse(0));
});
Related
Here is the coding question for which I am trying to solve
Write a program that reads two numbers aa and bb from the keyboard and calculates and outputs to the console the arithmetic average of all numbers from the interval [a; b][a;b], which are divisible by 33.
Sample Input 1:
-5
12
Sample Output 1:
4.5
Here is my Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double average = 0;
int a = scanner.nextInt();
int b = scanner.nextInt();
Problem: Throws Arithmetic Exception
What is the problem?
Your variable i loops from -5 to 12. Then, you divide (a + b) / i (line 14).
0 is between -5 and 12. Thus, you will eventually divide by zero.
(I assume that line 13 is supposed to prevent this, but the way you have written it, it does not. In fact, 0 is among the very few values of i for which line 14 will actually be executed.)
According to your sample input and sample output, you need to add all the numbers in the range that are divisible by 3 and divide that total by how many different numbers are in the range.
Between -5 and 12, the numbers that are divisible by 3 are:
-3, 0, 3, 6, 9, 12
When you add them all together, you get 27.
And there are 6 different numbers altogether.
So the average is 27 divided by 6 which gives 4.5
Now for the code.
import java.util.Scanner;
public class RangeAvg {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter lower bound: ");
int a = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter upper bound: ");
int b = scanner.nextInt();
int lower = Math.min(a, b);
int upper = Math.max(a, b);
int total = 0;
int count = 0;
for (int i = lower; i <= upper; i++) {
if (i % 3 == 0) {
System.out.println(i);
total += i;
count++;
}
}
System.out.println("total = " + total);
System.out.println("count = " + count);
if (count > 0) {
double average = (double) total / count;
System.out.println("average = " + average);
}
else {
System.out.printf("No numbers divisible by 3 between %d and %d%n", lower, upper);
}
}
}
Below is a sample run:
Enter lower bound: -5
Enter upper bound: 12
-3
0
3
6
9
12
total = 27
count = 6
average = 4.5
I've written some code that has a scanner read from a text file on my computer, but when running the code, the scanner only reads every other number that's in the text file.. any ideas?
Note: For the grades.txt, this is the file
"3 8 1 13 18 15 7 17 1 14"
import java.util.*;
import java.io.*;
public class GradeAverage
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("C:\\Users\\Media - Graphics\\Documents\\SCHOOL\\NCVPS\\GradeAverage\\grades.txt"));
int i = 0;
int sum = 0;
int lineNumber = 0;
int average = 0;
while(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
lineNumber++;
}
System.out.println("The sum of the numbers: "+sum);
System.out.println("The number of scores: "+lineNumber);
average = sum/lineNumber;
System.out.println("The average of the numbers: "+average);
}
}
Here's what it outputs:
3
1
18
7
1
The sum of the numbers: 67
The number of scores: 5
The average of the numbers: 13
Every time you call nextInt() in your loop, you consume one int. So when you do
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
You consume two int(s). You want something like
int t = scanner.nextInt();
System.out.println(t);
sum += t;
Also your average is currently an int (I would expect a float or double).
double average = sum/(double)lineNumber;
Don't forget to remove int average = 0; (or modify this and average accordingly).
I am fairly new to java and I'm trying to code to find the average. I understand that the average is adding all the numbers and then dividing the sum by the number of numbers but I'm not really sure how to code that. My guess is that I'd need a for loop but I don't know what to do from there. The program basically asks for a file to be read and then calculate the average. Here's the code I have so far:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Calculations
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));
int length = reader.nextInt();
double [] num = new double[length];
double [] num2 = new double[length];
System.out.println("The numbers are:");
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
System.out.println(num[i]);
}
}
}
The file I would be using is list.txt which contains:
20
1.1 2 3.3 4 5.5 6 7 8.5 9 10.0
11 12.3 13 14 15.5 16.1 17 18 19.2 20.0
The mean should be 10.625. Any help is deeply appreciated. Thank you in advance.
Just introduce a new variable sum, initialize it to 0, and add the elements to the variable while you are printing them.
System.out.println("The numbers are:");
double sum = 0; //new variable
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
sum += num[i];
System.out.println(num[i]);
}
sum /= (double) length; //divide by n to get the average
System.out.print("Average : ");
System.out.println(sum);
It appears that you're simply having trouble computing the average; I'll address that issue here:
In Java 7 and below, use a for loop:
double sum = 0; //declare a variable that will hold the sum
//loop through the values and add them to the sum variable
for (double d : num){
sum += d;
}
double average = sum/length;
In Java 8 you can use a Stream to compute the average
double sum = Arrays.stream(num).sum(); //computes the sum of the array values
double average = sum/length;
In my program Logic is like:--
Input Addition with Output(result)
2 3 5
3 3+4 10
4 3+4+4 15
5 3+4+4+4 20
6 3+4+4+4+4 25
So, I have made:--
import java.util.Scanner;
public class Addition {
public static void main( String[] args) {
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int result=0;
System.out.print("Enter a number: ");
int inputNumber = s.nextInt();
if(inputNumber==2){
result = inputNumber+3;
}
else{
Addition c=new Addition();
int j = inputNumber-2;
int power=c.pow(4,j);
result = inputNumber+3+power;
}
System.out.print(result);
}
int pow(int c, int d)
{
int n=1;
for(int i=0;i<d;i++)
{
n=c*n;
}
return n;
}
}
In this program I am getting result:--
Input Output(result)
2 5
3 10
4 23
5 72
why? What Am I doing wrong??
You're confusing 'power of' with multiplication.
int power=c.pow(4,j);
should simply be:
int power= 4 * j;
You are calculating j correctly, its value will be 1 for inputNumber 3, 2 for inputNumber 4 and so on ...But You are not using it correctly. Note we are not adding powers of 4(4,16,64..), we are simply adding multiples of 4 in increasing order(4,8,12,..). So you should be adding 4*j to calculate the result
Change your code as follows:-
int j = inputNumber-2;
int multiple=4*j;
result = inputNumber+3+multiple;
Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class