Reputation: 1
Im trying to Convert numbers to words from 0-100 only and how do i reexecute the program if it didnt meet the conditions without extiting the program. if i input 55, i want to output Fifty-Five but if i type numbers that are not in 0-100, it will output "you should input 0-100 only try again" then it will automatically go to "input number between 0-100 only"
package convertnumbertowords;
import java.util.Scanner;
public class ConvertNumberToWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input number between 0-100 only ");
int num1 = sc.nextInt();
while (num1 <= -1 && num1 >= 101 ){
if(num1 <= 100 && num1 >= 0){
System.out.println("The "+num1+" in words is "+
Integer.toString(num1));
}
else{
System.out.println("You should input 0-100 only Try Again");
}
}
}
}
Upvotes: 0
Views: 70
Reputation: 58
My suggestion, is to keep the words within an array, separate it to ones, and tens. E.g.:
String ones[] = { " ", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten"," Eleven", " Twelve", " Thirteen", " Fourteen", "Fifteen", "Sixteen", " Seventeen", " Eighteen"," Nineteen" };
The reason why I kept the ones[0] as empty, so it'll be easy to understand, ones[1] = one
String tens[] = { " ", " ", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", "Seventy", " Eighty", " Ninety" };
I kept the 0, 10 as empty because I have it declared in the ones.
Based on my example, if it's less than that just use ones[number]. If it's more than 19 , I would suggest to divide it with ten to get the word for its tens word and then modulus(%) the number with 10 to get its ones word. All the best in cracking it, My suggestion may not be prefect but hope it will give you some idea
Upvotes: 1
Reputation: 1121
To keep until correct input is entered you first take an input -> check if it is wrong -> If yes then prompt user again otherwise move to next step. In code it will look like this
// Ask for input
System.out.println("Input number between 0-100 only ");
int num = sc.nextInt();
// Check if input is incorrect
while (num > 100 || num < 0) {
// If input is incorrect prompt user again
System.out.println("You should input 0-100 only Try Again");
// Update num and check until unser enters a num within the range
num = sc.nextInt();
}
Upvotes: 0