Search code examples
javastringcharnumericvalue-of

Read number as string sequence and convert first and last to an Integer


I'm new to programming and I've just started learning Java.
I want to do a program that's

  • asks the user to enter a string that contains a sequence of numbers and then
  • takes the first and the last numbers of that sequence and
  • check if these numbers are an odd or even

Based on that information it will do certain things.

Here's my code:

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    String n = kb.nextLine();
    Integer x = Integer.valueOf(n.charAt(n.length() - 1));
    Integer y = Integer.valueOf(n.charAt(0));
    String out;
    if (y % 2 == 0 && x % 2 == 0) {
        out = "$" + n.substring(1, n.length() - 1) + "$";
    } else if (y % 2 > 0 && x % 2 > 0) {
        out = "X" + n.substring(1, n.length() - 1) + "X";
    } else if (x == 0); {
        out = n.substring(0, n.length() - 1) + "#";
    }
    System.out.println(out);
}

I'm not sure what's the problem. I think its about those two lines

Integer x = Integer.valueOf(n.charAt(n.length()-1));
Integer y = Integer.valueOf(n.charAt(0));

The output value is different than the one in the input..


Solution

  • The Scanner code can be improve and there is indeed a problem with your conversion. Your code gets the ASCII value of those symbols. Try it like this:

    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner console = new Scanner(System.in);
    
        while (console.hasNextLine()) {
            String n = console.nextLine();
            Integer x = Integer.parseInt(n.substring(n.length()-1));
            //System.out.println(x);
            Integer y = Integer.parseInt(n.substring(0, 1));
            //System.out.println(y);
            String out;
            if (y % 2 == 0 && x % 2 == 0)
            {
                out = "$"+n.substring(1, n.length()-1)+"$";
            }
            else if (y % 2 > 0 && x % 2 > 0) {
                out = "X" +n.substring(1, n.length()-1) + "X";
            }
            else if (x == 0); 
            {
            out = n.substring(0, n.length()-1)+ "#";
            }
            System.out.println(out);
        }
    }
    

    Online Demo

    I've used substring()/parseInt() but there are many ways to convert a string or char to an Integer.