[英]processing single dimensional array java
我正在嘗試使用對話框中的用戶輸入創建數組。 應該詢問用戶要輸入多少個數字,然后要求用戶輸入數字。 然后假定該代碼以相反的順序輸出數字。 下面是我到目前為止的代碼..它不起作用。 我嘗試用用戶輸入初始化數組時發生了錯誤。 我對Java很陌生,因此歡迎任何建議。 提前致謝。
public static void main(String[] args)
{
String input;
int space;
double [] numbers;
double count;
String numberInput;
double number;
input = JOptionPane.showInputDialog
(null, "How many numbers would you like to enter?");
space = Integer.parseInt(input);
numbers = new double[space];
count = 0;
while (count < space)
{
numberInput = JOptionPane.showInputDialog
(null, "Enter a number to be sorted: ");
number = Double.parseDouble(numberInput);
for (int i = 0; i < numbers.length; i++)
numbers[i] = number;
count++;
}
double[] numbers2 = swapArray(numbers);
JOptionPane.showMessageDialog(null, numbers2);
}
public static double[] swapArray(double[] array)
{
double[] result = new double[array.length];
for (int i = 0, j = result.length - 1;
i < array.length; i++, j--)
{
result[j] = array[i];
}
return result;
}
}
這是我對你的任務的看法。 它應該給您一些有關如何解決問題的想法,而不給您一個復制粘貼的解決方案,也不能給您提供(盡我所能)最好的結構/邏輯(但仍然給您一些提示,以指明他們的方向) :
package so_q33405148;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
//TIP: You can use 'Scanner' instead of a 'Reader' here, to avoid having to parse strings into ints (scanner can do it for you)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many numbers would you like to enter?");
int count = Integer.parseInt(br.readLine());
int input[] = new int[count];
for (int i = 0; i < count; i++) {
System.out.print("Enter a number to be sorted: ");
//TIP: With some clever math, you can invert the array right as it's still filling up here, by manipulating a new int (so 'i' is unchanged, as it's the for-loop's index) using 'i' and 'input.length'...Or, with a little creativity and insight, you may even achieve the same result manipulating 'i' directly somewhere else...
input[i] = Integer.parseInt(br.readLine());
}
System.out.println("Original array:\n" + Arrays.toString(input));
//TIP: Better methods to reverse arrays and/or collections exist.
//Take a look at SO question #3962766 (puritan solution without as much memory-footprint) and also Google about 'Arrays.asList()' and 'Collections.reverse()' (learn about collections-sorting)
int reversedInput[] = new int[input.length];
for (int i = 0; i < count; i++) {
reversedInput[i] = input[count - i - 1];
}
System.out.println("Reversed array:\n" + Arrays.toString(reversedInput));
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.