Hello! I am looking for some assistance with adding code to my program for handling non numeric data/user input, specifically letters. The program is coded in java.

import java.util.*;

public class AnArray
{
    public static void main (String [] args)
    {
        // creates an array of interegers between 0 and 50
        int element[] = new int [51];

        // scanner for input
        Scanner scan = new Scanner(System.in);

        int input;

        // do/while loop for inputs

        do
        {
            System.out.println("Enter a number between 0 and 50. Enter -1 to quit.");

            input = scan.nextInt();  // replace this line with new methodPhil sends

            if(input == -1)
            {
                System.out.println("Invalid input");
            }
            else if(input > 50)
            {
                System.out.println("Invalid input");
            }
            else if (input < -1)
            {
                System.out.println("Invalid input");
            }
            else if(input == -1)
            {
            // quits loop
            }
            // accumulator of frequencies of the numbers
            else
            {
                element[input]++;
            }

    }

        // sentinel loop -1 to quit the loop
        while(input != -1);
        // header for table
        System.out.println("Number Entered" + "  " + "Frequency");
        System.out.println("--------------" + "  " + "---------");
        // numbers entered
        for(int i = 0; i < element.length; i++)
        {
            // so numbers entered do not show up
            if(element[i] > 0)
            {
                System.out.println(i + "               " + element[i]);
            }
        }
    }
}

Recommended Answers

All 3 Replies

You asked for help but didn't tell what you need help on. That is, as it's your assignment no one writes your code so let's hear where you feel it's failing.

Also, you could put it in IDEONE so others can edit and run it.

as far as I can tell, the comments in your code already hint to what you should do next.
for non- Integer input, don't use the nextInt(); method, and don't assign the value to an int.

I am unclear on what specific type of input you want to take in.

You say letters. Do you mean chars that are specifically A-Z and a-z? Do you mean a string of characters without spaces? Or do you want a string of characters with spaces?

Each one requires a slightly different scanner implementation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.