dimanche 3 mars 2019

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.

Aucun commentaire:

Enregistrer un commentaire