So I have been working on this program and I cannot get the input from the 3 fields (a,b,c) to store as variables. Any help will be appreciated. Everything seems to work and if the button is pressed it closes the window but it will not proceed because the input is not stored.
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.io.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
public class Herons extends JFrame implements ActionListener {
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static String aa1;
public static String bb1;
public static String cc1;
public static JFrame main = new JFrame("Herons Formula");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
Herons object = new Herons();
}
Herons(){
//JFrame main = new JFrame("Herons Formula");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel myPanel = new JPanel(new GridLayout (0,1));
//JPanel pane = new JPanel(new GridLayout(0,1));
myPanel.setPreferredSize(new Dimension(250,300));
JTextField a = new JTextField(3);
JTextField b = new JTextField(3);
JTextField c = new JTextField(3);
JButton find = new JButton("Calculate!");
main.add(myPanel);
myPanel.add(new JLabel ("Input the lengh of each side:"));
main.add(myPanel);
myPanel.add(new JLabel ("A:"));
myPanel.add(a);
myPanel.add(new JLabel ("B:"));
myPanel.add(b);
myPanel.add(new JLabel ("C:"));
myPanel.add(c);
myPanel.add(find);
//find.setActionCommand("Calculate!");
find.addActionListener(this);
main.pack();
main.setVisible(true);
String aa = a.getText();
String bb = b.getText();
String cc = c.getText();
aa1 = aa;
bb1 = bb;
cc1 = cc;
//JOptionPane.showMessageDialog(null, myPanel);
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
//System.out.println("Action command for pressed button: " + actionCommand);
if (actionCommand == "Calculate!") {
main.setVisible(false);
myPanel.setVisible(false);
main.dispose();
//String aa = a.getText();
//String bb = b.getText();
//String cc = c.getText();
double aaa = Double.parseDouble(aa1);
double bbb = Double.parseDouble(bb1);
double ccc = Double.parseDouble(cc1);
double s = 0.5 * (aaa + bbb + ccc);
double area = Math.sqrt(s*(s-aaa)*(s-bbb)*(s-ccc));
area = (int)(area*10000+.5)/10000.0;
if (area == 0){
area = 0;
}
JOptionPane.showMessageDialog(null, "The area of the triangle is: " + area);
}
}
}
The problem is basically this:
class Herons {
static JTextField a;
Herons() {
JTextField a = new JTextField(); // 'a' is shadowed
}
}
When you say JTextField a = ... in the constructor it declares a different local variable called a and shadows the field.
It should be like this:
Herons() {
a = new JTextField(); // field 'a' is assigned
}
Otherwise you may have noticed that when you tried to call getText on your fields they were null in actionPerformed.
I found this page about hiding/shadowing if you want to read more.
As a side note, your variables also do not need to be static (and maybe shouldn't be since you're creating an instance of the class to refer to them).
You must get the value of the TextFields in the actionPerformed method, not in your constructor. When you get the value of these text fields in the constructor, they're empty, because they've just been added to the interface. So add this at the beginning of the method:
public void actionPerformed(ActionEvent e) {
String aa = a.getText();
String bb = b.getText();
String cc = c.getText();
and remove those lines from the constructor:
String aa = a.getText();
String bb = b.getText();
String cc = c.getText();
aa1 = aa;
bb1 = bb;
cc1 = cc;
Related
I am trying to use Groovy in order to convert string to the reflection code but I have "No such property" exception.
I have tried to make global all variables, change the reflection code and put #Field notation but problem still remaining. I put Groovy code inside "runTestSamples()".
MainClass - Test2
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.jacoco.agent.AgentJar;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IClassCoverage;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.data.SessionInfoStore;
import org.jacoco.core.instr.Instrumenter;
import org.jacoco.core.runtime.IRuntime;
import org.jacoco.core.runtime.LoggerRuntime;
import org.jacoco.core.runtime.RuntimeData;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
public class Test2 {
private Runnable targetInstance;
public Class<?> targetClass;
private static HashMap<Integer, String> testSamples;
private static HashMap<String, Integer> coverageData;
public String targetName;
public IRuntime runtime;
public Instrumenter instr;
public InputStream original;
public byte[] instrumented;
public RuntimeData data;
public MemoryClassLoader memoryClassLoader;
static Test2 t2 = new Test2();
int a;
public static void main(String[] args) throws Exception {
testSamples = new HashMap<Integer, String>();
coverageData = new HashMap<String, Integer>();
try {
t2.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public void execute() throws Exception {
testSamples = new HashMap<Integer, String>();
coverageData = new HashMap<String, Integer>();
targetName = SUTClass.class.getName();
runtime = new LoggerRuntime();
instr = new Instrumenter(runtime);
original = getTargetClass(targetName);
instrumented = instr.instrument(original, targetName);
original.close();
data = new RuntimeData();
runtime.startup(data);
memoryClassLoader = new MemoryClassLoader();
memoryClassLoader.addDefinition(targetName, instrumented);
targetClass = (Class<? extends Runnable>) memoryClassLoader.loadClass(targetName);
targetInstance = (Runnable) targetClass.newInstance();
// Test samples
runTestSamples();
targetInstance.run();
final ExecutionDataStore executionData = new ExecutionDataStore();
final SessionInfoStore sessionInfos = new SessionInfoStore();
data.collect(executionData, sessionInfos, false);
runtime.shutdown();
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(executionData, coverageBuilder);
original = getTargetClass(targetName);
analyzer.analyzeClass(original, targetName);
original.close();
for (final IClassCoverage cc : coverageBuilder.getClasses()) {
coverageData.put("coveredInstructions", cc.getInstructionCounter().getCoveredCount());
}
System.out.println(coverageData.get("coveredInstructions"));
System.out.println(a);
}
public static class MemoryClassLoader extends ClassLoader {
private final Map<String, byte[]> definitions = new HashMap<String, byte[]>();
public void addDefinition(final String name, final byte[] bytes) {
definitions.put(name, bytes);
}
#Override
protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
final byte[] bytes = definitions.get(name);
if (bytes != null) {
return defineClass(name, bytes, 0, bytes.length);
}
return super.loadClass(name, resolve);
}
}
private InputStream getTargetClass(final String name) {
final String resource = '/' + name.replace('.', '/') + ".class";
return getClass().getResourceAsStream(resource);
}
public void runTestSamples() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException, ClassNotFoundException {
// Test case
targetClass.getMethod("f", int.class, int.class).invoke(targetInstance, 2, 9);
// Groovy String to code
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate("targetClass.getMethod(\"f\", int.class, int.class).invoke(targetInstance, 2, 9);");
}
}
Exception
groovy.lang.MissingPropertyException: No such property: targetClass for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:65)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:309)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:437)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:475)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:446)
at Test2.runTestSamples(Test2.java:119)
at Test2.execute(Test2.java:66)
at Test2.main(Test2.java:43)
the problem in this code:
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate("targetClass.getMethod(\"f\", int.class, int.class).invoke(targetInstance, 2, 9);");
when you call shell.evaluate imagine that you call absolutely new class that doesnot know anything about your current variables like targetClass
so, GroovyShell telling that there is no such property: targetClass
to fix it - you have just to populate binding - pass the variables values and names that should be visible inside the shell.evaluate(...).
Binding binding = new Binding();
binding.setVariable("target", targetClass) //pass targetClass as target variable name
binding.setVariable("instance", targetInstance)
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate("target.getMethod(\"f\", int.class, int.class).invoke(instance, 2, 9)");
another point - groovy is already dynamic language and you could simplify your nested script from this:
target.getMethod("f", int.class, int.class).invoke(instance, 2, 9)
to this:
instance."f"(2, 9)
and finally maybe you don't need to use the groovyshell because the following code dynamycally calls the method:
class A{
def f(int a, int b){ a+b }
}
def instance = new A()
def method = "f"
def params = [2,9]
println instance."${method}"(params)
I am new to spark and trying to learn it. I am trying to create a Dataset from a textFile using a class. When i do a dataset.show(), it shows all blank and columns length shows 0.
Code:
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
public class DatasetExample {
public static void main(String[] args) {
test(fileName);
}
static final String fileName = "inputFile";
static SparkConf conf = new SparkConf().setMaster("local").setAppName("Test");
static JavaSparkContext sc = new JavaSparkContext(conf);
static SparkSession session = SparkSession.builder().config(conf).getOrCreate();
private static void test(String fileName){
JavaRDD<Input> rdd = sc.textFile(fileName).map(new Function<String, Input>() {
#Override
public Input call(String s) throws Exception {
String[] str = s.split(",");
System.out.println(str[0] + " and " + str[1] + " and " + str[2]);
return new Input(str[0], str[1], Integer.parseInt(str[2]));
}
});
Dataset<Row> dataSet = session.createDataFrame(rdd, Input.class);
dataSet.show();
System.out.println("Column length is: " + dataSet.columns().length);
}
static class Input{
String key;
String value;
int number;
Input(String key, String value, int number){
this.key = key;
this.value = value;
this.number = number;
}
}
}
Output shown is:
foo and A and 1
foo and A and 2
foo and A and 1
foo and B and 2
foo and B and 1
bar and C and 2
bar and D and 3
dek and X and 3
max and X and 3
eer and P and 3
++
||
++
||
||
||
||
||
||
||
||
||
||
++
Column length is: 0
I do not want to explicitly define schema but I want it to take schema from class structure. What I might be missing?
From JavaBeans Wiki Definition:
In computing based on the Java Platform, JavaBeans are classes that
encapsulate many objects into a single object (the bean). They are
serializable, have a zero-argument constructor, and allow access to
properties using getter and setter methods
So, make it public and generate getter/setter:
public static class Input {
String key;
String value;
int number;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Input(String key, String value, int number) {
this.key = key;
this.value = value;
this.number = number;
}
}
and you will have output.
I have a problem with functionality of my simple program I am making at the moment. I am trying to create two objects, each of them is asking user to provide a name and then choose from few options, by using Scanner. First object, monster of class createMonster, is asking user to provide information through Scanner. However, while creating second object monster2 of class createMonster, program does not asking for user input.
Do I need to do some changes in my class CreateScanner or is it a bigger problem?
public class MainClass {
public static void main(String[] args) {
RandomMonsterGenerator monster = new RandomMonsterGenerator();
monster.createMonster();
RandomMonsterGenerator monster2 = new RandomMonsterGenerator();
monster2.createMonster();
}
}
RandomMonsterGenerator code:
public class RandomMonsterGenerator {
// Objects
Attributes attr = new Attributes();
CreateScanner createScanner = new CreateScanner();
// Variables
String monsterName;
String attributesValues;
int choice;
// Main method for generating monster
public void createMonster() {
attr.generateAttributes();
generateName();
chooseClass();
System.out.println("Generating random stats:");
attributesValues = attr.toString();
System.out.println(attributesValues);
createScanner.closeScanner();
}
// Generating monster name
private void generateName() {
System.out.println("Name your monster: ");
monsterName = createScanner.stringInput();
System.out.println("Name of the monster: " + monsterName);
}
// Choosing a class
private void chooseClass() {
System.out.println("Class descriptions: ");
System.out.println("Warrior has +2 to Strength and +2 to Condititon.");
System.out.println("Thief has +2 to Dexterity and +2 to Charisma.");
System.out.println("Mage has +2 to Intelligence and +2 to Wisdom.");
System.out.println("**************************************************");
System.out.println("Choose your class from following options: ");
System.out.println("Warrior, press '1'");
System.out.println("Thief, press '2'");
System.out.println("Mage, press '3'");
choice = createScanner.intInput();
switch(choice) {
case 1:
Warrior warrior = new Warrior(attr);
System.out.println(monsterName + " is a warrior.");
break;
case 2:
Thief thief = new Thief(attr);
System.out.println(monsterName + " is a thief.");
break;
case 3:
Mage mage = new Mage(attr);
System.out.println(monsterName + " is a mage.");
break;
default:
System.out.println("No option choosen.");
break;
}
}
}
CreateScanner code:
import java.util.Scanner;
public class CreateScanner {
Scanner sc = new Scanner(System.in);
public String stringInput() {
String input = "";
if (sc.hasNextLine()) {
input = sc.nextLine();
}
return input;
}
public int intInput() {
int input2 = 0;
if (sc.hasNextLine()) {
input2 = sc.nextInt();
}
return input2;
}
public void closeScanner() {
sc.close();
}
}
Two things.
First, don't close the scanner until you're done with it. This closes the System.in
as well and as soon as you do that you won't be getting anymore input. This is why it just skips over the second RandomMonsterGenerator input.
Second, only create one Scanner and pass it to your RandomMonsterGenerator as an argument. This keeps things simple.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
RandomMonsterGenerator monster = new RandomMonsterGenerator(scanner);
RandomMonsterGenerator monster2 = new RandomMonsterGenerator(scanner);
}
I have a Combo Bx (Dropdown box) with an index range of 0-20. If there anyways I can use that index to specify which object I want data from? All of the objects use the same naming convention obj0, obj1, obj2, etc. Basically something like this...
public abstract class Person {
private String name;
private String title;
private String email;
private String job;
public Person(String name, String title, String email, String job){
this.name = name;
this.title = title;
this.email = email;
this.job = job;
}
//Getters and Setters
}
public class main extends javax.swing.JFrame {
...misc code...
private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {
Person obj0 = new Person("Jon Doe",
"Program Coordinator",
"jon.doe#test.com",
"Faculty");
Person obj1 = ...
...
Person obj20 = ...
/*
Onclick it uses the index of the current index in the combobox (dropdown)
to specify which object to get the data from.
*/
private void btn_GetActionPerformed(java.awt.event.ActionEvent evt) {
//Uses the obj naming convention plus the index
string foo = "obj" + toString(combobox_Name.getSelectedIndex());
//Fills the textbox using the above string and the getName method
txtbox_username.setText(ToObject(foo).getName);
}
I have created a basic design of what I think you want:
This code creates 20 objects, adds them to a combobox and uses their predefined name when selected to change a textfield.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class ObjExample {
String name;
public ObjExample(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
public class Main extends JFrame implements ActionListener {
JComboBox jcb = new JComboBox();
JTextField jtf = new JTextField("Text Field");
public Main() {
setSize(200, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i = 0; i <= 20; i++) {
jcb.addItem(new ObjExample(Integer.toString(i)));
}
jcb.addActionListener(this);
add(jcb);
add(jtf);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jcb) {
ObjExample obj = (ObjExample) jcb.getSelectedItem();
jtf.setText(obj.toString());
}
}
}
I am trying to print out the answer for the Area of a circle in the myPrint(); method but it keeps calculating zero why?
I did my calculations in the Math(); method that I created. I am very new at coding and would greatly appreciate the help.
Thanks
package Project1;
import java.util.Scanner;
public class Code1 {
static String myStr;
static double radius;
static double answer;
static double pie;
public static void main(String[] args){
Name();
Info();
Math();
myPrint();
}
public static void Name(){
Scanner input = new Scanner(System.in);
System.out.println("What Is Your Name");
myStr = input.nextLine();
}
public static void Info(){
Scanner input = new Scanner(System.in);
String myStr;
System.out.println("What is Your Phone Number");
myStr = input.nextLine();
System.out.println("What is Your Age");
myStr = input.nextLine();
System.out.println("What is Your Postal Code");
myStr = input.nextLine();
}
public static void Math(){
double radius,answer;
double pie = 3.14;
Scanner input = new Scanner(System.in);
System.out.println("What is the Area of the Circle");
radius = input.nextDouble();
answer = pie *(radius * radius);
}
public static void myPrint(){
System.out.print("The answer is:"+ answer);
}
}
You have the static variable answer, but you declare answer again in Math(), so when you assign answer equal to your calculation, that's not changing the global variable, but it's changing the local variable. When you print answer in myPrint(), the answer will be 0 because it will have been assigned a value of 0 by default.