• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

Java Exception Handling question

xynapse

Limp Gawd
Joined
Nov 15, 2005
Messages
142
I'm trying to write a program that meets the following requirements. I'm getting all kinds of errors because I'm a noob but I'm trying to learn! Please help.

1. Create an array with 100 randomly chosen integers.
2. Prompt the user to enter the index of the array, then display the corresponding element value. If the specified index is out of bounds, display the message "Out of Bounds."


Code:
import java.util.Scanner;
import java.io.*;

public class exceptionHandling {
	public static void main(String[] args) {


        //create random number between 1 to 100 

	Random rn = new Random();

	int r = rn.nextInt(100)+1;


		Scanner scan = new Scanner(System.in);
		//prompt user to enter a random number
		System.out.print("Enter an integer: ");
		
		
		int index = scan.nextInt();
		if (index > r.length)
		System.out.println("Out of Bounds.");


	}
		
	
}
 
Thanks.

Code:
import java.util.Scanner;

public class Array {

public static void Array(String[] args) {


    		Scanner scan = new Scanner(System.in);
		//prompt user to enter a random number
		System.out.print("Enter an integer: ");
		
		for (int i = 0; i < 100; i++) {
			
			try {
				System.out.println(1 / 0);
			}
			catch (Exception ex) {
			}

		
		int index = scan.nextInt();
		if (index > i.length)
		System.out.println("Out of Bounds.");


	}


}
}

Getting this error

Array.java:22: int cannot be dereferenced
if (index > i.length)
 
Code:
		for (int i = 0; i < 100; i++) {
		    ...
		    if (index > i.length)

i is not an array, it's an int. You need to create an array of int first and then loop through all of its elements, assigning a random int to each one. Try getting just that part working first...
 
This code snippet will setup your int array with random values ranging from 1 to 100 of array size 100.

int[] intArray = new int[100];
Random rnd = new Random();
for (int i = 0; i < intArray.length; i++) intArray = rnd.nextInt(100) + 1;

From here just get input from user and display the appropriate value or message.
 
Thanks guys. I was trying to rush through an assignment for this 8 week java programming course all while Chemistry and Physics 2 finals were coming up. Anyway, the semester is all done now. Woooohooo! Going to go back and review it all. Also, interested in checking out Python if you guys have any suggestions for a n00b that would be groovy.
 
Back
Top