I am new to this forum so please be patience with me. I am working on a program that takes in a sentence from the keyboard, delimit the sentence by spaces, iterate through every word, if there is a number multiple the number by 2 and print out the sentence along with the multiplied number. So far I am able to get the sentence from the keyboard, and delimit. I am stuck when it comes to checking if there is a number in the sentence .I have tried using regex, stringtokenizer, .split.
I would suggest that there are much better things than try‑catch. You want to know whether the token is an int or not? And you want input from the keyboard? Well, there is a class designed to be able to do both. There is no risk of Exceptions in this code, as long as your while(...) is designed correctly.You will find more about it in the API documentation.
thank you for everyone's reply and sorry for the lag. i finally had some time to work on this small program again. this is what i have came up with:
it's suppose to be:
hi
10
i'm getting a little closer. i need to figure out how to check if its a number and not a value (in this case, 5) and how to not print the value before and after its multiplied, only after it's multiplied is needed.
I finally got the output I needed. Thanks Carey for the suggestion, that was such a stupid mistake I made. Thanks Campbell for suggesting I use loops. And finally thanks AJ for the parse hint. I haven't written code in a year I am just so rusty!
Campbell Ritchie wrote:I would suggest that there are much better things than try‑catch. You want to know whether the token is an int or not? And you want input from the keyboard? Well, there is a class designed to be able to do both. There is no risk of Exceptions in this code, as long as your while(...) is designed correctly.You will find more about it in the API documentation.
Here is the source for inScan.nextInt(). It does exactly the same:
A.J. Côté wrote: . . . It does exactly the same: . . .
What makes you think that? It uses hasNext(integerPattern()). That is completely different from using an Exception. Should you wish to go through the code for integerPattern() you will probably find it does something completely different.