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);
Related
I tried to print Armstrong numbers between two given integers and my code iterates only one time in for and exits after that, can anyone identify why?
I am attaching my code here
public static void main(String[] args) {
//armstrong no. bw two integers given
Scanner in= new Scanner(System.in);
System.out.println("Enter 1 no. ");
int fno= in.nextInt();
System.out.println("Enter 2 no.");
int sno= in.nextInt();
int i,sum=0,digits,count=0;
for(i=fno+1;i<sno;++i)
{
//to find no. of digits in i
digits=i;
while(digits!=0){
digits/=10;
++count;
}
//to find a^^n
int times=0;
int dig,n,temp;
n=i;
while (n!=0){
dig=n%10;
temp= (int) Math.pow(dig,count);
sum=sum+temp;
n/=10;
}
if (sum==i)
System.out.print(i+" ");
}
}}
Your sum is outside of your for, and you aren't resetting it. This means on the second iteration sum !=0 and everything will be messed up. Also I suggest using i++ instead of ++i and leaving spaces between cycles, conditions and variable definitions. You should also reset count after each iteration, so your final code should look so your code should look something like this
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter 1 no. ");
int fno = in.nextInt();
System.out.println("Enter 2 no.");
int sno = in.nextInt();
int sum = 0, digits, count = 0;
for(int i=fno+1;i<sno;++i) {
//to find no. of digits in i
digits=i;
while(digits!=0){
digits/=10;
++count;
}
//to find a^^n
int times=0;
int dig,n,temp;
n=i;
while (n != 0){
dig = n%10;
temp = (int) Math.pow(dig,count);
sum = sum + temp;
n /= 10;
}
if (sum == i) {
System.out.print(i + " ");
}
sum = 0;
count = 0;
}
}
}
I tried to edit TCoder12's post. But It was not saved due to this error:
The edit queue is full at the moment - try again in a few minutes!
So, I decided to post another answer. As TCoder12 said your main problem is that you mistakenly put some instructions inside the for loop, and mistakenly put some instructions out of for loop.
Try not to use extra variables and instructions to reduce the complexity of your code and the risk of making unwanted errors. Also, use appropriate names for variables:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter 1 no. ");
int startNumber = input.nextInt();
System.out.println("Enter 2 no.");
int endNumber = input.nextInt();
for(int eachNumber = startNumber; eachNumber < endNumber; eachNumber++) {
int sum = 0, count = 0;
int numberOfDigits=String.valueOf(eachNumber).length();
//to find a^^n
int temp = eachNumber;
while (temp != 0){
sum += (int) Math.pow(temp % 10, numberOfDigits);
temp /= 10;
}
if (sum == eachNumber) System.out.print(eachNumber + " ");
}
}
}
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.
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]);
I'm trying to create a code that lets the user determine the size and elements of an array and then print it out. So far I have this.
import java.util.Scanner;
public class test3 {
public static void main (String[] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
System.out.println(values[i]);
}
}
}
I don't know if it is right because when a user inputs the size and then the elements, the code is just displaying the element as the user inputs it. For example,
input how many numbers you want to find the median for
5
please enter 5 numbers
3//user input
3//what is displayed.
I want to make it so that the user inputs all of their numbers and THEN it displays the inputed numbers as an array.
We are not allowed to use the array class by the way.
import java.util.Scanner;
public class test3 {
public static void main (String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
}
for (int i = 0; i < num; i++) {
System.out.println(values[i]);
}
}
}
Your for loop will execute for as many number as the user has entered, in your test case 5. Every iteration will take a number from the keyboard input, place it into the array and display it. Since you want to capture all the numbers first and then want to display them you should remove
System.out.println(values[i]);
from the for loop and place that into another for loop to display the numbers like so
for(int x=0 ;i < num ; i++)
{
System.out.println(values[x]);
}
This way the first loop will gather all the numbers and after the numbers are collected the second loop will display the numbers one by one iterating over the array.
Hope this helps!
Cant find the error in coins array. when i tried to initialize the array with n+10 elements it worked. but actually it should be using only the n elements. where am i getting it wrong?
import java.util.Scanner;
public class MaximumContiguousSum {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int amount, n;
System.out.print("Enter number of types of coins : ");
n = in.nextInt();
int[] coins = new int[n];
System.out.print("Enter coins values : ");
for(int i=0; i<n; i++){
coins[i] = in.nextInt();
}
System.out.print("Enter the amount : ");
amount = in.nextInt();
int[] arr = new int[amount+1];
arr[1]=1; arr[0]=0;
for(int i=2; i<=amount; i++){
arr[i]=100;
int j=0;
//Error in the following line
while(coins[j]<=i && j<n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
j++;
}
}
System.out.println("The number of coins to be used : " + arr[amount]);
in.close();
}
private static int min(int a, int b) {
// TODO Auto-generated method stub
return (a<b)?a:b;
}
}
Output:
Enter number of types of coins : 3
Enter coins values : 1 2 7
Enter the amount : 10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MaximumContiguousSum.main(MaximumContiguousSum.java:22)
You have an off-by-one error. Your line:
while(coins[j]<=i && j<=n)
Will try to grab coins[n] before it quits, and the final index of your array is actually n-1
Don't check greater than or equal on the error line
change this while(coins[j]<=i && j<n){ to while(coins[j]<i && j<n){ in your code
This
int[] coins = new int[n];
declares coins to have n elements with maximum index n - 1
this
while(coins[j]<=i && j<=n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
Will attempt to access coins[n] when j = n which is past the end
Edit: arr[i-coins[j]] is protected against.
finally this:
while(coins[j]<=i && j<n)
should be this
while(j < n && coins[j]<=i)