r/javahelp • • Mar 09 '20

Homework How to put a max character length on a string

Im doing a college assignment and cannot figure how to put a max character length of 40 on a String

20 Upvotes

9 comments sorted by

2

u/AssassinBoy49 Nooblet Brewer Mar 12 '20

you can use the length method and an if statement to check that it is within the limit. if not the program should produce an error

1

u/Dishy2001 Mar 12 '20

Cheers, Would that go underneath the field or in the constructor?

2

u/AssassinBoy49 Nooblet Brewer Mar 12 '20

I'm not entirely sure as I'm pretty new to java, I believe that it goes in the field, though you may be able to it in the constructor as well, sorry for the late reply but I hope this helps.

2

u/Dishy2001 Mar 12 '20

Same boat as myself, Sure look no harm in trying both. Dont worrt about the late reply mate. Not due til Monday

2

u/AssassinBoy49 Nooblet Brewer Mar 12 '20

alright man, good luck

2

u/fsbk366 Mar 10 '20

If the string is a parameter of an object, you can add limiting criteria to the setter method.

15

u/[deleted] Mar 09 '20

[removed] — view removed comment

3

u/Dishy2001 Mar 09 '20

Thank you, that thought never popped into my head. Will use that as its relitively straight forward. Thanks a million

4

u/Python4fun Mar 10 '20

You can also check the string length and throw an error if the length is too high.