Should simply changing the Locale change decimal number notation in Java? - java

Yes, I read through the various post with regards to this but their scenarios where a bit different and didn't explain what is going on in the background.
Lets say the following program is created in a country where decimal points use '.' notation but then executed in a country which uses ',' notation.
For example, 1.23 and 1,23 are technically the same number but with different notations.
import java.awt.FlowLayout;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import javax.swing.*;
class LocaleTestDecimal extends JFrame implements ActionListener
{
static JTextField t;
static JFrame f;
static JButton b;
static JLabel l;
static JLabel localLabel;
LocaleTestDecimal()
{
}
public static void main(String[] args)
{
Locale locale = Locale.getDefault();
f = new JFrame("Locale = " + locale.toString());
l = new JLabel("nothing entered");
b = new JButton("submit");
LocaleTestDecimal te = new LocaleTestDecimal();
b.addActionListener(te);
t = new JTextField(16);
//default value of 1.23
t.setText(Double.toString(1.23));
NumberFormat format = NumberFormat.getInstance(Locale.ITALY);
Number number = null;
try {
number = format.parse("1.23");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
double d = number.doubleValue();
l.setText(Double.toString(number.doubleValue()));
JPanel p = new JPanel();
p.add(t);
p.add(b);
p.add(l);
f.add(p);
f.setSize(300, 300);
f.show();
}
// if the button is pressed
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("submit")) {
// set the text of the label to the text of the field
l.setText(t.getText());
// set the text of field to blank
t.setText(" ");
}
}
}
The above code runs fine and as expected when my Locale is set to English.
After changing my Windows Region and Format to Italy.
And changed my Eclipse VM arguments
The numbers still use the '.' notation for numbers. Even using the NumberFormat didn't seem to change the value on the JFrame.
The title of the JFrame contains the locale which confirms it is Italy.
Question 1:
Why am I not seeing numbers using the ',' notation?
Question 2:
As these numbers expected to dynamically change simply based on the Locale set?

Related

Array input numbers 0-2 and output corresponding letters a,b,c

I have created the array with the elements ("A","B","C")
if the user enters ‘0’ output “A” to the outputlabel,e.g.,outputLabel.setText(array[0]).
I am just getting errors in the command prompt when i enter in the correct numbers. Any help with this would be highly appreciated. I have the gui created correctly. Just unsure about the array and outputs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiFrame extends JFrame implements ActionListener {
String[] stringArray = {"A", "B", "C"};
JTextField inputArea;
JLabel theOutputLabel;
public GuiFrame() {
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Please enter the index of the array to
output: ");
JLabel outputLabel = new JLabel("Array index");
JTextField userInput = new JTextField ();
JButton inputButton = new JButton("Go");
String inputFromUser = userInput.getText();
Container contentPane = getContentPane();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label1);
panel.add(outputLabel);
panel.add(userInput);
panel.add(inputButton);
inputButton.addActionListener(this);
contentPane.add(panel);
setSize(250, 250);
setVisible(true);
userInput.setSize(250,50);
System.out.println(inputFromUser);
String stringArray[] = new String[3];
}
public static void main(String[] args){
new GuiFrame();
}
#Override
public void actionPerformed(ActionEvent e) {
String userInput = inputArea.getText();
try {
do {
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
}while(e.getActionCommand().equals("0") || e.getActionCommand().equals("1") || e.getActionCommand().equals("2"));
System.out.println("You have entered a number that is outside of the range of the array index please try again");
}
catch (ArrayIndexOutOfBoundsException arrayError){
System.out.println("Array Index Out of Bounds");
arrayError.printStackTrace();
}
}
}
What you have now defeats the purpose of using an array. Imagine you had to do it for all letters of the Alphabet, would you add 26 conditions? What if you have thousands of options?
Thererfore, instead of
/** DON'T DO THIS */
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
You should parse the input and get element from the array according to the index.
/** DO THIS */
int index = Integer.parseInt(e.getActionCommand());
theOutputLabel.setText(stringArray[index]);
Integer.parseInt() could throw a java.lang.NumberFormatException if the input is not a valid integer, so you have to add a catch for that.
If you want to have the index available for test in the while condition, then declare it without initializing before the do block.
Hey apart from what #isapir has suggested also please check that there are few places in your code that would result into NullPointerExceptions like :
JTextField inputArea; // Not assigned will lead to NPE
JLabel theOutputLabel; // Not assigned will lead to NPE
String userInput = inputArea.getText(); // Because of inputArea unassigned this line will throw NPE for sure so fix that as well.
So I'm assuming what exception you were getting in cmdPrompt would be NPE one so better fix your basic bug first and check your constructor code properly. Lastly, it's always better to share the exception details before post questions on SO.
e.getActionCommand().equals("0") this line will not give what you have entered in frame pop-up. Check this also instead use inputArea.getText() will give you user's entered number digit.

Displaying dominoes with Unicode charset

I'm currently creating a domino game in java. The idea is to load the domino images, rotate them if necessary, and then display them on the screen.
A few weeks ago I posted a question asking how to rotate an imageIcon in Java.
Someone replied as follows: "The Unicode charset includes dominoes".
So if I understand this correctly, instead of loading domino images I can use Unicode character set to display the dominoes on the screen? I cannot find any examples on Internet how to do this. Any one can give me an example of how this is done?
Dominoes are represented by UTF8 characters from U+1F030 to U+1F09F. There is a special block for them.
🀰 🀱 🀲 🀳 🀴 🀵 🀶 🀷 🀸 🀹 🀺 🀻 🀼 🀽 🀾 🀿
🁀 🁁 🁂 🁃 🁄 🁅 🁆 🁇 🁈 🁉 🁊 🁋 🁌 🁍 🁎 🁏
🁐 🁑 🁒 🁓 🁔 🁕 🁖 🁗 🁘 🁙 🁚 🁛 🁜 🁝 🁞 🁟
🁠 🁡 🁢 🁣 🁤 🁥 🁦 🁧 🁨 🁩 🁪 🁫 🁬 🁭 🁮 🁯
🁰 🁱 🁲 🁳 🁴 🁵 🁶 🁷 🁸 🁹 🁺 🁻 🁼 🁽 🁾 🁿
🂀 🂁 🂂 🂃 🂄 🂅 🂆 🂇 🂈 🂉 🂊 🂋 🂌 🂍 🂎 🂏
🂐 🂑 🂒 🂓 🂔 🂕 🂖 🂗 🂘 🂙 🂚 🂛 🂜 🂝 🂞 🂟
According to https://unicode-table.com:
Domino Tiles is a Unicode block containing characters for representing game situations in dominoes. The block includes symbols for the standard six dot tile set and backs in horizontal and vertical orientations
See https://unicode-table.com/en/blocks/domino-tiles/
According to The Unicode Standard, Version 10.0:
The domino tile symbols do not represent the domino pieces per se, but instead constitute graphical symbols for particular orientations of the dominoes, because orientation of the tiles is significant in discussion of dominoes play. Each visually distinct rotation of a domino tile is separately encoded. Thus, for example, both U+1F081 domino tile vertical-04-02 and U+1F04F
domino tile horizontal-04-02 are encoded, as well as U+1F075 domino tile vertical-02-04 and U+1F043 domino tile horizontal-02-04. All four of those symbols represent the same game tile, but each orientation of the tile is visually distinct and requires its own symbol for text. The digits in the character names for the domino tile symbols reflect the dot patterns on the tiles.
You also have to choose a font able to display them.
The previous answer is correct. However:
More convenient page for characters: http://www.alanwood.net/unicode/domino-tiles.html
Plus, the actual printing of those characters is described here.
An example of printing one of the dominoes:
class Scratch {
public static void main(String[] args) {
System.out.println(new String(Character.toChars(127026)));
}
}
This prints 🀲 on IntelliJ's console. Your results may vary, depending on your font.
The following code shows how to ascertain the installed fonts that support displaying this group of Unicode characters (3 out of over 250 fonts installed here), and displaying them in a text area.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.EmptyBorder;
import java.util.Vector;
public class DominoTiles {
private JComponent ui = null;
public static final int DOMINO_TILE_START = 127024;
public static final int DOMINO_TILE_END = 127123;
String dominoeTiles;
JTextArea textArea = new JTextArea(4, 10);
DominoTiles() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
StringBuilder sb = new StringBuilder();
for (int ii = DOMINO_TILE_START; ii <= DOMINO_TILE_END; ii++) {
String s = new String(Character.toChars(ii));
sb.append(s);
}
textArea.setText(sb.toString());
textArea.setLineWrap(true);
ui.add(new JScrollPane(textArea));
String[] fontFamilies = GraphicsEnvironment.
getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
final Vector<String> compatibleFonts = new Vector<>();
for (String fontFamily : fontFamilies) {
Font f = new Font(fontFamily, Font.PLAIN, 1);
if (f.canDisplayUpTo(sb.toString()) < 0) {
compatibleFonts.add(fontFamily);
}
}
final JList list = new JList(compatibleFonts);
ui.add(new JScrollPane(list), BorderLayout.LINE_START);
ListSelectionListener listSelectionListener = new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
String fontFamily = list.getSelectedValue().toString();
Font f = new Font(fontFamily, Font.PLAIN, 60);
textArea.setFont(f);
}
}
};
list.addListSelectionListener(listSelectionListener);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
DominoTiles o = new DominoTiles();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
This example shows how to turn Unicode characters into images (plus a few more tricks of rendering them).

Calculator in Swing Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class calc implements ActionListener
{
JFrame f;
JPanel p;
JTextField jt1,jt2,jt3;
JButton j1,j2;
static double a=0,b=0,result=0;
static int operator=0;
calc()
{
f = new JFrame();
p = new JPanel();
jt1 = new JTextField(20);
jt2 = new JTextField(20);
j1 = new JButton("+");
j2 = new JButton("-");
jt3 = new JTextField();
f.add(p);
p.add(jt1);
p.add(jt2);
p.add(j1);
p.add(j2);
j1.addActionListener(this);
j2.addActionListener(this);
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()=="+")
{
a=Double.parseDouble(jt1.getText());
operator = 1;
b=Double.parseDouble(jt2.getText());
switch(operator)
{
case 1: result=(a+b);
}
jt3.setText(result);
}
}
public static void main(String [] args)
{
calc obj = new calc();
}
}
i'm making a calculator using java swing, the output of this code is:
calc.java:48 error: incompatible types: double cannot be converted to String
jt3.setText(result);
i think this is not a big error, well help me to get rid of this, i just want to sum didn't add more functions like multiply or minus or etc, i just want to run as small code first then i'll add more functions to it well help will be appreciated thanks.
Easy way is:
//jt3.setText(result);
jt3.setText("" + result);
This will force the compiler to create a String of the two values.
Use jt3.setText(String.valueOf(result));.
.setText() only accept String type.
You can see it in Class TextField.
Class text can accept only string values.
where the result you provided as an argument is Double
You can use this to convert it as a string
string converted = Double.toString(result);
This error is because JTextField is expecting a String to set the text to it, not a double, so, you need to either:
jt3.setText(String.valueOf(result));
Or
jt3.setText("" + result);
The first one will convert result to a String value, while the second one will concatenate an empty String to result, and return a String as well.
However one last suggestion I want you to take note of is, don't use single letter variables, make them more descriptive, for example:
JFrame f; //This should be JFrame frame;
The same for the JPanel and the rest of your variables, since in larger programs it could be hard to remember that f means a JFrame and not the conversion to Fahrenheit from Celsius or a formula like F = m * a, it may be confusing and really hard to debug / understand later on.
And also as has been said in the comments above, use .equals to compare String in Java, see How do I compare strings in Java? for more on this

How to fix this Bad operand

I Need To convert years of days and this error stops me.
help please.. need to pass it now.
error: bad operand types for binary operator '*'
error: result = screen * 365;
^
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DaysOfYears extends JFrame implements ActionListener
{
JTextField screen = new JTextField(30);
JButton conBtn = new JButton("Convert");
JLabel jb = new JLabel ("");
private double result;
public DaysOfYears(){
super("Convert Your Years in Days");
setSize(400, 200);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(screen);
add(conBtn);
add(jb);
conBtn.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
result = screen * 365;
jb.setText(""+result);
}
public static void main (String[] args) {
DaysOfYears days = new DaysOfYears();
days.show(true);
}
}
I think you wanted to parse the text value of your JTextField and then perform your multiplication. Something like,
result = Integer.parseInt(screen.getText()) * 365;
Note that leap years have 366 days.
The JTextField holds its contents as String. You will need to convert it to integer unless of course you are supplying a string representation of a double data type within the JTextField.
Try something like:
result = Integer.valueOf(screen.getText()) * 365;
Here screen is a object of JTextFieldso multiply operation will not perform on the object of JTextField type you can grab the values of this object convert it into any Number type then try to multiplying. It will solve your problem .
Try this......
result = Integer.parseInt(screen.getText()) * 365;
// this will perform multiply actually. Thnak you

JButton set the button text to a variable

I will make a java game similar to cookie clickers, but is seems that I can't put a variable as a text in the button.
This is what is causing the problems, because the variable isn't a string(I cut out the other part of the code, because it's not important for now):
import javax.swing.JFrame;
import javax.swing.JButton;
public class Frame {
public static int num1 = 0;
public static void main(String[] args){
JFrame f = new JFrame("Cookie Clicker");
JButton b1 = new JButton(num1);
f.setSize(500, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(b1);
}
}
As you can see there's the num1 variable in there and it won't let it to be there. Any ideas how to make it work?
See: http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
There exists no constructor for the following:
new JButton(int);
For converting int to String see: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html ... more specifically, use:
Example use of String.valueOf(int):
int fiveInt = 5;
String fiveString = String.valueOf(fiveInt); // sets fiveString value="5"
Try to get the value of int to String:
JButton b1 = new JButton(String.valueOf(num1));
You need to make a string representation of your integer variable, as described here: How do I convert from int to String?.

Categories

Resources