Вывести массив таблица java

Печать двумерного массива в Java как таблица

Я хотел бы напечатать введенный 2-мерный массив как таблица, т.е. если по какой-то причине они вставили все 1 с.

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 

Так же, как и выше, но в консоли на Java затмение, никаких причудливых кнопок и графического интерфейса, но в консоли, вот что у меня есть.

 import java.util.Scanner; public class Client < public static void main(String[] args)< Scanner input = new Scanner(System.in); int[][] table = new int[4][4]; for (int i=0; i < table.length; i++) < for (int j=0; j < table.length; j++) < System.out.println("Enter a number."); int x = input.nextInt(); table[i][j] = x; System.out.print(table[i][j] + " "); >System.out.println(); > System.out.println(table); > > 

И это то, что я получаю, когда я все ввожу и консоль завершается:

5 ответов

Вам нужно распечатать массив отдельно от ввода числа. Так что вы можете сделать что-то вроде этого:

public class PrintArray < public static void main(String[] args) < Scanner input = new Scanner(System.in); int[][] table = new int[4][4]; for (int i = 0; i < table.length; i++) < for (int j = 0; j < table.length; j++) < // System.out.println("Enter a number."); int x = input.nextInt(); table[i][j] = x; >//System.out.println(); > // System.out.println(table); for (int i = 0; i < table.length; i++) < for (int j = 0; j < table[i].length; j++) < System.out.print(table[i][j] + " "); >System.out.println(); > > > 

Рассмотреть возможность использования java.util.Arrays ,

Там есть метод, который называется deepToString , Это будет отлично работать здесь.

System.out.println(Arrays.deepToString(table)); 

У вас будет цикл через эти массивы, чтобы распечатать содержимое. toString() массива просто печатает ссылочное значение.

Источник

Вывести массив таблица java

Иногда вот решишь с первого раза медиум и думаешь фсе я АйТишнег, потом даже условия понять не можешь и думаешь, может на категорию ЕС пойти отучится

Сюжет «Начало» нервно курит в сторонке по сравнению с теми ситуациями, в которые попадают Диего и Амиго)

Спикер на видео просто ТОП, с удовольствием бы слушал от него лекции на каждую тему! P.S. накидайте классов для ачивки, заранее благодарен!

Если подсознание Диего не окажется зараженным багами, а сам он в конце не окажется сторонником багов, я ставлю оценку на бал ниже этому сериалу

почему вы пишите . int[][] имя = new int[ширина][высота]; Где имя — это имя переменной-массива, ширина — это ширина таблицы (в ячейках), а высота — это высота таблицы. Пример: int[][] data = new int[2][5]; Создаем двумерный массив: два столбца и 5 строк. . а потом выясняется что на самом деле это не [ширина][высота] а [высота][ширина]. первое число показывает то сколько строк (одномерных массивов) будет создано, а вторая длину этих строк

Читайте также:  Кэширование nginx php fpm

Робокома с роботяночками или продолжать вывозить все дерьмо за корпоратов? Ставь класс если 1 + в комменты если 2

Даа, пришлось подумать, но дополнительная информация из инета помогла решить как и большинство))) Очень понравилось

Нуу, провозился с этой задачей. По крайней мере понял пробелы. Советую не спешить подгонять ответ, если не получается, обратите внимание 1) Отдельно момент объявления, отдельно инициализация массива. 2) Требуется не динамически выводить массив, а сначала создать массив, а потом выводить. 3) Обратить внимание на индексы массива.

Источник

How to print the results to console in a tabular format using java?

Tabular Output

In this post, we will see how we can print the results in a table format to the standard output like the image as shown below.
To print the results like a table structure we can use either printf() or format() method.
Both the methods belong to the class java.io.PrintStream .

The printf() and format() Methods

  • The package java.io includes a PrintStream class that has two formatting methods that you can use to replace print and println . These methods format and printf are equivalent to one another.
  • The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out . Thus, you can use format or printf anywhere in your code where you have previously been using print or println .

I have created a domain (POJO) class called Student.java which has some basic attributes like id, emailId, name, age and grade.

 
private String id; private String name; private String emailId; private int age; private Character grade;

And the oher class is the main class to print the Student information.

  • For demonstration purpose I have created some random Student objects and added those objects to the List.
  • But in real time you may fetch the data from a Database or by calling a web service.

Below are the two classes for printing the output in tabular format.

1. Student.java

 
public class Student < private String id; private String name; private String emailId; private int age; private Character grade; // Getter and Setter methods public String getId() public void setId(String id) public String getName() public void setName(String name) public String getEmailId() public void setEmailId(String emailId) public int getAge() public void setAge(int age) public Character getGrade() public void setGrade(Character grade) // Default Constructor public Student() < super(); >// Parameterized Constructor public Student(String id, String name, String emailId, int age, Character grade) < super(); this.id = id; this.name = name; this.emailId = emailId; this.age = age; this.grade = grade; >>

2. Main.java

 
import java.util.ArrayList; import java.util.List; public class Main < public static void main(String[] args) < // Create an Empty List of Student, And add few objects to the List List&amp;amp;amp;amp;lt;Student&amp;amp;amp;amp;gt; students = new ArrayList&amp;amp;amp;amp;lt;Student&amp;amp;amp;amp;gt;(); students.add(new Student("ST001", "James Smith", "james_smith@gmail.com", 23, 'A')); students.add(new Student("ST002", "Philip Duncan", "philip_duncan@gmail.com", 22, 'c')); students.add(new Student("ST003", "Patrick Fixler", "patrick_fixler@gmail.com", 25, 'b')); students.add(new Student("ST004", "Nancy Goto", "nancy_goto@gmail.com", 24, 'A')); students.add(new Student("ST005", "Maria Hong", "maria_hong@gmail.com", 22, 'e')); // Print the list objects in tabular format. System.out.println("-----------------------------------------------------------------------------"); System.out.printf("%10s %30s %20s %5s %5s", "STUDENT ID", "EMAIL ID", "NAME", "AGE", "GRADE"); System.out.println(); System.out.println("-----------------------------------------------------------------------------"); for(Student student: students)< System.out.format("%10s %30s %20s %5d %5c", student.getId(), student.getEmailId(), student.getName(), student.getAge(), student.getGrade()); System.out.println(); >System.out.println("-----------------------------------------------------------------------------"); > >

Console Output

----------------------------------------------------------------------------- STUDENT ID EMAIL ID NAME AGE GRADE ----------------------------------------------------------------------------- ST001 james_smith@gmail.com James Smith 23 A ST002 philip_duncan@gmail.com Philip Duncan 22 c ST003 patrick_fixler@gmail.com Patrick Fixler 25 b ST004 nancy_goto@gmail.com Nancy Goto 24 A ST005 maria_hong@gmail.com Maria Hong 22 e -----------------------------------------------------------------------------

Share this:

Источник

Вывод матрицы в виде таблицы

здравствуйте. подскажите, как можно вывести двумерный массив в консоль в виде таблицы? то есть, чтобы было разделение линиями и данные не съезжали, а выводились ровно. ожидаемый результат примерно такой:
____________________
|"first" | 9.8 | 1.45 | 0|
------------------------
|"second"| 1 | 3.5 | 1|
--------------- ---------
главное, чтобы ровно разделялось, и было понятно, какие числа из какого столбца

Вывод матрицы в виде таблицы
Как вывести матрицу смежности в виде таблицы? Код генерирования матрицы смежности: using System;.

Вывод из таблицы MySQL записей в виде html таблицы и дальнейшая их обработка
И снова здравствуйте! На этот раз я со сложным вопросом. Мне нужно вывести определенные записи из.

Вывод всей таблицы из БД в виде таблицы
Доброго времени суток, уважаемые обитатели cyberforum. Столкнулся с такой проблемой : нужно.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
class Person { private String firstname; private String lastname; private float age; private int salary; public Person(String firstname, String lastname, int age, int salary) { this.firstname = firstname; this.lastname = lastname; this.age = age; this.salary = salary; } String[] getArg() { return new String[] {firstname,lastname, Float.toString(age), Integer.toString(salary)}; } } class ConsoleTable { public static void write(String matrix[][]) { int max = 0; for(int i=0; i matrix.length; ++i) { max = max>matrix[i].length? max : matrix[i].length; } int maxsize[] = new int[max]; for (int i = 0; i  matrix.length; ++i) { for (int j = 0; j  matrix[i].length; ++j) { int size = matrix[i][j].length(); if (maxsize[j]  size) { maxsize[j] = size; } } } int lw=0; for (int i =0; imaxsize.length; ++i) { lw += maxsize[i]; } lw += maxsize.length*2+1; for(int i=0; ilw; ++i) { System.out.print('-'); } System.out.println(); for (int i = 0; i  matrix.length; ++i) "); for (int j = 0; j  matrix[i].length; ++j) { //"%*f" - не работает( System.out.printf(" %"+maxsize[j]+"s",matrix[i][j]); System.out.print(" System.out.println(); } for(int i=0; ilw; ++i) { System.out.print('-'); } System.out.println(); } } public class Main { public static void main(String[] args) { Person persons[] = new Person[] { new Person("anthon","antonov",10,0), new Person("artur","petrov",20,20000), new Person("ivan","ivanow",100,1000) }; String[][] arguments = new String[persons.length][]; for(int i=0; ipersons.length; ++i) { arguments[i] = persons[i].getArg(); } ConsoleTable.write(arguments); } }

Эксперт PythonЭксперт Java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
private static String matrixTotring(double[][] matrix)  StringBuilder result = new StringBuilder(); int len = matrix[0].length; for (double[] rows : matrix) { result.append(' result.append(System.lineSeparator()); for (int i = 0; i = len * 8; i++) { result.append('-'); } result.append(System.lineSeparator()); } return result.toString(); }

Вывод в виде таблицы html
Добрый день, подскажите пожалуйста, как сделать что бы выводилось в виде таблицы, нужно что бы.

Вывод данных из БД в виде таблицы
Добрый день. У меня на странице нужно отобразить данные в виде таблиц. Но, не получается. <?php.

Вывод данных из БД в виде таблицы
Доброго времени суток! В общем имеется БД с фото. Нужно из нее вывести фото вряд по три штуки ну и.

Вывод чисел в виде таблицы
Нужно вывести числа в виде следующей таблицы: 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 Вот мой код: .

Источник

Оцените статью