Заполнение массива и двумерного массива с клавиатуры
Не работает цикл if чтобы выбрать вид массива и заполнить его
import java.util.Scanner;
public class Fourth {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Введите вид массива 1 - обычный, 2 - двумерный: ");
int a = input.nextInt();
if (a == 1)
System.out.print("Введите длинну массива: ");
int size = input.nextInt();
int array[] = new int[size];
System.out.print("Введите элемент массива:");
for (int i = 0; i < size; i++) {
array[i] = input.nextInt();
}
System.out.print ("\nДлинна массива: " + array.length);
for (int i = 0; i < size; i++) {
System.out.print (" \n" + array[i]);
}
System.out.println();
if (a == 2) {
System.out.print("Введите количество строк массива: ");
int c = input.nextInt();
System.out.print("Введите количество столбцов массива: ");
int d = input.nextInt();
int[][] arr = new int[c][d];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print("Введите элемент arr[" + i + "][" + j + "]:");
arr[i][j] = input.nextInt();
}
}
}
}
Ответы (2 шт):
Автор решения: Agzam
→ Ссылка
В Java после if надо ставить { если потом идет несколько "действий":
{ после if можно не ставить только если потом идет 1 действие
Примеры:
Код:
int a = 1;
if(a == 1) System.out.println("Hello");
System.out.println("world");
Вывод:
Hello
world
Код:
int a = 0;
if(a == 1) System.out.println("Hello");
System.out.println("world");
Вывод:
world
Код:
int a = 1;
if(a == 1) {
System.out.println("Hello");
System.out.println("world");
}
Вывод:
Hello
world
Ваш код должен выглядеть так:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Введите вид массива 1 - обычный, 2 - двумерный: ");
int a = input.nextInt();
if (a == 1) {
System.out.print("Введите длинну массива: ");
int size = input.nextInt();
int array[] = new int[size];
System.out.print("Введите элемент массива:");
...
} else if(a == 2) {
...
}
...
}
Автор решения: rlowell
→ Ссылка
Как-то так
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Введите вид массива 1 - обычный, 2 - двумерный: ");
int a = input.nextInt();
if (a == 1) {
System.out.print("Введите длинну массива: ");
int size = input.nextInt();
int[] array = new int[size];
System.out.print("Введите элемент массива:");
for (int i = 0; i < size; i++) {
array[i] = input.nextInt();
}
System.out.print("\nДлинна массива: " + array.length);
for (int i = 0; i < size; i++) {
System.out.print(" \n" + array[i]);
}
System.out.println();
}
else if (a == 2) {
System.out.print("Введите количество строк массива: ");
int c = input.nextInt();
System.out.print("Введите количество столбцов массива: ");
int d = input.nextInt();
int[][] arr = new int[c][d];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print("Введите элемент arr[" + i + "][" + j + "]:");
arr[i][j] = input.nextInt();
}
}
}
}