# Thread: input to an integer (simply)

1. Member
Join Date
Jan 2008
Posts
23
Rep Power
0

## input to an integer (simply)

I need help with this basic program. I am trying to convert an input to an integer but I cant use the way I have it written in this coding method. It has to be something simpler. Is there a solution to my problem?

Java Code:
```import javax.swing.JOptionPane;

public class Assignment4ITEC2260
{

public static void main(String[] args)
{
int number1;
int number2;
int num;

// Prompt for first number
do{
String input = JOptionPane.showInputDialog(null,"Enter first number");
if(input == null)
System.exit(1);

// convert input to a integer
try
{
number1 = Integer.parseInt(input.trim());
}
catch(NumberFormatException ex)
{
number1 = 0;
}
}while(number1 < 1);

// Prompt for second number
do{
String input = JOptionPane.showInputDialog
(null,"Enter second number greater than first number");
if(input == null)
System.exit(1);

// convert input to a integer
try
{
number2 = Integer.parseInt(input.trim());
}
catch(NumberFormatException ex)
{
number2 = 0;
}
}while(number2 < number1);

// display the odd numbers between the first number and the second number.

String numbers = "";

// using a for loop
for(num = number1+1; num < number2;num++)
{
// check for odd number
if((num % 2) != 0)
{
numbers = numbers + num + " ";
}
}

JOptionPane.showMessageDialog
(null,numbers,"using for loop", JOptionPane.INFORMATION_MESSAGE);

// using a do loop
numbers = "";
num = number1+1;

do{

// check for odd number
if((num % 2) != 0)
{
numbers = numbers + num + " ";
}

num++;

} while(num < number2);

JOptionPane.showMessageDialog
(null,numbers,"using a do loop", JOptionPane.INFORMATION_MESSAGE);

// using a do-while loop

numbers = "";
num = number1+1;

while(num < number2)
{

// check for odd number
if((num % 2) != 0)
{
numbers = numbers + num + " ";
}

num++;

}

JOptionPane.showMessageDialog
(null,numbers,"using a do-while loop", JOptionPane.INFORMATION_MESSAGE);

System.exit(0);
}

}```
Thanks,
Chitwood

2. Member
Join Date
Jan 2008
Posts
23
Rep Power
0
I cant use try/catch in number1 and number2 conversions? Does anyone have an easy solution?

3. Cross-posted from new to Java: http://www.java-forums.org/new-java/...lp-please.html

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14
... ...

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•