【问题标题】:printing Random Unicode Characters in java through infinite FOR loop通过无限 FOR 循环在 java 中打印随机 Unicode 字符
【发布时间】:2015-01-03 04:25:26
【问题描述】:

我想通过使用无限 for loop 在 java 中的 JFRAME 中打印随机 Unicode 字符。

我是java编程新手,希望答案不要太复杂。

这是目前的代码-

import java.awt.*;
import javax.swing.*;
import java.util.*;

public class Matrix extends JFrame{
    private static final int NUMBER_OF_REPS = 0;

    public static void main(String[] args) {
        int a;

        Random rand=new Random();

        for(a=1;a>0;)
        {
            JLabel lbl=new JLabel();
            lbl.setForeground(Color.GREEN);
            lbl.setFont(new Font("MS Arial Unicode",Font.BOLD,12));
            lbl.setText("\\u30"+Integer.toHexString(rand.nextInt(96) + 160));
        }

        JFrame frame=new JFrame();
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.getContentPane().setBackground(Color.BLACK);

        //error! lbl cannot be resolved to a variable
        frame.getContentPane().add(lbl);
        frame.getContentPane().setLayout(new FlowLayout());
    }  
}

【问题讨论】:

  • 如果您提供有关您尝试过的东西的详细信息会很有帮助
  • 对新程序员的一般建议:将您的问题分解为更小的问题,并专注于独立解决每个问题。在这种情况下,您可以将其分解为两个问题: 1. 使用 for 循环生成随机 Unicode 字符。 2. 创建JFrame 并将文本写入其中。然后,将这些问题分解为更小的问题。这将帮助您逐步学习并提出清晰、简洁的问题。祝你好运!
  • 我搜索了几个小时,但找不到我正在寻找的具体答案;我想创建一个程序,使用循环在 jframe 中随机生成和显示 unicode 字符。
  • lbl 在 for 循环结束时超出范围。重写您的代码,以便您可以在循环内移动frame.getContentPane().add(lbl);
  • 如何重复制作新的 jlabels 并使用循环在其中添加随机字符?

标签: java for-loop unicode infinite


【解决方案1】:

我使用了一个 while 循环,它们更容易处理无限数。至于 JFRAME,你会想看看另一个答案,因为我对 javax.swing 不是很好。* 现在它只是把它放到控制台中

public Random random = new Random();

public static void main(String[] args) {
    while(true) {
        int i = random.nextInt(127);
        System.out.print((char)i);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多