m bunn m bunn - 1 year ago 51
Java Question

Declaring a variable to store 3rd and 6th character of a String and tests if they are slashes

I am making a program where the user is asked to enter a month in format mm/dd/yyyy
I have to make sure the slash is in the 3rd and 6th positions.
IF IT IS NOT in the correct formats, in position 3 AND 6 (according to instructions, but doesnt this imply its actualy 2 & 5), I must print "Incorrect Format" to the screen. Here is my code so far.

public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.println("Enter a date (mm/dd/yyyy):");
String date = kbd.next();
String slash1 = date.substring(3,3);
String slash2 = date.substring(6,6);
int numofChar = date.length();

if (numofChar < 10)
System.out.println("Too few characters in the date");
if (numofChar > 10)
System.out.println("Too many characters in the date");
if (!(slash1.equals("/") || slash2.equals("/")))
System.out.println("incorrect format");

To be honest, I could have made the code look nicer, I have been playing and switching code for two hours on this one part of the problem, its just not making any sense to me. I have researched this question in different ways, just not coming up with the right way.

So if it seems messy or totally off track, that may be why. Also, ive likely confused everything i did know, so if something more is wrong, please help!

How would I declare a variable, that stores the character at position 3 and 6; then tests to see if both are in fact slashes?

Answer Source

You can check the character directly. No need to take a substring.

if (userInput.charAt(2).equals('/') && userInput.charAt(5).equals('/')) {}

But, if you want to use substring, you should know how it works.

public String substring(int beginIndex)

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

public String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

So there is another apprach:

String slash1 = userInput.substring(2,2);
String slash2 = userInput.substring(5,5);

if (slash1.equals("/") && slash2.equals("/")){}

Watch out! Strings are represented by character(s) in double quotes "" and characters are represented by single character in a single quotes ''.

Another thing that might be helpful for you is, that if you know, that something is a String, declare it a String. It's a lose of data when you declare that it's an Object. if it's a String it must be an Object!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download