Results 1 to 2 of 2
Thread: NegativeArray
- 11-11-2012, 10:21 PM #1
Member
- Join Date
- Oct 2012
- Posts
- 20
- Rep Power
- 0
NegativeArray
On my last assignment and it has me stumped again.
Goal of this project is to ask the user for an input. Can be a string or integer. Said input is supposed to declare the size of the array. If the input is a positive integer it successfully creates said array and gives a message. If its a String/Letter entered I have to parse it to get a NumberFormatException error and handle it appropriately. If its a negative number I also have to use a NegativeArraySizeException and handle that appropriately with a catch block as well.
My code is as follows:
The error Im getting is:PHP Code://NegativeArray.java by Tyler 10/27/2012 import java.util.*; public class NegativeArray { public static void main(String[] args) { int numItems = 0; int[] items; String inputItems; Date today = new Date(); System.out.println("NegativeArray.java" + "\nby Tyler " + today); //Create array if rules are met try { //Enter number of items to have in array inputItems = System.out.println("Enter number of items to hold in the array: "); numItems = Integer.parseInt(inputItems); //Create array to hold number of names to enter items = new int[numItems]; System.out.println("Array created successfully"); } //Catch if you enter a negative array size catch(NegativeArraySizeException exception) { System.out.println("You can not enter a negative size for an array"); } //Catch if you use a non numeric array size catch(NumberFormatException exception) { System.out.println("You must use a number greater than or equal to 0"); } //Displays what you tried to enter System.out.println("The size of the array you tried to create was: " + numItems); } }
Not sure why. Im clearly setting inputItems equal to the number/string entered by the user.C:\Users\Tyler\Documents\School Work\CIS280\Project 7>javac NegativeArray.java
NegativeArray.java:21: incompatible types
found : void
required: java.lang.String
inputItems = System.out.println("Enter number of items to hold i
n the array: ");
^
1 error
- 11-11-2012, 11:55 PM #2
Member
- Join Date
- Aug 2012
- Posts
- 8
- Rep Power
- 0
Re: NegativeArray
Because of
System.out.println returns void, it doesn't read anything from console.Java Code:inputItems = System.out.println("Enter number of items to hold in the array: ");
Use
or something other to read input from console.Java Code:Console console = System.console(); inputItems = console.readLine("Enter number of items to hold in the array: ");


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks