i was wondering if someone could give me a little bit of help with my triangular number program.. it is supposed to tell the user if the inputed number is a triangular number or not..the problem is, is that it doesnt seem to work..any help would be greatly appreciated.
public class Triangular { public static boolean triangular(int number) { if (number < 1) return false; // only positive numbers
int tri = 0; for (int i=1; tri<number; ++i) { tri += i; // create next triangular number } // after the for-loop, tri>=number, with // tri==number if number is triangular and // tri>number if number is not triangular
if (tri==number) return true; return false;
}
public static void main(String[]args) { int userInput;
//Ask user to supply a number System.out.println("Please enter a number to see if it is a Triangular Number>"); userInput = (int)KBInput.readDouble(); //Casts the double to an int System.out.println("The number you entered is " + userInput); System.out.println("The number " + (triangular(userInput) ? "is " : "is not ") + "a triangular number" );
import java.io.*;
publicclass Triangular {
publicstaticboolean triangular(int number)
{
if (number < 1) returnfalse; // only positive numbers
int tri = 0;
for (int i=1; tri<number; ++i)
{
tri += i; // create next triangular number
} // after the for-loop, tri>=number, with
// tri==number if number is triangular and
// tri>number if number is not triangular
return (tri==number);
}
publicstaticvoid main(String[]args) {
//Ask user to supply a number
int userInput = getInput("Please enter a number to see if it is a Triangular Number>");
System.out.println("The number you entered is " + userInput);
System.out.println("The number " + (triangular(userInput) ? "is " : "is not ") + "a triangular number" );
}
publicstaticint getInput(String message){
int n = -1;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(message);
String s = br.readLine();
n = Integer.parseInt(s);
}catch(IOException ioe){
System.err.println(ioe.getMessage());
}catch(NumberFormatException nfe){
System.err.println(nfe.getMessage());
}
return n;
}
}