How to fix this Bad operand - java

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

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.

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

Adding 2 Integers using AWT

I'm trying to create a Java AWT program with these codes:
import javax.swing.*;
import java.awt.*;
public class Exer1 extends JFrame {
public Exer1(){
super ("Addition");
JLabel add1 = new JLabel("Enter 1st Integer: ");
JTextField jtf1 = new JTextField(10);
JLabel add2 = new JLabel("Enter 2nd Integer: ");
JTextField jtf2 = new JTextField(10);
JButton calculate = new JButton("Calculate");
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(add1);
add(jtf1);
add(add2);
add(jtf2);
add(calculate);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] a){
Exer1 ex1 = new Exer1();
}
}
My problem is HOW to add these 2 integers using JTextField. Can someone help me? Thank you so much. :)
You need to use ActionListener on your JButton.
Then you need to get int's from JTextField's and sum them like next:
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
System.out.println("sum=" + (i1 + i2));
} catch (Exception e1){
e1.printStackTrace();
}
}
});
Generally, you should create an event listener for click events on your button: Lesson: Writing Event Listeners. In that handler, you would take contents of your two text fields, convert them to integers:
Integer i1 = Integer.valueOf(jtf1.getText());
Then you can add those two integers and display them in another control or do anything else with them.
Start with How to Use Buttons, Check Boxes, and Radio Buttons and
How to Write an Action Listeners
This will provide you with the information you need to be able to tell when the user presses the button.
JTextField#getText then return's String. The problem then becomes a problem of converting a String to a int, which if you take the time, there are thousands of examples demonstrating how to achieve that
Once you've played around with oddities of converting String to a int, you could take a look at How to Use Spinners and How to Use Formatted Text Fields which perform there own validation on the values been entered

Celsius to Fahrenheit Converter GUI program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm having trouble figuring out the logic behind why my code isn't working. I'm new to GUI programming and java as well, and I'm still a little rough on the format of creating a GUI program. In the code I'm trying to convert Celsius to Fahrenheit and vice versa. Any help would be appreciated. Thanks!
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class myGUIClass<FahrenheitButtonHandler> extends JFrame{
private JLabel msgCelsius;
private JLabel msgFahrenheit;
private JButton btnCelsius;
private JButton btnFahrenheit;
private static JTextField fldCelsius;
private static JTextField fldFahrenheit;
Container contain;
public myGUIClass(String myGUIWindow){
super("myGui");
contain = getContentPane();
contain.setLayout(new FlowLayout());
msgCelsius = new JLabel("Degrees in Celsius");
btnCelsius = new JButton("Convert From Celsius to Fahrenheit");
fldCelsius = new JTextField(15);
msgFahrenheit = new JLabel("Degrees in Fahrenheit ");
btnFahrenheit = new JButton("Convert From Fahrenheit to Celsius");
fldFahrenheit = new JTextField(15);
contain.add(msgCelsius);
contain.add(fldCelsius);
contain.add(btnCelsius);
contain.add(msgFahrenheit);
contain.add(fldFahrenheit);
contain.add(btnFahrenheit);
CelsiusButtonHandler btnHandlerCelsius = new CelsiusButtonHandler();
btnCelsius.addActionListener(btnHandlerCelsius);
FahrenheitButtonHandler btnHandlerFahrenheit = new FahrenheitButtonHandler();
btnFahrenheit.addActionListener(btnHandlerFahrenheit);
setSize(400,200);
setVisible(true);
}//end method
private class CelsiusButtonHandler implements ActionListener{
//#Override
//implement the listener interface methods to process the events
public void actionPerformed(ActionEvent ae){
Integer celsius;
Integer fahrenheit;
try{
if (ae.getSource() == btnCelsius){
celsius = Integer.parseInt(fldCelsius.getText());
fahrenheit = Math.round((9 /(float)5)) * (celsius + 32);
fldFahrenheit.setText(fahrenheit.toString());
}//end if
}//end try
catch (Exception e){
fldFahrenheit.setText("");
}//end catch
}//end inner class
}//end class
private class FahrenheitButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent a){
Integer fahrenheit1;
Integer celsius1;
try{
if(a.getSource()== btnFahrenheit){
fahrenheit1 = Integer.parseInt(fldFahrenheit.getText());
celsius1 = Math.round((5 / (float)9)) * (fahrenheit1 - 32);
fldCelsius.setText(celsius1.toString());
}//end if
}//end try
catch (Exception e){
fldCelsius.setText("");
}//end catch
}//end method
}//end private class
public static void main (String[] args){
#SuppressWarnings("rawtypes")
myGUIClass guiClass = new myGUIClass(null);
guiClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end main
}//end outer class
//theres a problem with the math in these lines:
//am i not casting these correctly? whenever i input 50 i'm supposed to get 122 but i get 164.
//fahrenheit = Math.round((9 /(float)5)) * (celsius + 32);
//celsius1 = Math.round((5 / (float)9)) * (fahrenheit1 - 32);
Ignoring the code issues that make the example uncompliable...
You have an integer division problem...
celsius = (5 / 9) * (fahrenheit - 32);
If 5/9 = 0 as the resulting value is converted to an integer.
Try using something more like...
celsius = Math.round((5 / (float)9)) * (fahrenheit - 32);
Now, personally, I would be using a double or float instead of an int and formatting the result but that's me. You'll need to do the same thing FahrenheitButtonHandler
In your FahrenheitButtonHandler class, you are also applying the wrong value to the text field...
celsius1 = Integer.parseInt(fldFahrenheit.getText());
fahrenheit1 = celsius1*(9/5)+32;
fldCelsius.setText(celsius1.toString());
You applying the celsius1 value, which is the value your extract from the fldFahrenheit field, not the calculated result, it should be
fldCelsius.setText(fahrenheit1.toString());
...but remember, there is still the interger division problem you need to correct for this...
Finally, you registered the wrong ActionListener to the btnFahrenheit
FahrenheitButtonHandler btnHandlerFahrenheit = new FahrenheitButtonHandler();
btnFahrenheit.addActionListener(btnHandlerCelsius); // <-- Wrong listener...
It should be...
FahrenheitButtonHandler btnHandlerFahrenheit = new FahrenheitButtonHandler();
btnFahrenheit.addActionListener(btnHandlerFahrenheit);

How to create an array by inputting numbered into a textfield, Java applet

My assignment is to input 20 numbers via a text field then out the mean, the median and the total using a while loop. I should be able to figure out the while loop myself, but I can't get the text field to input numbers into an array. Please help, here is my code so far:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
public class whileloopq extends Applet implements ActionListener
{
Label label;
TextField input;
int[] numArray = new int[20];
int num;
public void init ()
{
Label label = new Label("Enter numbers");
TextField input = new TextField(5);
add(label);
add(input);
input.addActionListener(this);
}
public void actionPerformed (ActionEvent ev)
{
int num = Integer.parseInt(input.getText());
int index = 0;
numArray[index] = num;
index++;
input.setText("");
}
public void paint (Graphics graf)
{
graf.drawString("Array" + numArray, 25, 85);
}
}
Any help would be much appreciated.
(Answer written under the assumption that this is a homework assignment.)
You know how to parse an integer from a string, as you show with your usage of Integer.parseInt, but you are calling it to parse the entire 20 characters as one integer. You need to get each character individually to be parsed.
I recommend using a for loop, and String#substring to substring the input text into several strings of length one.
Alternatively, you can split the input text around an empty string and then iterate through the resulting array (note that the first string in the array will be empty), but the other approach is more likely the one expected from someone new to Java, so you'll have to use your judgement here.
In actionPerformed() you are trying to read from class filed input.setText("");
but in init() you didn't initialized that field but created and added to applet local variable
TextField input = new TextField(5);
so class field is steal null. Change it to
input = new TextField(5);
import java.awt.*;
public class frame4array extends Frame
{
Checkbox c1[];
TextField t1[];
int i;
frame4array(String p)
{
super(p);
c1=new Checkbox[2];
t1=new TextField[2];
for(i=0;i<2;i++)
{
t1[0]=new TextField();
t1[0].setBounds(200, 50, 150, 30);
t1[1]=new TextField();
t1[1].setBounds(200, 80, 150, 30);
c1[0]=new Checkbox("Singing");
c1[0].setBackground(Color.red);
c1[0].setBounds(430,200,120,40);
c1[1]=new Checkbox("Cricket",true);
}
for(i=0;i<2;i++)
{
add(t1[i]);
add(c1[i]);
}
setFont(new Font("Arial",Font.ITALIC,40));
}
public static void main(String s[])
{
frame4array f1=new frame4array("hello");
f1.setSize(600,500);
f1.setVisible(true);
}
}

Categories

Resources