Separate odd even from string - java

The below is the question:
Get comma separated String of numbers from user and print the set of odd numbers and even numbers.
sample input:
1,2,3,4,5,6,7,8,9,10
Sample output:
Odd Numbers:
1,3,5,7,9
Even Numbers:
2,4,6,8,10
Sample input:
20,30,40
Sample output:
Even Numbers:
20,30,40
My code:
class OddEv{
public static void main(String args[]){
String s;
Scanner in=new Scanner(System.in);
s=in.nextLine();
for(int i=0;i<s.length();i++){
if(s.charAt(i)%2==0){
System.out.print(s.charAt(i));
}
if(s.charAt(i)%2!=0){
System.out.print(s.charAt(i));
}
}
but I am not getting the right answer. What changes should I bring to get the right output according to the question
actually I don't know java very well so I don't know what to do here

You can try this simple solution, without using any other concepts like regex. For this, you can split your string and store it in a string array, and than iterating over an array you can check whether the number is odd or even. Following code will store all the even and odd numbers from your string into the array named even and odd.
String s = "1,2,3,4,5,6,7,8,9,10";
int even[] = new int[10];
int odd[] = new int[10];
String ar[] = s.split(",");
int j=0,k=0,oddChecker=0,evenChecker=0;
for(int i=0;i<ar.length;i++){
if(Integer.parseInt(ar[i])%2 == 0){
even[j] = Integer.parseInt(ar[i]);
++j;
evenChecker = 1;
}
else{
odd[k] = Integer.parseInt(ar[i]);
++k;
oddChecker = 1;
}
}
if(oddChecker == 0){
System.out.println("even");
System.exit(0);
}
if(evenChecker == 0){
System.out.println("odd");
System.exit(0);
}
System.out.println("Even numbers:");
for(int i=0;i<j;i++){
if(i!=j-1){
System.out.print(even[i]+",");
}
else{
System.out.print(even[i]);
}
}
System.out.println();
System.out.println("Odd numbers:");
for(int i=0;i<k;i++){
if(i!=k-1){
System.out.print(odd[i]+",");
}
else{
System.out.print(odd[i]);
}
}
Output:
Even numbers:
2,4,6,8,10
Odd numbers:
1,3,5,7,9
Don't forget to convert String to Integer when checking the condition and adding numbers to arrays. For that I've used Integer.parseInt(your_string).

use two ArrayList of Integer for odds and evens, and change String s to String []s then use userInput.split(",") to separate numbers. parse strings in s to integer using Integer.parseInt(str) method then use if statement to determine number is odd or even and add them to arraylists.
public static void main(String args[]) {
String s[];
Scanner in = new Scanner(System.in);
s = in.nextLine().split(",");
ArrayList<Integer> odds = new ArrayList<>();
ArrayList<Integer> evens = new ArrayList<>();
for (String item : s) {
int number = Integer.parseInt(item);
if (number % 2 == 0) {
evens.add(number);
} else {
odds.add(number);
}
}
}
you can use following code to print results in output:
System.out.println("Even Numbers:");
System.out.println(Arrays.toString(evens.toArray()).replaceAll("[\\p{Ps}\\p{Pe}]", ""));
System.out.println("Odd Numbers:");
System.out.println(Arrays.toString(odds.toArray()).replaceAll("[\\p{Ps}\\p{Pe}]", ""));
sample input:
10,11,12,13,14,15,16,17,18,19,20
sample output:
Even Numbers:
10, 12, 14, 16, 18, 20
Odd Numbers:
11, 13, 15, 17, 19

hope this solves your problem
public class CommaSeperatedNum {
public static void main(String args[]){
String s;
Scanner in=new Scanner(System.in);
s=in.nextLine();
String numarray[] = s.split(",");
int odd[] = new int[20];
int oddcnt=0;
int even[] = new int[20];
int evencnt =0;
for(int i=0;i<numarray.length;i++)
{
if( Integer.parseInt((numarray[i]).trim())%2 ==0){
odd[oddcnt] = Integer.parseInt(numarray[i].trim());
oddcnt++;
}
{
even[evencnt] = Integer.parseInt(numarray[i].trim());
evencnt++;
}
}
System.out.print("Odd Numbers : " );
for (int i = 0; i < odd.length && odd[i] != 0; i++) {
System.out.print(odd[i]+" " );
}
System.out.println();
System.out.print("Even Numbers : " );
for (int i = 0; i < even.length && even[i] != 0; i++) {
System.out.print(even[i]+" " );
}
}

Following is a more functional solution with less moving parts:
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String[] split = in.nextLine().split(",");
String evens = Arrays.stream(split)
.filter(number -> Integer.parseInt(number) % 2 == 0)
.collect(Collectors.joining(","));
String odds = Arrays.stream(split)
.filter(number -> Integer.parseInt(number) % 2 != 0)
.collect(Collectors.joining(","));
System.out.println("Even Numbers:\n" + evens);
System.out.println("Odd Numbers:\n" + odds);
}
Yeah, it's quite inefficient, I know. There's probably a better way to do it, but I just wanted the OP to get a hint of how descriptive and simple a code can be.

a lambda with partitioningBy does the separation
it depends only on the last digit whether a string represents an even or odd number
a conversion into a numerical value is not necessary
String inp = "1,2,3,4,5,6,7,8,9,10";
String[] nums = inp.split( "," );
Map<Boolean, List<String>> map = Arrays.stream( nums ).collect(
partitioningBy(s -> "02468".indexOf(s.charAt(s.length() - 1)) >= 0));
System.err.println( "even: " + map.get( true ) );
System.err.println( "odd: " + map.get( false ) );
even: [2, 4, 6, 8, 10]
odd: [1, 3, 5, 7, 9]

Related

I want to print even and odd number from an input array list

I want to print even and odd number from an input array list.
Input : 1 2 3 4
Expected output
Even number is : 2 4
Odd number is : 1 3
but i get my output is
Odd number is [1]
Even number is [2]
Odd number is [1, 3]
Even number is [2, 4]
I think is the for loop there might put wrongly?
import java.util.ArrayList;
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
ArrayList<Integer> even = new ArrayList<Integer>();
ArrayList<Integer> odd = new ArrayList<Integer>();
int[]number=new int[10];
Scanner read = new Scanner (System.in);
System.out.print("Enter number :" );
for(int i=0;i<number.length;i++){
number[i]=read.nextInt();
if(number[i]%2==0){
even.add(number[i]);
System.out.println("Even number is " + even);
}
else{
odd.add(number[i]);
System.out.println("Odd number is " + odd);
}
}
}
}
The program is working correctly, but your println statements should go after the for loop rather than inside of it. The output shows that it's printing the lists of odd and even numbers as they're generated, rather than after the whole input set has been processed.
...
for(int i=0;i<number.length;i++){
number[i]=read.nextInt();
if(number[i]%2==0)
even.add(number[i]);
else
odd.add(number[i]);
}
System.out.println("Even number is " + even);
System.out.println("Odd number is " + odd);
...
public static void main(String[] args) {
ArrayList<Integer> even = new ArrayList<Integer>();
ArrayList<Integer> odd = new ArrayList<Integer>();
int[] number = new int[10];
Scanner read = new Scanner(System.in);
System.out.print("Enter number :");
for (int i = 0; i < number.length; i++) {
number[i] = read.nextInt();
if (number[i] % 2 == 0) {
even.add(number[i]);
} else {
odd.add(number[i]);
}
}
System.out.println("Even number is :");
for (Integer e : even) {
System.out.print(e + " ");
}
System.out.println("\nOdd number is :");
for (Integer o : odd) {
System.out.print(o + " ");
}
}
You are printing inside the for loop where you are reading the user input. Print your data after you take the input as above.
Also note the difference in the way the output is formatted using println and print methods.

String of only even numbers and only odd numbers

I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input

Program about friendly numbers

I am working on some additional exercises for my introduction to programming class, and I cannot figure out what I did wrong regarding the following question:
(Friendly Numbers) An integer is said to be friendly if the leftmost
digit is divisible by 1, the leftmost two digits are divisible by 2,
and the leftmost three digits are divisible by 3, and so on. The
n-digit itself is divisible by n. For example, the number 42325 is
friendly because 4 is divisible by 1, 42 is divisible by 2, 423 is
divisible by 3, 4232 is divisible by 4, and 42325 is divisible by 5.
Write a general method (with or without recursion) with the name
isFriendly that determines whether or not the number is “friendly”
. Write a main method that tests the method isFriendly.
My program is as follows:
import java.util.Scanner;
public class Question4 {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = in.nextLine();
}
public static String isFriendly(String input){
int n = input.length();
int number = Integer.parseInt(input);
String output = "";
for (int i = 0; i<=n; i++){
if (((n/10*i)%i) != 0 ){
output = "Friendly";
}else{
output = "Not friendly";
}
return output;
}
}
}
The error given is: "The result must return a result of type String".
What can I do to solve this problem, and can I write this program in a more efficient way?
Thank you so much for considering this question!
try this:
public static String isFriendly(String input) {
if (input == null || input.length() == 0) return "Not friendly";
int n = input.length();
int number = Integer.parseInt(input);
for (int i = 0; i<=n; i++) {
if (((n/10*i)%i) == 0 ) {
return "Not friendly";
}
}
return "Friendly";
}
Please try my code here I use StringBuilder class to get each actual int then convert it to string then convert it to int everytime the loop iterate
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = in.nextLine();
System.out.println(isFriendly(input));
}
public static String isFriendly(String input)
{
int n = input.length();
String output = "";
StringBuilder sb = new StringBuilder("");
int myIntOutput=0;
for (int i = 0; i<n; ++i)
{
sb.append(input.charAt(i));
if (Integer.parseInt(sb.toString())%(i+1)==0)
{
myIntOutput++;
}
}
if(myIntOutput==n)
{
output="Friendly";
return output;
}
else
{
output="Not Friendly";
return output;
}
}
if this help you consider accepting it as an answer

Inserting dashes between two odd numbers

folks. In my program I take a user input of numbers of a String type and put dashes between two odd numbers. For example:
Input = 99946 Output = 9-9-946
Input = 56730 Output = 567-30
But in my code, if I, for example, write 9933444 then the ouput that I'm getting is: 9-9-9-3-3-3-344444. It correctly separates the odd numbers by dashes but also adds extra numbers. What could be causing this bug ?
import java.util.Arrays;
import java.util.Scanner;
public class DashInsert {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the numbers: ");
String myString = kbd.nextLine();
char[] numbers = myString.toCharArray();
String result = "";
for(int i = 1; i < numbers.length; i++)
{
int value1 = Character.getNumericValue(numbers[i]);
int value2 = Character.getNumericValue(numbers[i-1]);
if(value1 % 2 != 0 && value2 % 2 != 0)
{
result += numbers[i-1] + "-" + numbers[i] + "-";
}
else
result += numbers[i-1] + "" + numbers[i];
}
System.out.println(result);
}
}
There is a trivial one-line solution:
str = str.replaceAll("(?<=[13579])(?=[13579])", "-");
This works by matching between odd numbers and replacing the (zero-width) match with a dash. The regex is a look behind and a look ahead.
It can be done without look arounds by capturing the odd digits and putting them back using a back reference:
str = str.replaceAll("([13579])([13579])", "$1-$2");
Both solutions achieve the same result.
The code can be simplified a bit (as well as solve the "double char" bug):
String str = "9933444";
char[] numbers = str.toCharArray();
String result = "";
for(int i = 1; i < numbers.length; i++)
{
int value1 = Character.getNumericValue(numbers[i-1]);
int value2 = Character.getNumericValue(numbers[i]);
result += value1;
if(value1 % 2 != 0 && value2 % 2 != 0) {
result += "-";
}
}
result += numbers[numbers.length - 1];
System.out.println(result);
OUTPUT
9-9-3-3444
The reason for the "double char" bug is that every loop prints both the items on the places i-1 and i. which means that i will be printed again on the next loop (where it will become i-1).
In case you're using Java 8 - you can use a Stream do something that looks more like what you were originally trying to do:
public static void main(String[] args){
String str = "9933444";
List<String> lst = Arrays.asList(str.split(""));
String res = lst.stream().reduce((a,b) -> {
if (isOdd(a) && isOdd(b)) {
return a + "-" + b;
}
else {
return a + b;
}
}).get();
System.out.println(res);
}
// grep the last digit from the string and check if it's odd/even
public static boolean isOdd(String x) {
if (x.length() > 1) {
if (x.substring(x.length()-1).equals("-")) {
x = x.substring(x.length()-3, x.length()-2);
}
else {
x = x.substring(x.length() - 1);
}
}
return Integer.parseInt(x) % 2 == 1;
}
OUTPUT
9-9-3-3444
The bug is caused by the fact that, even though you are looping through your list of numbers one at a time, you write out two numbers with each loop iteration. Logically, this design will always yield repeated numbers.
Either change your loop to iterate by twos, or print a single number in each loop iteration.
Don't bother concatenating two odd numbers with the "-" in between them, during the evaluation, just add the "-" after the number that you're checking in each iteration.
public static void main(String[] args) throws Exception {
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the numbers: ");
String myString = kbd.nextLine();
char[] numbers = myString.toCharArray();
String result = "";
for(int i = 0; i < numbers.length; i++) {
int value1 = Character.getNumericValue(numbers[i]);
int value2 = i + 1 < numbers.length
? Character.getNumericValue(numbers[i + 1])
: 0;
if(value1 % 2 != 0 && value2 % 2 != 0) {
result += numbers[i] + "-";
} else {
result += numbers[i];
}
}
System.out.println(result);
}
Results:
Input: 99946 Output: 9-9-946
Input: 56730 Output: 567-30
Input: 9933444 Output: 9-9-3-3444

Converting a user input word into a unicode array in Java

So I am having a problem figuring out how to convert a word that the user input into a int array that has each of the letters of the word in their own unicode values (so something like "A" would turn into 65 in the array). I was thinking of one way that this could be done is that first I have the word input by the user split up into separate chars (so the String "And" would first be split up into chars "A", "n", "d", and then would turn into ints 65, 110, 100 when they are put into the int array). The problem is that I am lost on where to go. I am not sure how I would split the word up into separate chars, and then have those chars be converted, and go into an int array. Any help is greatly appreciated! Also just as I side note I need to be able to find the maximum, minimum, and average of all the values as well.
Try this:
public static void stringToArray (){
Scanner in = new Scanner(System.in);
System.out.print("Input String: ");
String input = in.nextLine();
Integer[] lista = new Integer[input.length()];
for(int i=0;i<input.length();i++) {
lista[i] = input.codePointAt(i);
System.out.print(lista[i] + " ");
}
System.out.print("\nArray descending order: ");
Arrays.sort(lista, Collections.reverseOrder());
for(int i=0;i<input.length();i++)
System.out.print(lista[i] + " ");
if (lista.length>0) {
int min=lista[0];
int max=lista[0];
int sum=0;
int avg;
for(int i=0;i<lista.length;i++){
if (lista[i]> max) max=lista[i];
if (lista[i]< min) min=lista[i];
sum += lista[i];
}
avg=sum/lista.length;
System.out.println("\nThe maximun value is: "+max);
System.out.println("The minimun value is: "+min);
System.out.println("The average value is: "+avg);
}
}
This will add each character to an integer array:
public static int[] codepoints(String str) {
int[] arr = new int[str.length()];
for (int i = 0; i < arr.length; i++) {
arr[i] = str.charAt(i);
}
return arr;
}
DEMO
One possible solution would be to iterate the characters in your String and copy them into a new int array like,
public static int[] getPoints(String str) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
int[] out = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
out[i] = chars[i];
}
return out;
}
And then you might test it like,
public static void main(String[] args) {
System.out.println(Arrays.toString(getPoints("And")));
}
Output is (as requested)
[65, 110, 100]

Categories

Resources