I'm trying to write down something more sophisticated than simple Fahrenheit to Celsius and vice versa converter. I'm trying to use JoptionPane for better fell but I'm stuck in one place and have no idea how to resolve this (line 32 and 37 - method not applicable for the arguments ()) any help will be appreciated.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class ex74v3 {
public static void main(String[] args) {
temp();
new ex74v3();
}
public ex74v3() {
boolean done=false;
while(!done){
done=true;
String[] ans=new String[11];
String[] choice={
"(°F) to (°C)",
"(°C) to (°F)",
};
int choice_indx=JOptionPane.showOptionDialog(null, "Choose type of conversion", "Choice",
0,JOptionPane.QUESTION_MESSAGE ,
null,choice,0);
ans[0]=choice[choice_indx];
if(choice_indx==1 || choice_indx==2) {
done=false;
}else{
choice_indx=JOptionPane.showMessageDialog(null, "Fahrenheit to Celsius: " + baseFtC() + " (°C)");
}
if(choice_indx==2) {
done=false;
}else{
choice_indx=JOptionPane.showMessageDialog(null, "Celsius to Fahrenheit : " + baseCtF() + " (°F)");
}
}
}
public static int temp() {
String value = JOptionPane.showInputDialog(null, "Enter value ");
#SuppressWarnings("unused")
int log;
return log = Integer.parseInt(value);
}
public int baseCtF(int value) {
int conversion = (int) (temp() * 1.8 + 32);
return conversion;
}
public int baseFtC(int value) {
int conversion = (int) ((temp() - 32) / 1.8);
return conversion;
}
}
Ok, there is an other way, easier, thanks anyway ;]
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ex74v4 {
public static void main(String[] a) {
DecimalFormat digit = new DecimalFormat("0.00");
String value = JOptionPane.showInputDialog(null, "Enter value ");
float log;
log = Float.parseFloat(value);
JFrame frame = new JFrame();
Object stringArray[] = { "Celsius to Fahrenheit", "Fahrenheit to Celsius" };
int reply = JOptionPane.showOptionDialog(frame, "Choose conversion type of value: " + digit.format(log), "MiniConverter",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray,
stringArray[0]);
if (reply == JOptionPane.YES_OPTION) {
DecimalFormat digit2 = new DecimalFormat("0.00");
double conversion = log * 1.8 + 32;
JOptionPane.showMessageDialog(frame, log + " " + "(°C) equals " + digit2.format(conversion) + " (°F)", "MiniConverter", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else {
DecimalFormat digit3 = new DecimalFormat("0.00");
double conversion = (log - 32) / 1.8;
JOptionPane.showMessageDialog(frame, log + " " + "(°F) equals " + digit3.format(conversion) + " (°C)", "MiniConverter", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
Related
recently I started learning Java, I watched a YT video where a programmer used static methods and variables to create a simple guess game using JFrame.
Afterwards I tried to implement a close/restart button, after reading some Threads I relized static methods aren´t made that for. So my question is now how do I solve my problem now. :)
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ThreadLocalRandom;
public class main extends JFrame {
JLabel text = new JLabel("Please choose a number between 1 & 10 ");
JLabel textVersuch = new JLabel();
JButton button = new JButton("Try");
int myNumber = ThreadLocalRandom.current().nextInt(1,10+1);
JTextField textField = new JTextField();
int count = 0;
//is there a better way to hide all this information, but still keep them useable for my methods?
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.openUI(); //error occurs
}
//How do I manage to start my method openUI() to start my game?
public void openUI(){
JFrame frame = new JFrame("Program");
frame.setSize(400,400);
frame.setLocation(800,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultLookAndFeelDecorated(true);
text.setBounds(0,50,400,25);
textVersuch.setBounds(300,0,100,25);
textField.setBounds(0,150,50,25);
button.setBounds(50,150,100,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String textFromTextfield = textField.getText();
int number = Integer.parseInt(textFromTextfield);
if(number<1 || number>10){
text.setText("Your number has to be between 1 & 10 ");
textField.setText("");
}else{
guess(number);
}
}catch (Exception error){
text.setText("Please enter a digit! ");
textField.setText("");
}
}});
frame.add(button);
frame.add(textField);
frame.add(text);
frame.add(textVersuch);
frame.setLayout(null);
frame.setVisible(true);
}
public void close(JFrame frame){
frame.dispose(); //here I want to close the game
}
public void guess(int number ) throws InterruptedException {
count++;
textVersuch.setText(count + " tries!");
if(number == myNumber){
text.setText("You was right! " + " You tried " + count + " time(s) :)" );
button.setText("Restart");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//How can I restart my JFrame?
}
});
} else if (count < 3) {
text.setText("Wrong guess! Retry");
if (number < myNumber){
text.setText("Your searched number is bigger than" + number );
}else {
text.setText("Your searched number is lower than" + number );
}
} else {
text.setText("Sorry, you lost the number was " + myNumber);
}
textField.setText("");
}
}
hi here is my code i want to call the insert(latitude,longitude) inside the get() but it is not working for me so please help!
public void onStart(Intent intent, int startid){
Toast.makeText(getApplicationContext(),"Service Strated...",Toast.LENGTH_SHORT).show();
device_id = intent.getExtras().getString("device_id");
final int delay = 60000; //milliseconds
h.postDelayed(new Runnable() {
public void run() {
try {
get();
} catch (JSONException e) {
e.printStackTrace();
}
h.postDelayed(this, delay);
}
}, delay);
}
public void get() throws JSONException {
count++;
gps=new GPSTracker(getApplicationContext());
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if (latitude != 0.0 & longitude != 0.0) {
insert(latitude,longitude);
Toast.makeText(getApplicationContext(), "Your Location : \n Lat :" + latitude + "\nLang :" + longitude, Toast.LENGTH_LONG).show();
if(count==5){
send();
count=0;
}
}
}
}
public void insert(double lat,double lon){
System.out.print("hi_entered");
boolean exist = checkIfExist(lat, lon);
System.out.print(exist);
if(!exist) {
System.out.print("INSERT INTO location VALUES(null,'" + lat + "','" + lon + "',null);");
db.execSQL("INSERT INTO location VALUES(null,'" + lat + "','" + lon + "',null);");
}
}
I have two applications, sending messages asynchronously in both directions. I am using sockets of type ZMQ.DEALER on both sides. The connection status is additionally controlled by heartbeating.
I have now problems to get the connection reliably recovering after connection problems (line failure or application restart on one side). When I restart the applicaton on the server side (the side doing the bind()), the client side will not always reconnect successfully and then needs to be restarted, especially when the local buffer has reached the HWM limit.
I did not find any other way to make the connection recovery reliable, other than resetting the complete ZMQ.Context in case of heartbeat failures or if send() returned false. I will then call Context.term() and will create Context and Socket again. This seemed to work fine in my tests. But now I observed occasional and hangups inside Context.term(), which are rare and hard to reproduce. I know, that creating the Context should be done just once at application startup, but as said I found no other way to re-establish a broken connection.
I am using JeroMQ 0.3.4. The source of a test application is below, ~200 lines of code.
Any hints to solve this are very much appreciated.
import java.util.Calendar;
import org.zeromq.ZMQ;
public class JeroMQTest {
public interface IMsgListener {
public void newMsg(byte[] message);
}
final static int delay = 100;
final static boolean doResetContext = true;
static JeroMQTest jeroMQTest;
static boolean isServer;
private ZMQ.Context zContext;
private ZMQ.Socket zSocket;
private String address = "tcp://localhost:9889";
private long lastHeartbeatReceived = 0;
private long lastHeartbeatReplyReceived;
private boolean sendStat = true, serverIsActive = false, receiverInterrupted = false;
private Thread receiverThread;
private IMsgListener msgListener;
public static void main(String[] args) {
isServer = args.length > 0 && args[0].equals("true");
if (isServer) {
new JeroMQTest().runServer();
}
else {
new JeroMQTest().runClient();
}
}
public void runServer() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT")) {
String msgSent = "HEARTBEAT_REP " + msgReceived.substring(10);
sendStat = zSocket.send(msgSent.getBytes());
System.out.println("heartbeat rcvd, reply sent, status:" + sendStat);
lastHeartbeatReceived = getNow();
} else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
while (true) {
boolean heartbeatsOk = lastHeartbeatReceived > getNow() - delay * 4;
if (heartbeatsOk) {
serverIsActive = true;
String msg = "SERVER " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
ct++;
}
if (serverIsActive && (!heartbeatsOk || !sendStat)) {
serverIsActive = false;
if (doResetContext) {
resetContext();
}
}
sleep(delay);
}
}
public void runClient() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT_REP")) {
System.out.println("HEARTBEAT_REP received:" + msgReceived);
lastHeartbeatReplyReceived = getNow();
}
else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
boolean reconnectDone = false;
while (true) {
boolean heartbeatsOK = lastHeartbeatReplyReceived > getNow() - delay * 4;
String msg = "HEARTBEAT " + (ct++);
sendStat = zSocket.send(msg.getBytes());
System.out.println("heartbeat sent:" + msg + ", status:" + sendStat);
sleep(delay / 2);
if (sendStat) {
msg = "MSG " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
reconnectDone = false;
}
if ((!heartbeatsOK && lastHeartbeatReplyReceived > 0) || (!sendStat && !reconnectDone)) {
if (doResetContext) {
resetContext();
}
lastHeartbeatReplyReceived = 0;
reconnectDone = true;
}
sleep(delay / 2);
}
}
public void resetContext() {
closeJmq();
sleep(1000);
createJmq();
System.out.println("resetContext done");
}
private void createJmq() {
zContext = ZMQ.context(1);
zSocket = zContext.socket(ZMQ.DEALER);
zSocket.setSendTimeOut(100);
zSocket.setReceiveTimeOut(100);
zSocket.setSndHWM(10);
zSocket.setRcvHWM(10);
zSocket.setLinger(100);
if (isServer) {
zSocket.bind(address);
} else {
zSocket.connect(address);
}
receiverThread = new Thread() {
public void run() {
receiverInterrupted = false;
try {
ZMQ.Poller poller = new ZMQ.Poller(1);
poller.register(zSocket, ZMQ.Poller.POLLIN);
while (!receiverInterrupted) {
if (poller.poll(100) > 0) {
byte byteArr[] = zSocket.recv(0);
msgListener.newMsg(byteArr);
}
}
poller.unregister(zSocket);
} catch (Throwable e) {
System.out.println("Exception in ReceiverThread.run:" + e.getMessage());
}
}
};
receiverThread.start();
}
public void closeJmq() {
receiverInterrupted = true;
sleep(100);
zSocket.close();
zContext.term();
}
long getNow() {
Calendar now = Calendar.getInstance();
return (long) (now.getTime().getTime());
}
private static void sleep(int mSleep) {
try {
Thread.sleep(mSleep);
} catch (InterruptedException e) {
}
}
}
I have a script that currently displays dialogue text letter by letter. Currently it rolls through each string of text in my _stanzas array without pausing. I would like to change this script so that it requires the user to press "Z" on their keyboard before the script begins to print the next block of text from _stanzas. I cant seem to figure it out...here is my code.
using UnityEngine;
using System.Collections;
public class Text : MonoBehaviour {
public float LetterPause = 0.1f;
public GameObject text;
public GameObject box;
public GameObject name;
private bool _textFinished;
private int _textIndex;
private string[] _stanzas;
int tracker;
public void Start()
{
if (Application.loadedLevel == 1) {
_stanzas = new [] {
" It’s Terrence’s hat... ",
"He always was one to lose track of the" + "\n" + "material objects in life," + "\n" + "but to hold onto the immaterial forever.",
"I’ll carry it for him" + "\n" + "until I find him. "
};
}
_textFinished = true;
_textIndex = -1;
tracker = _textIndex;
}
public void Update()
{
if (_textFinished)
{
if (_textIndex++ >= (_stanzas.Length - 1))
{
_textFinished = false;
text.SetActive(false);
box.SetActive(false);
name.SetActive(false);
}
if (_textFinished){
SetText(_stanzas[_textIndex]);}
}
}
private IEnumerator TypeText(float waitTime, string text)
{
_textFinished = false;
guiText.text = "";
foreach (var letter in text)
{
guiText.text += letter;
yield return new WaitForSeconds (waitTime);
}
_textFinished = true;
}
private void SetText(string text)
{
StartCoroutine(TypeText(LetterPause, text));
}
}
change
if (_textFinished)
to
if (_textFinished && (Input.GetKeyDown(KeyCode.Z) || _textIndex < 0))
I'm trying to figure out how to invoke a Boolean method as true or false. Here is what I have thus far:
import java.util.Scanner;
import java.text.DecimalFormat;
public class AssignmentThree {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the length of Edge 1: ");
double edge1 = scan.nextDouble();
System.out.print("Enter the length of Edge 2: ");
double edge2 = scan.nextDouble();
System.out.print("Enter the length of Edge 3: ");
double edge3 = scan.nextDouble();
scan.close();
DecimalFormat Dec = new DecimalFormat("###,###,##0.00");
if(isValid (edge1, edge2, edge3) == true) {
System.out.println("The area of the triangle is " + Dec.format(area(edge1, edge2, edge3)));
}
if(isValid (edge1, edge2, edge3) == false) {
System.out.println("This is not a valid traingle");
}
}
public static boolean isValid(double side1, double side2, double side3) {
//testing to see if the triangle is real
if(side1+side2>side3 || side1+side3>side2 || side2+side3>side1) {
return true;
} else {
return false;
}
}
I'm not sure if the problem is in my method or not but when the program is ran it simply prints the area, and never if its valid or not.