I am trying to figure out how to distiguish if the user input was a string or a int.

The out put i am looking for is

please enter a string: cat
please enter a string: dog
please enter a string: hamster
please enter a string: 1234
please enter a string: quit

Number of strings: 4
Average string length: 4.25
Number of possible words: 3

So am not sure how check to see if the user entered numbers and then avarage it up. Below is what i have so far

Thank you for your time.

import java.io.*;
import java.util.Scanner;

public class rad {

public static void main(String[] args) throws IOException {

Scanner in = new Scanner(System.in);
String input;

double counter = 1;
double totalLength = 0;

System.out.printf("Please enter a string:");

input = in.next();
while (!input.equals("quit")){

    int length = input.length();

    totalLength += length;

System.out.printf("Please enter a string:");
input = in.next(); //waits for user to input more information


double finalCount = counter - 1;

System.out.printf("\nNumber of strings: %.1f\n", finalCount);

double averageLength = totalLength / finalCount;

System.out.printf("Average string length: %s\n total %s", averageLength, totalLength);

int numPossibleWords = 0;
System.out.printf("Number of possible words: %s", numPossibleWords);


Recommended Answers

All 6 Replies

how to distiguish if the user input was a string or a int.

Several ways to use the Scanner class. It has methods that will test what the user has typed in before the program tries to read in the data. These methods all begin with these 3 letters: has. See the API doc for the method names and what they do.

Thanks for the response. I was trying to use Integer.parseint() method but im not sure if i was using it correctly.

I don't see it in your code.
Can you post the code and explain what you are trying to do?

Hi. You can continue with what you're doing using the Integer.parseInt(). You can try parsing each of the user's input. If it throws an exception, then you can consider it as String. You may consider something like:

try {
} catch (Exception e) {
    System.out.println("It's a  string!")

You could try to catch all Exception, but in your case you should try NumberFormatException because it is direct to the exception thrown when a string is not a number is being parsed.

PS: If a user enters "+123" as an input, do you consider it as a number or a String? The Integer.parseInt() will not accept this string as a number but throws the NumberFormatException...
PSS: If a user enters "abc123" as an input, do you consider it as a possible word?

Thank you for all the help :) I got it

Be a part of the DaniWeb community

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