I need help with trying to create a array where you enter the the number of integers you want in the array, you enter the numbers, and it prints the reverse of the numbers. I keep getting errors everytime I atempt to run this program.
public class RA{
public static void main(String[] args) {
int numofarry = 0;
int[] a;
String numofarry = JOptionPane.showInputDialog(null,
"Enter the list length:",
"Project 4 Input", JOptionPane.QUESTION_MESSAGE);
numofarry = Intger.parseInt(numofarry);
a = new int[numofarry];
reverse(a);
System.out.println("The reversal is ");
for (int i = 0; i < a.length; i++){
String aString = JOptionPane.showInputDialog(null,
"Enter a number:",
"Project 4 Input", JOptionPane.QUESTION_MESSAGE);
a[i] = Integer.parseInt(aString);
}
System.out.print(a[i] + " ");
}
public static int[] reverse(int[] a) {
int[] newList = new int[a.length];
for (int i = 0; i < a.length; i++)
newList[i] = a[a.length - 1 - i];
You cant cast a String to an int, also, Strings are immutable. You will have to use a seperate variable.
Also, you cannot use the same name for two variables in the same scope.
Code:
int arrSize;
int[] a;
String numofarry = JOptionPane.showInputDialog(null,
"Enter the list length:",
"Project 4 Input", JOptionPane.QUESTION_MESSAGE);
arrSize = Integer.parseInt(numofarry);
a = new int[numofarry];
...
Furthermore, you spelt Integer as Intger.
Another thing, why are you calling reverse() before your adding data to the array? Your actually passing an empty array.
Another few things I picked up on, you cant access the looping variable i outside of the for block, it is out of scope and Java does not recognise it.
And, in your reverse function, you actually have to return a value. Otherwise, you will get a nasty error.
Code:
public static int[] reverse(int[] a)
{
int[] newList = new int[a.length];
for (int i = 0; i < a.length; i++)
newList[i] = a[(a.length - 1) - i];
return newList;
}
My only problem now is that I can only get it yo output the orginal array but not the reverse. Help please
import javax.swing.JOptionPane;
public class pro41{
public static void main(String[] args) {
int numofarry=0;
int[] a;
String numofarryString = JOptionPane.showInputDialog(null,
"Enter the list length:",
"Project 4 Input", JOptionPane.QUESTION_MESSAGE);
numofarry = Integer.parseInt(numofarryString);
a = new int[numofarry];
System.out.println("The reversal is ");
for (int i = 0; i < a.length; i++){
String aString = JOptionPane.showInputDialog(null,
"Enter a number:",
"Project 4 Input", JOptionPane.QUESTION_MESSAGE);
public static int[] reverse(int[] a)
{
int[] newList = new int[a.length];
for (int i = 0; i < a.length; i++)
newList[i] = a[(a.length - 1) - i];
return newList;
}
Bookmarks