Easy n00b Java help #40545

ChrisCramer247

Platinum Member
Dec 6, 2001
2,171
1
0
Hey Everyone. I'm stuck on this one part of my program. Not sure if I can maintain this in Main or need a seperate call to a method. Here were the instructions given:


1. Set up the program for keyboard entry (I declared this as static and global)

2. in the main method, use a for loop to ask for each of the five numbers as follows: (this is what im unsure about

for (int x=1;x<=5;x++){
try{
display(?Please enter number ?+x+?: ?);
String input = keyboard.readLine();
number=Integer.parseInt(input);
}

catch(NumberFormatException e){
display(?I was expecting an integer.?);
exitProgram();
}
}


Here is the source code I have so far, if anyone can help it would be greatly appreciated THANKS!

import java.io.*;
public class AverageFive {

static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

//***--------------------------------Begin Main------------------
public static void main(String args[]) throws IOException {

int x = 0;

String input = null;

//THIS IS WHERE IT GETS BAD, DO I NEED A SEPERATE METHOD OR CAN I KEEP IT IN MAIN?

for (int x=1;x<=5;x++){

try{

display("please enter a number "+x+": ");

String input = keyboard.readLine();

number=Integer.parseInt(input);

}

catch(NumberFormatException e){

display ("I was expecting and integer.");

System.exit(0);
}
}

//***------------------Begin Display----------------------
public static void display(String n){

System.out.println(n);

}//close display

}//close AverageFive


 

manly

Lifer
Jan 25, 2000
13,086
3,851
136
For a program this small, you don't really need to factor your code into separate functions, or modules.
 

RRZReme

Junior Member
Oct 18, 2001
23
0
0
Why don't you read your input into a character array and then just check the array for any numbers?

BTW, global variables are BAD BAD BAD