I am writing a program that takes integers from the user and stores them in an array, then calculates the arrays average.
The array can hold at maximum 100 integers. If the user wants to do less than 100, they hit CTRL+Z (or Command+D) to stop prompting for numbers.
Here is my main method:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] array = new int[100];
System.out.printf("Enter a stream of numbers: ");
readIntoArray(input, array);
for (int i = 0; i<=array.length;i++) {
array[i] = input.nextInt();
}
}
And here is the method that reads into the array.
public static int readIntoArray(Scanner input, int[] nums) {
int count = 0; //number of elements entered into the array
while (count <= nums.length && input.hasNextInt()) {
nums[count]=input.nextInt();
count++;
}
return count;
}
And here is the average method.
public static void printAboveAverage(int[] nums, int size) {
double average;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum =+ nums[i];
}
average = sum/size;
System.out.print(average);
What am I doing wrong?
I keep getting a NoSuchElementException immediately after hitting CTRL+Z.
Here:
while (count <= nums.length && input.hasNextInt()) {
This loop will probably stop when you hit ctrl-z and there is no more int. But next statement is:
array[i] = input.nextInt();
In other words: your read method seems to correctly check if enough numbers are in, or if the scanner stopped having input.
But your main method ignores that, and just asks for another number from the scanner.
So it could be as simple as: just drop that for loop within your main method that wants more numbers.
I suggest you have a try and catch if it gives you an Exception, maybe use it to get unlimited numbers (dont use the max 100 numbers) and when he finds the exception he counts the average?
Not the best solution, excpetion are not meant to always be used, Thanks to domsson for the reminder
something like:
try{
//Get the numbers
}
catch(Exception e){
//Calculate the average
}
Just thinking out loud, it may help you.
Related
This code is to input n integer values and calculate the no. of even and odd values among those inputted values.
This java code shows ArrayIndexOutOfBoundsException when used do..while loop, however when used for loop it worked fine. Haven't changed any thing just rearranged the syntax so as to convert for loop into do while loop.
FOR LOOP:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
}
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
The above code works fine and gives suitable output.
DO...WHILE LOOP:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0, i=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
do
{
a[i] = sc.nextInt();
i++;
} while (i<n);
do
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
i++;
} while (i<a.length);
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
The above code has a runtime exception i.e.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at EvenOddCount.main(EvenOddCount.java:20)
In your original code, you had two separate i variables:
for(int i=0;i<n;i++)
...
for(int i=0;i<a.length;i++)
In your do/while version, you've got one i variable. Once you've gone through the first loop, the value of i will be n - but you start on the second loop without resetting it to 0, so on the very first iteration it will be out of range.
You can fix that by adding:
i = 0;
just before the second do/while loop, but be aware that you'll still have a problem (even in the first loop) if n is 0, because you're not checking the condition until the end of the iteration. If you use:
while (i < n)
and
while (i < a.length)
instead, that will check the condition before the first iteration, so it will execute 0 times when n is 0. (You still need to reset i to 0 before the second loop though.)
U need to reset the value of i :
do
{
a[i] = sc.nextInt();
i++;
} while (i<n);
i =0;
do
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
i++;
} while (i<a.length);
I am trying to multiply two largest numbers from an array of numbers. Its working fine for small numbers.
Correct input / output - this is working:
3 10 2 8
80
Correct input / output - this is failing:
2 100000 90000
9000000000
My output is however 10000000000 instead.
Can someone tell me what is wrong in my code?
public static Long sumPairwise(Long[] numbers){
int index=0;
int n = numbers.length;
for(int i=1;i<n;i++){
if(numbers[i]>numbers[index])
index=i;
}
numbers[n-1]= numbers[index];
index=0;
for(int j=1;j<n-1;j++){
if(numbers[j]>numbers[index])
index=j;
}
numbers[n-2]=numbers[index];
Long product = (numbers[n-2])*(numbers[n-1]);
return product ;
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long numbers[] = new Long[n];
for (int i=0;i<n;i++)
numbers[i]= sc.nextLong();
System.out.println(sumPairwise(numbers));
}
There is a bug in your code: numbers[n-1] may well contain the second highest number. You are overwriting that number with the highest number in your code, before you try and put it at the first to last position.
One way to overcome this is to sort the array using Arrays.sort, this way you are sure that the last two numbers are the highest and second highest number.
public static long multiplyLargestTwoNumbers(long[] numbers) {
long[] sortedNumbers = numbers.clone();
Arrays.sort(sortedNumbers);
int size = numbers.length;
// multiply highest and second highest number
return sortedNumbers[size - 1] * sortedNumbers[size - 2];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long numbers[] = new long[n];
for (int i = 0; i < n; i++) {
numbers[i] = sc.nextLong();
}
System.out.println(multiplyLargestTwoNumbers(numbers));
}
Other changes:
using long instead of Long: try and use primitive types when the objective reference types are not needed (you need Long if you want to use e.g. a List because a List can only hold object references);
spaced out for loops, please use white space;
renamed method, as it does't add anything pairwise;
used curly braces for for loop in main method;
removed spurious parentheses in part that performs multiplication.
You might also introduce an if statement that first checks if the numbers array does indeed contain at least two elements. This is called a guard statement.
Finally remember that byte, short and long all contain signed numbers of a specific bit size. Basically you are performing calculations modulus 2^n where n is the bit size. If the value is too large it may overflow and return an incorrect result. For that you need BigInteger.
You are replacing the original number in that index with another number.
That is causing the issue.
Please just simply find the max 2 numbers from below logic and multiply.
Also, remember to close scanner.
Here the simple solution. This will work only for positive integers.
import java.util.Scanner;
public class Snippet {
public static long multiplyHighestTwoValues(Long[] numbers) {
long maxOne = 0;
long maxTwo = 0;
for (long n : numbers) {
if (maxOne < n) {
maxTwo = maxOne;
maxOne = n;
} else if (maxTwo < n) {
maxTwo = n;
}
}
long product = maxOne * maxTwo;
return product;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long numbers[] = new Long[n];
for (int i = 0; i < n; i++)
numbers[i] = sc.nextLong();
System.out.println(sumPairwise(numbers));
sc.close();
}
}
Instead of Long try to use BigInteger to multiply larger values that fit into long, otherwise your result may overflow.
Use BigDecimal instead for multiplying floating point numbers.
I'm quite new to java.
I'm trying out some things for a project but I don't get why this does not work.
The goal here is to let the user input numbers separated by spaces and end with a letter. The program then needs to count the even and odd indexed numbers and output which sum is larger.
I already made this successfully when the amount of numbers given was a constant, but now I want to make it adapt to the user input.
Because I want to put the numbers in an array I need to know the length of this array. To get this I want to count the amount of numbers the user puts in so I can create the appropriate length array.
For some reason the while loop does not end and keeps running. How do I count the amount of numbers put in?
EDIT
I've added in.next(); in the first while loop so it is not stuck at the first input element. This brings me to a further problem however of having two while loops trying to loop through the same input. I have tried to create a second scanner and resetting the first one, but it does not get the second loop to start at the first element. Previous answers show that this is not possible, is there a way to put this in one while loop while still using arrays to store the values?
P.S. The input values should be able to be any positive or negative integer.
Here is my complete code:
import java.util.Scanner;
public class LargerArraySum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = 0;
System.out.println("Enter your numbers seperated by spaces, end with a letter");
while(in.hasNextInt()) {
length++;
in.next();
}
System.out.println(length);
int arra[] = new int[length];
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
int evenSum = EvenArraySum(arra);
int oddSum = OddArraySum(arra);
if(evenSum<oddSum) {
System.out.println("The sum of the odd indexed elements is bigger");
} else if(oddSum<evenSum) {
System.out.println("The sum of the even indexed elements is bigger");
} else {
System.out.println("The sum of the odd and even indexed elements is equal");
}
}
public static int EvenArraySum(int[] a) {
int sum = 0;
for(int i=1;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the even indexed elements is: " + sum);
return sum;
}
public static int OddArraySum(int[] a) {
int sum = 0;
for(int i=0;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the odd indexed elements is: " + sum);
return sum;
}
}
add in.next(); in the loop. Actually you don't need array. You can sum even and odd indexed numbers while reading without saving them.
1) Your first while-loop does not work because the iterator is always checking for further numbers in from the same position.
Example:
Position 0 1 2 3 4 5
Value 1 3 5 7 9 0
At start the iterator points to position 0. If you call hasNextInt() it will check if position 1 is available, in this case it will be true. At this moment the interator still points to position 0. So you increase your length and do the same thing again, so you have an infinite loop.
To move the iterator to the next position you need to call nextInt().
2) You can't iterate over the same Scanner with a second while-loop in that way. If you would correct you first while-loop the iterator would point to position 5 (it reached the end of the scanner). So the check for hasNextInt() will be false and the second while-loop will not be entered.
3) The comments already mentioned it, you could use an ArrayList for this use case like so:
final ArrayList<Integer> input = new ArrayList<>();
while ( in.hasNextInt() ) {
input.add( in.nextInt() );
}
System.out.println( input.size() );
( or like kitxuli mentioned in his answer, dont even store the values, just count them in the first while-loop)
Your code has 2 major problems . The first and the second while loops lets take a look at your first loop .
while(in.hasNextInt()) {
length++;
}
your condition in.hasNextInt() made you insert input because no variable was initialized with in.nextInt but also returns either [true] or [false] so as long as its true it will add to the length variable without prompting you to insert a [new input] .so the code should look like.
Int length = 0;
int k ;
while(in.hasNextInt()) {
length++ ;
k = in.nextInt();
}
you insert the input into an initialized variable k for ex then prompt the user to further input into k after adding to [length] then the loop will check your condition without prompting user for input.
Lets look at your second while loop.
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
In in.NextInt() you are prompting the user to enter new input once again so you don't need int x.Not even the while loop .However you MUST declare a new scanner in this ex: I call it c .The code should look like this.
int [] a = new int [length];
Scanner c = new Scanner (System.in);
for(int i=0;i<length;i++) {
if (c.hasNextInt()){
a[i] = c.nextInt();
} else
break;
}
You must add the if statement because if you get an alphabet in the int array you will get an exception error .The array a[i] will not prompt the user.
Of course it isn't practical to make the user enter the values twice so a better code to implement without using ArrayList class which I think you may not know very well is by using an empty String .
NEW CODE :-
String g = "";
String j ="";
int y ;
int q=0;
int w = 0;
while (in.hasNextInt())
{
y = in.nextInt();
g =g+y+",";
q++;
}
int arra [] = new int [q];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(',')){
arra[w]=Integer.parseInt(j);
System.out.println(arra[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
Another even better code :-You just insert your numbers separated by spaces without a letter ,hit enter and the array is filled.
Scanner in = new Scanner (System.in);
String g = "";
String j ="";
int y ;
int q=0;
int i=0;
int w = 0;
System.out.println("inset your input separated by spaces");
g = in.nextLine();
while(i<g.length()){
if((g.charAt(i))==(' ')){
q++;
}
i++;
}
int a [] = new int [q+1];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(' ')){
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
So I've been tasked with creating a code that creates a predetermined array list for users to input up to over 100 integers with the option of using 0 to signify once their done with their inputs. However, when trying to call for say the minimum value, it just returns a value of 0. How would I properly format it so it compares it to all the value in the user inputted array list? Appreciate any help I can get! I added comments on the side to show which areas I have questions about or where I believe that the error lies.
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
String calc;
double[] numbers2; //An array for storing double values.
int[] numbers; // An array for storing the int values.
int count; // The number of numbers saved in the array.
int num; // One of the numbers input by the user.
int max;
int min;
/* Initialize the summation and counting variables. */
numbers2 = new double[100]; // Space for 100 doubles.
numbers = new int[100]; // Space for 100 ints.
count = 0; // No numbers have been saved
max = Integer.MIN_VALUE; //Properly initialized?
min = Integer.MAX_VALUE; //Properly initialized?
/*Start of min method. */
if (calc.equals("min")){
System.out.println("Enter up to 100 positive integers;
while (true) { // Get the numbers and put them in the array.
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break; } /*Zero marks the end of the input. All
have been inputted. */
else {
numbers[count] = num; // Put num in position count.
count++;
}
for (int i=0; i<numbers.length;i++) { //"For" statement needed here?
if (numbers[i] < min) {
min = numbers[i];}
}
}
System.out.println("Your minimum is : " + min);
}
}
}
Your for loop that finds the minimum should be after the while loop that reads the input, not inside it (since currently it goes over un-initialized elements of the array, so it always finds a 0 as the minimum). If you do that, you should also change the for loop to only iterate over the elements you assigned to the array (indices 0 to count-1), and not the entire array.
Alternately, you can remove the for loop and just put the
if (numbers[count-1] < min) {
min = numbers[count-1];
}
condition inside the while loop.
This will find the minimum in the same loop that reads the input.
Of course, if you do that, you don't need to store the elements in an array at all, so you can further simplify the code.
Here's a possible solution the keeps the array and the for loop :
while (count < numbers.length) { // avoid too many inputs
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break;
} else {
numbers[count] = num;
count++;
}
}
for (int i=0; i<count;i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?
Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.
The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.
You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?
I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)