package com.codegym.task.task06.task0606;
import java.io.*;
import java.util.Scanner;
/*
Even and odd digits
*/
public class Solution {
public static int even;
public static int odd;
public static void main(String[] args) throws IOException {
//write your code here
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(System.in));
String sNum= bufferedReader.readLine();
int nNum=Integer.parseInt(sNum);
int l=sNum.length();
int a[]= new int[l];
int i=0;
a[i]= nNum;
for (i=0;i<l;i++) {
if (a[i] % 2 == 0) {
even++;
} else
odd++;
}
System.out.println("Even: "+even+" Odd: "+odd);
System.out.println(l);
}
}
Tried to do this with arrays.help me where i m making mistake.
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Christopher Gill
7 June 2019, 09:24
public class Solution {
public static int even;
public static int odd;
public static void main(String[] args) throws IOException {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String xx=reader.readLine();
int num=Integer.parseInt(xx);
for(int i=0;i<xx.length();i++)
{
if(num%2==0)
{
even=even+1;
}
else
{
odd=odd+1;
}
num=num/10;
}
System.out.println("Even: "+even +" Odd: "+odd);
//write your code here
}
}
0
Guadalupe Gagnon
4 February 2019, 15:31
This is an interesting approach to solving this problem. Unfortunately numbers do not provide individual access to their digits by array, however String literals do. This means that the line that first reads in the number, stored in String variable sNum, does have access to the individual characters. On top of this, the character values of "0"-"9" have literal numerical values of 48-57 (they line up even and odd properly without converting).
You can access the individual characters with <StringVariable>.charAt(index). Change your code to not convert anything to a number, then make the change to get individual characters at the 'if' line like so:
Read this to get a better understanding of ASCII:
http://www.asciitable.com/ 0
shaan mohd khan QA Automation Engineer at mphasis Ltd
5 February 2019, 05:53
thanx a lot.
0