-
Small Java Code for Math
I intend to teach my grade 4 Mathematics students on factors. And I would
like to write a Java code (the only language available in my school) and
demo it on a terminal. But I know nothing about Java. Please Help!
The expected code should read an integer from the keyboard and then output
all the factors of the number, including 1 and itself. For instance:
reading 15, output 1,3,5,15
reading 60, output 1,2,3,4,5,6,10,12,15,20,30,60
etc.
In the past, I used my DBase III+ code to do it and it worked well. But
now only Java is available and I have to re-code it.
Could anyone suggest the ways that I can follow?
-
Re: Small Java Code for Math
Hi Nancy,
Use the following code..
//////////////////////////////////////
import java.io.*;
public class Factor
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter an integer " );
String input = in.readLine();
if (!input.equals(""))
{
try
{
int inputval = Integer.parseInt(input);
if ( inputval == 1)
System.out.println("The only factor of 1 is 1");
else
{
StringBuffer sb = new StringBuffer("The factors of " + input + " are ");
int max = ( inputval /2) + 1;
for (int x=1; x < max ; x++)
{
if ( (inputval%x) == 0 )
sb.append(x+",");
}
sb.append(inputval);
System.out.println(sb.toString());
}
}
catch(NumberFormatException e)
{
System.out.println("Please enter an valid integer like 1,2..." );
}
}
}
}
//////////////////////////////////////
Cheers,
Nikhil
"Nancy" wrote:
>
>I intend to teach my grade 4 Mathematics students on factors. And I would
>like to write a Java code (the only language available in my school) and
>demo it on a terminal. But I know nothing about Java. Please Help!
>
>The expected code should read an integer from the keyboard and then output
>all the factors of the number, including 1 and itself. For instance:
>
>reading 15, output 1,3,5,15
>reading 60, output 1,2,3,4,5,6,10,12,15,20,30,60
>etc.
>
>In the past, I used my DBase III+ code to do it and it worked well. But
>now only Java is available and I have to re-code it.
>
>Could anyone suggest the ways that I can follow?
-
Re: Small Java Code for Math
Hi Nikhi,
Thank you so much for your kind help. I'll compile it to make it work.
Hope this would convince my subject panel and my students.
Sincerely thanks with warmth.
Nancy
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks