2014-01-14 3 views
3

У меня есть задание завтра, я закончил его, я просто получаю одну ошибку. Ну, это не совсем ошибка, так как это мой вывод - это не тот результат, который хочет мой учитель.создание таблицы умножения с использованием JOptionPane

Мой учитель хочет, чтобы я создать таблицу умножения, используя JOptionPane

И это то, что я до сих пор:

import javax.swing.JOptionPane; 

public class assign3 { 

public static void main(String[] args) { 

     String Boundary1 = JOptionPane.showInputDialog(null, "Please enter the first boundary of the multiplication table."); 
     String Boundary2 = JOptionPane.showInputDialog(null, "Please enter the second boundary of the multiplication table."); 

     int X = Integer.parseInt(Boundary1); 
     int Y = Integer.parseInt(Boundary2); 
     int j = 1; 
     String Result = ""; 
     int x = 1; 

     while (x <= X){ 
      for(int i = 1;i<= Y; i++){ 
       j = i * x; 
       Result = Result + j + " "; 
      } 
      x++; 
      Result = Result + "\n"; 
     } 
     JOptionPane.showMessageDialog(null, Result); 
    } 
} 

Мой выход показывает вверх, как это.

https://www.dropbox.com/s/ulp1gj9sqi94d3a/IMG_20140114_162054.jpg

Но мой учитель хочет выход, чтобы показать, как это.

https://www.dropbox.com/s/6gtexqoj3rs7xvl/IMG-20140114-WA0000.jpg

Мой код не имеет правильное расстояние между цифрами, я пытался исправить это как-то на некоторое время без удачи.

+1

Строковое представление чисел имеет разную длину, поэтому вам нужно использовать различное количество пробелов для каждого. С этим очень легко получить результат _far_ лучше, чем вы, учителя ... –

+0

JTextArea знает TAB, программно тоже – mKorbel

+0

Несвязанный: Пожалуйста, изучите соглашения об именах java и придерживайтесь их. – kleopatra

ответ

1

Одно из решений (предполагается, что result уже нужны вкладки (\t)):

JTextArea jf=new JTextArea(result); 

jf.setEditable(false); 
jf.setOpaque(false); 

JOptionPane.showMessageDialog(null, jf); 

РЕДАКТИРОВАТЬ:

public static void main(String[] args) { 

     String Boundary1 = JOptionPane.showInputDialog(null, "Please enter the first boundary of the multiplication table."); 
     String Boundary2 = JOptionPane.showInputDialog(null, "Please enter the second boundary of the multiplication table."); 

     int X = Integer.parseInt(Boundary1); 
     int Y = Integer.parseInt(Boundary2); 
     int j = 1; 
     String Result = ""; 
     int x = 1; 

     while (x <= X) { 
      for (int i = 1; i <= Y; i++) { 
       j = i * x; 
       Result = Result + j + "\t"; 
      } 
      x++; 
      Result = Result + "\n"; 
     } 
     JTextArea jt=new JTextArea(Result); 
     jt.setEditable(false); 
     jt.setOpaque(false); 
     jt.setTabSize(3); 
     JOptionPane.showMessageDialog(null, jt); 
    } 

O/P: enter image description here

+0

привет, спасибо за ваш ответ, однако пространство между каждой колонкой слишком большой https://www.dropbox.com/s/m5fr1nm4hqttujw/Screen%20Shot%202014-01-14%20at%205.55.22%20PM.png – user3114770

+0

@ user3114770 использование (относительно моего примера) 'jf. setTabSize (1); 'или какой-либо другой номер –

+0

@ user3114770 Размер вкладки 3-4 должен быть достаточным для шрифта по умолчанию. –

1

Вы пытались использовать String.format("%5d", j)?

Он будет печатать каждый int на 5 пространств - длина.

Пример: 10 будет ___10.

Или String.format("%-5d", j) для выравнивания по левому краю.

Пример: 10___.

Edit: Другой вариант заключается в использовании html:

public static void main(String[] args) { 

    String Boundary1 = JOptionPane.showInputDialog(null, "Please enter the first boundary of the multiplication table."); 
    String Boundary2 = JOptionPane.showInputDialog(null, "Please enter the second boundary of the multiplication table."); 

    int X = Integer.parseInt(Boundary1); 
    int Y = Integer.parseInt(Boundary2); 
    int j = 1; 
    String Result = "<html><table>"; 
    int x = 1; 
    while (x <= X){ 
     Result += "<tr>"; 
     for(int i = 1;i<= Y; i++){ 

      j = i * x; 
      Result += String.format("<td><center>%d</center></td>", j); 
     } 
     x++; 
     Result = Result + "</tr>"; 
    } 

    Result += "</table></html>"; 

    JOptionPane.showMessageDialog(null, Result); 

} 

Результат:

Result

1

решаемые

public class assign3 { 

    public static void main(String[] args) { 

     String Boundary1 = JOptionPane.showInputDialog(null, "Please enter the first boundary of the multiplication table."); 
     String Boundary2 = JOptionPane.showInputDialog(null, "Please enter the second boundary of the multiplication table."); 

     int X = Integer.parseInt(Boundary1); 
     int Y = Integer.parseInt(Boundary2); 
     int j = 1; 
     String Result = " |"+"\t"; 
     int x = 1; 

     for(int i=1;i<=Y;i++){ 
       Result = Result + i + "\t"; 
      } 
      Result=Result+"\n"; 
      while (x <= X){ 
      if(x<10){ 
      Result=Result+ x + " |" +"\t"; 
      }else{ 
      Result=Result+ x + "|" +"\t"; 

      } 
      for(int i = 1;i<= Y; i++){ 
       j = i * x; 
       Result = Result + j +"\t"; 
      } 
      x++; 
      Result = Result + "\n"; 
     } 
     JTextArea jt=new JTextArea(Result); 
     jt.setEditable(false); 
     jt.setOpaque(false); 
     jt.setTabSize(3); 
     JOptionPane.showMessageDialog(null, jt);   
    } 
    } 

ВЫХОД:

output

+0

Спасибо за помощь, но цифры по-прежнему не выравниваются, как должны. – user3114770

+0

@ user3114770 Done:) - – Aarav

+0

@ user3114770 Что вы подразумеваете под [https://www.dropbox.com/s/6gtexqoj3rs7xvl/IMG-20140114-WA0000.jpg](https://www.dropbox.com/s /6gtexqoj3rs7xvl/IMG-20140114-WA0000.jpg) – Aarav

Смежные вопросы