Reputation: 21
I am supposed to ask the reader to input a number and then check if it's between 500 and 1000, so i can add up the digits. But i don't know how to check if the number is between the interval.
import java.util.Scanner;
public class AddNumbers {
public static void main(String[]args){
Scanner input = new Scanner (System.in);
//Prompt user to enter number
System.out.println("Enter a number between 500 and 1000:");
String number;
number=input.nextLine();
//Get digits from number
char numberDigit1 = number.charAt(0);
char numberDigit2 = number.charAt(1);
char numberDigit3 = number.charAt(2);
//initialize variable
String constant=500;
String constant2=1000;
while (number.CompareTo(constant)){
System.out.println("The sum of the digits is: " + ((number.charAt(0) + (number.charAt(1) + (number.charAt(2))))));
}
while (number.CompareTo(constant)){
if (number<=0)
System.out.println("****ERROR: THE NUMBER MUST BE BETWEEN 500 AND 1000****");
}
while (number.CompareTo(constant2)){
if (number>=0)
System.out.println("****ERROR: THE NUMBER MUST BE BETWEEN 500 AND 1000****");
}
input.close();
}
}
Upvotes: 0
Views: 298
Reputation: 44834
This will not compile
String constant=500;
String constant2=1000;
But why are you even using Strings
?
int constant=500;
int constant2=1000;
number=input.nextLine();
int realInt = Integer.parseInt (number);
if (realInt >= constant && realInt <= constant2) {
// you still have `number` so
int result = 0;
for (char ch : number.toCharArray ())
{
result += Integer.valueOf ("" + ch);
}
System.out.println (result);
}
Upvotes: 1
Reputation: 30819
Instead of reading input as a string and converting it into an int, we can directly validate integer input e.g:
Scanner scanner = new Scanner (System.in);
int input;
if(!scanner.hasNextInt()){
System.out.println("Input must be a number.");
}else{
input = scanner.nextInt();
if(input < 500 || input > 1000){
System.out.println("****ERROR: THE NUMBER MUST BE BETWEEN 500 AND 1000****");
}
}
Upvotes: 0