public class Tile extends JLabel{
private char _c;
static char randomChar;
public Tile(char c, Color background) {
super();
setBackground(background);
setOpaque(true);
_c = c;
}
public static char randomLetter() {
Random r = new Random();
randomChar = (char) (97 + r.nextInt(25));
return randomChar;
}
public static char getChar(){
return Tile.randomLetter();
}
public static String convert(){
char ch = Tile.randomLetter();
return String.valueOf(ch);
}
public static void main(String[] args) {
Tile tile = new Tile(Tile.convert(), Color.BLUE);
Tile tile1 = new Tile(Tile.randomLetter(), Color.RED);
Tile tile2 = new Tile(Tile.randomLetter(), Color.GREEN);
Tile tile3 = new Tile(Tile.randomLetter(), Color.YELLOW);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new GridLayout(4,1));
frame.setSize(500, 800);
frame.setVisible(true);
frame.add(tile);
frame.add(tile1);
frame.add(tile2);
frame.add(tile3);
System.out.println(Tile.convert());
所以我试图制作一个游戏,有四个瓷砖,我使用Jlabels作为我的瓷砖。我的瓷砖有一个字符和一个颜色,因为jlabels不接受字符,我试图制作一个方法将我的字符转换为字符串,然后将它放在我的jlabel中,以便接受它。我该怎么做?
答案 0 :(得分:4)
假设一个名为#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
/* You need an array of int's with size equal to the number of letters
* int the alphabet
*/
int count['Z' - 'A' + 1];
/* You need some space to store the text, `str' will become a poitner
* when you pass it to `fgets()' pointing to an array of 1000 `chars'
*/
char str[1000];
/* Initialize all the counters to 0 */
for (int i = 0 ; i < sizeof(count) / sizeof(*count) ; ++i)
count[i] = 0;
printf("Enter any string : ");
/* Read the string, use `fgets()` and prevent a buffer overflow */
if (fgets(str, sizeof(str), stdin) == NULL)
return -1;
/* Now count the letters */
for (int i = 0 ; ((str[i] != '\0') && (str[i] != '\n')) ; ++i)
{
/* If it's not a letter, go to the next one */
if (isalpha((int) str[i]) == 0)
continue;
/* It's a letter, count it at the correct position */
count[toupper((int) str[i]) - 'A'] += 1;
}
/* Print the count of each letter, skipping those that did not appear */
for (int i = 0 ; i < sizeof(count) / sizeof(*count) ; ++i)
{
if (count[i] == 0)
continue;
fprintf(stderr, "Number of %c's : %d\n", i + 'A', count[i]);
}
return 0;
}
的char变量,就像
myChar
会起作用。