Can't get System.exit() to work in dragon12 project - java

I have everything working but the System.exit(0). It should exit any time remaining if the button is pressed. I'm not sure what to do. Help would be greatly appreciated.
/*
Creates the perfect hard-boiled(simulates 12 minutes in boiling water) or soft-boiled
egg(simulates 6 minutes in boiling water). Both options require 10 seconds of rinsing
under cold water after necessary time for boiling. Allow user to exit any remaining
time.
*/
import java.io.*;
import java.util.*;
public class AdvancedEggMaker {
public static void main(String[] args) {
MCU mcu = null;
try {
mcu = new MCU(new Communicator(args[0]));
}
catch (IOException e) {
System.out.println(e);
}
mcu.println("SW2 - HB Egg", 0);
mcu.println("SW3 - SB Egg", 1);
while (true) {
int sw = mcu.getSwitch();
if (sw == 2) {
mcu.println("Hard Boiled Egg", 0);
mcu.println("Place Egg in", 0);
mcu.println("boiling water", 1);
mcu.println("then press SW4", 0);
mcu.println("SW5 - Quit", 1);
int sw2 = mcu.getSwitch();
switch (sw2) {
case 4:
int t = 720;
while (t > 0 && sw2 == 4) {
t = (t - 1);
mcu.println("Boiling...", 0);
mcu.println((t / 60) + "mins left...", 1);
}
break;
case 5:
System.exit(0);
break;
}
}
if (sw == 3) {
mcu.println("Soft Boiled Egg", 0);
mcu.println("Place Egg in", 0);
mcu.println("boiling water", 1);
mcu.println("then press SW4", 0);
mcu.println("SW5 - Quit", 1);
int sw2 = mcu.getSwitch();
switch (sw2) {
case 4:
int t = 360;
while (t > 0 && sw2 == 4) {
t = (t - 1);
mcu.println("Boiling...", 0);
mcu.println((t / 60) + "mins left...", 1);
}
break;
case 5:
System.exit(0);
break;
}
}
mcu.println("Rinse Egg", 0);
mcu.println("then press SW4", 0);
mcu.println("SW5 - Quit", 1);
int sw3 = mcu.getSwitch();
if (sw3 == 4) {
double t = 10;
while (t > 0.0) {
t = (t - 1);
mcu.println("Rinsing...", 0);
mcu.println(t + "Secs left...", 1);
}
if (sw == 5) {
System.exit(0);
}
}
}
}
}

Are you sure about that the execution is reaching one of your System.exit(0) statements. I don't see any sysout or logs to help you to be sure about that. First examine that because I don't see there any reason why it should not work.
Secondly you can check whether you have some background thread working in your code. It may be the case that you may have some connections/streams open somewhere in a thread and it is not letting the System.exit(0) to terminate the process.

Related

MineCraft Forge How to stop mobs from being invulnerable after hit (Java) 1.10.2

I have made a custom bow that fires really quickly, and I have learned that all mobs are invulnerable for a short period of time after they get hit. This renders my bow pretty much useless. I was wondering if there is any way to change the duration that the mobs are invulnerable for, or even remove it at all.
Code for bow firing method:
#Override
public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World worldIn, EntityPlayer playerIn, EnumHand hand) {
// int charge = 1;
// charge = ForgeEventFactory.onArrowLoose(stack, worldIn, playerIn, charge, true);
player123 = playerIn;
if (!worldIn.isRemote) {
final ItemArrow itemArrow = (ItemArrow) (Items.ARROW instanceof ItemArrow ? Items.ARROW : Items.ARROW);
final ItemStack ammo = new ItemStack(Items.ARROW, 1);
final float arrowVelocity = 1;
final EntityArrow entityArrow = itemArrow.createArrow(worldIn, ammo, playerIn);
entityArrow.setAim(playerIn, playerIn.rotationPitch, playerIn.rotationYawHead, 0.0F, arrowVelocity * 3.5F, 0F);
entityArrow.setDamage(2);
entityArrow.pickupStatus = EntityArrow.PickupStatus.DISALLOWED;
// entityArrow.setVelocity(0.2F, 0.1F, 0.2F);
final ItemStack magicarrow = new ItemStack(TheGalaxyMod.magicarrow, 1);
EntityLivingBase living = (playerIn);
if (FastMode.fastmode == 1){
int index = GetItemSlot(playerIn, magicarrow);
if (playerIn.inventory.hasItemStack(new ItemStack(TheGalaxyMod.creativequiver)))
{
entityArrow.setDamage(5000);
worldIn.spawnEntityInWorld(entityArrow);
}
else if (playerIn.inventory.hasItemStack(new ItemStack(TheGalaxyMod.magicquiver)))
{
worldIn.spawnEntityInWorld(entityArrow);
}
else if (!(playerIn.inventory.getStackInSlot(index).getItem() == null) && playerIn.inventory.getStackInSlot(index).getItem() == TheGalaxyMod.magicarrow)
{
damageItem(playerIn, magicarrow, 1);
worldIn.spawnEntityInWorld(entityArrow);
ItemStack stack2 = playerIn.inventory.getStackInSlot(index);
if(stack2.getItemDamage() > 500)
{
playerIn.inventory.setInventorySlotContents(index, null);
}
}
else if(playerIn.inventory.hasItemStack(ammo) ){
worldIn.spawnEntityInWorld(entityArrow);
removeItem(playerIn, ammo);
}
}
else if
(FastMode.fastmode == 2)
{
final ItemArrow itemArrow2 = (ItemArrow) (Items.ARROW instanceof ItemArrow ? Items.ARROW : Items.ARROW);
final ItemStack ammo2 = new ItemStack(Items.ARROW);
final float arrowVelocity2 = 1;
final EntityArrow entityArrow2 = itemArrow2.createArrow(worldIn, ammo2, playerIn);
entityArrow2.setAim(playerIn, playerIn.rotationPitch, playerIn.rotationYawHead, 0.0F, arrowVelocity2 * 3.5F, 0F);
entityArrow2.setDamage(2);
entityArrow2.pickupStatus = EntityArrow.PickupStatus.DISALLOWED;
int index = GetItemSlot(playerIn, magicarrow);
if (playerIn.inventory.hasItemStack(new ItemStack(TheGalaxyMod.creativequiver)))
{
entityArrow.setDamage(5000);
worldIn.spawnEntityInWorld(entityArrow);
entityArrow2.setDamage(5000);
worldIn.spawnEntityInWorld(entityArrow2);
}
else if (playerIn.inventory.hasItemStack(new ItemStack(TheGalaxyMod.magicquiver)))
{
worldIn.spawnEntityInWorld(entityArrow);
worldIn.spawnEntityInWorld(entityArrow2);
}
else if (!(playerIn.inventory.getStackInSlot(index).getItem() == null) && playerIn.inventory.getStackInSlot(index).getItem() == TheGalaxyMod.magicarrow)
{
damageItem(playerIn, magicarrow, 2);
worldIn.spawnEntityInWorld(entityArrow);
worldIn.spawnEntityInWorld(entityArrow2);
ItemStack stack2 = playerIn.inventory.getStackInSlot(index);
if(stack2.getItemDamage() > 500)
{
playerIn.inventory.setInventorySlotContents(index, null);
}
}
else if(playerIn.inventory.hasItemStack(ammo) ){
worldIn.spawnEntityInWorld(entityArrow);
worldIn.spawnEntityInWorld(entityArrow2);
removeItem(playerIn, ammo);
}
}
else if
(FastMode.fastmode == 3)
{
entityArrow.setFire(50);
int index = GetItemSlot(playerIn, magicarrow);
if (playerIn.inventory.hasItemStack(new ItemStack(TheGalaxyMod.creativequiver)))
{
entityArrow.setDamage(5000);
worldIn.spawnEntityInWorld(entityArrow);
}
else if (playerIn.inventory.hasItemStack(new ItemStack(TheGalaxyMod.magicquiver)))
{
worldIn.spawnEntityInWorld(entityArrow);
}
else if (!(playerIn.inventory.getStackInSlot(index).getItem() == null) && playerIn.inventory.getStackInSlot(index).getItem() == TheGalaxyMod.magicarrow)
{
damageItem(playerIn, magicarrow, 2);
worldIn.spawnEntityInWorld(entityArrow);
ItemStack stack2 = playerIn.inventory.getStackInSlot(index);
if(stack2.getItemDamage() > 500)
{
playerIn.inventory.setInventorySlotContents(index, null);
}
}
else if(playerIn.inventory.hasItemStack(ammo) ){
worldIn.spawnEntityInWorld(entityArrow);
removeItem(playerIn, ammo);
}
}
}
return super.onItemRightClick(stack, worldIn, playerIn, hand);
}
EDIT:
Solution Found:
Thanks to #Draco18s I have figured out the solution.
All I had to do was add the line
entityArrow.hurtResistantTime = 0
You need this:
entityHit.hurtResistantTime = 0;
Note: exact field name may change depending on Minecraft version and the build number of Forge.
Call it either just before you hurt the entity (bypassing the hurt resistance timers inflicted by all other sources of damage) or after (your damage is ignored if there's a timer, but if it inflicts damage, the next source is not ignored due to the timer). This line needs to be in the arrow class. If you don't have a custom arrow class, now's a good time to make one.
There's no (good) way to conditionally set the timer to 0 based on what the prior damage type was, unfortunately. If you are on 1.10 or newer, you could use capabilities, although possibly unwieldy.

How to optimize a lot of switch cases?

How could I optimize having a lot of switch cases? Is there some other method to do what I'm attempting to do?
I have a time slider and this slider updates a variable currentTime with the value (1-24) where the current slider is and calls the updateTime() method. In this method I have switch cases for 1 - 24 (only 3 in this example). Instead of making 24 switch cases, could I do this in a much simpler way?
private void updateTime() {
switch (currentTime) {
case 1:
hourlyData = weatherAPI.HourlyReport(1);
setHourlyData();
break;
case 2:
hourlyData = weatherAPI.HourlyReport(2);
setHourlyData();
break;
...
case 24:
hourlyData = weatherAPI.HourlyReport(24);
setHourlyData();
break;
default:
System.out.println("Oops");
break;
}
}
--
public Map HourlyReport(int hour) {
Hourly hourly = new Hourly(fio);
//In case there is no hourly data available
if (hourly.hours() < 0) {
System.out.println("No hourly data.");
} else {
hourlyData.put("Temp", hourly.getHour(hour).temperature()); // Temperature
hourlyData.put("TempFeel", hourly.getHour(hour).apparentTemperature()); // Feel Temperature
hourlyData.put("Humidity", hourly.getHour(hour).humidity()); // Humidity
hourlyData.put("WindSpeed", hourly.getHour(hour).windSpeed()); // Wind Speed
hourlyData.put("Precip", hourly.getHour(hour).precipProbability()); // Precipitation
hourlyData.put("TimeStamp", hourly.getHour(hour).time());// TimeStamp
}
return hourlyData;
}
The use of a switch is not justified in this case. Use a simple if
if (currentTime > 0 && currentTime < 25) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else {
System.out.println("Oops");
}
I would validate first
private void updateTime() {
if (currentTime < 1 || currentTime > 24)
throw new IllegalStateException("currentTime: " + currentTime);
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
}
You could use a simple if statement to validate currentTime's value and just pass it to weatherAPI.HourlyReport:
private void updateTime() {
if (currentTime >= 1 || currentTime <= 24) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else{
System.out.println("Oops");
}
}
private boolean isValidHour(){
if (currentTime >= 1 && currentTime <= 24)
return true;
else
return false;
}
private void updateTime() {
if(this.isValidHour())
hourlyData = weatherAPI.HourlyReport(currentTime);
else
System.out.println("Oops");
}

Running loop to check integer, not working

I'm trying to get the location of the user's finger touch and detect if it is within the bounds of an image view. I'm getting all the right integers returned to me, there is no problem with the values. The problem I'm getting is when trying to detect whether returnX is greater or less than the imageview X int.
ImageView img;
float eventX;
float eventY;
float x,y,x2,y2;
String TAG = "imgPos";
String TAG2 = "downcheck";
String TAG3 = "bounds";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.imageView1);
}
public void fingerDownLoop(){
if (SingleTouchEventView.userDown == true){
Log.e(TAG2, "Down is true");
Thread myThread = new Thread(myRunnable);
myThread.start();
} else if (SingleTouchEventView.userDown == false){
Log.e(TAG2, "Down is false");
}
}
public void getFingerLocation(){
float returnX = SingleTouchEventView.eventX;
float returnY = SingleTouchEventView.eventY;
Log.e(TAG3, " - X -");
Log.e(TAG3, " getX: " + returnX);
Log.e(TAG3, " - Y -");
Log.e(TAG3, " getY: " + returnY);
if (returnX < x){
Log.e(TAG3, "Outside bounds");
}
if (returnX > x){
Log.e(TAG3, "Inside bounds");
}
}
Runnable myRunnable = new Runnable() {
#Override
public void run() {
while (SingleTouchEventView.userDown == true) {
try {
Log.e(TAG2, "FingerDown");
getFingerLocation();
x = img.getLeft();
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Waits for 1 second (1000 milliseconds)
}
}
};
}
testText is a button click, it gets the imageviews position and stores it as the values. The problem I'm getting is here:
if (returnX < x){
Log.e(TAG3, "Outside bounds");
}
if (returnX > x){
Log.e(TAG3, "Inside bounds");
}
It is all ways showing as Inside bounds even though returnX is less than X. Any ideas?
Updated get img position.
int[] img_coordinates = new int[2];
img.getLocationOnScreen(img_coordinates);
double x_center = (double)img_coordinates[0] + img.getWidth()/2.0;
double y_center = (double)img_coordinates[1] + img.getHeight()/2.0;
int halfwidth = 150 / 2;
int halfheight = 150 / 2;
yboundtop = y_center - halfheight;
yboundbottom = y_center + halfheight;
xboundleft = x_center - halfwidth;
xboundright = x_center + halfwidth;
float returnX = eventX;
float returnY = eventY;
if (returnX < xboundleft || returnX > xboundright || returnY < yboundtop || returnY > yboundbottom) {
Log.e(TAG3, "Outside bounds");
}
if (returnX > xboundleft && returnX < xboundright && returnY > yboundtop && returnY < yboundbottom) {
Log.e(TAG3, "Inside bounds");
}
I'am not sure what you want to accomplish by your code, but checking in a loop is not very efficient and in this case probably not necessary.
Your imageView has a method getHitRect() and you could use it like this:
Rect hitRect = new Rect();
imageView.getHitRect(hitRect);
if(hitRect.contains(touchEvent.getX(), touchEvent.getY())){
// your touch is inside, do something useful
}
Use it inside your touch-method
Now that I kind of know what you are looking for I think I may be able to help. Override the onTouchEvent() method of your Activity to capture your touch events. This will be much more efficient than doing the loop yourself.
private boolean mTouchInImage = false;
public boolean onTouchEvent(MotionEvent event) {
boolean handledTouch = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Rect hitRect = new Rect((int)img.getX(), (int)img.getY(),
(int)(mg.getX() + img.getWidth()), (int)(img.getY() + img.getHeight()));
handledTouch = mTouchInImage = hitRect.contains((int)event.getX(), (int)event.getY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handledTouch = mTouchInImage;
mTouchInImage = false;
break;
case MotionEvent.ACTION_MOVE:
if (mTouchInImage) {
img.setX(event.getX() - img.getWidth() / 2);
img.setY(event.getY() - img.getHeight() / 2);
img.invalidate();
handledTouch = true;
}
break;
}
return handledTouch;
}

Countdown timer with GUI using SwingWorker - not updating properly

i'm trying to make a countdown timer using swingworker, problem is when seconds get to zero, programs sets them back to 60 and deducts one.I did make the program without GUI and it works just perfect, but using swingworker my timer looks like this
1: 0: 2
1: 0: 1
0: 59: 60
which is kinda wrong and should be
1: 0: 1
1: 0: 0
0: 59: 59
Both of my class lie on the same logic.I guess it has something to do with sending the whole Time object to the 'process' but i just can't explain it to myself.
doInBackground() method :
protected Void doInBackground() throws Exception {
Integer hours = Integer.parseInt(hoursField.getText());
Integer minutes = Integer.parseInt(minutesField.getText());
Integer seconds = Integer.parseInt(secondsField.getText());
Time time = new Time(hours, minutes, seconds);
if(minutes < 59 & seconds < 59) {
if(hours >=0 & minutes >=0 & seconds >=0) {
boolean count = true;
while(count) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
Logger.getLogger(Chronometer.class.getName()).log(Level.SEVERE, null, e);
}
time.setSeconds(time.getSeconds() - 1);
publish(time);
if(time.getHours() == 0 & time.getMinutes() == 0 & time.getSeconds() == 0) {
count = false;
}
if(time.getSeconds() == 0) {
time.setSeconds(60);
if(time.getMinutes() != 0) {
time.setMinutes((time.getMinutes() - 1));
}else if(time.getMinutes() == 0) {
time.setHours((time.getHours() - 1));
if(time.getHours() >= 0) {
time.setMinutes(59);
}
if(time.getHours() < 0) {
time.setHours(0);
}
}
}
}
}else {
System.exit(0);
}
}
return null;
}
And this is the simple java class that works on the same logic :
boolean count = true;
while(count) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
}
seconds--;
System.out.println(hours + ": " + minutes + ": " + seconds);
if(hours == 0 & minutes == 0 & seconds == 0) {
count = false;
}
if(seconds == 0) {
seconds = 60;
if(minutes != 0){
minutes--;
}else if(minutes == 0) {
hours--;
if(hours >=0){
minutes = 59;
}
if(hours < 0) {
hours = 0;
}
}
}
}
If anyone could point me my mistake, i'd be very grateful.
Thanks
Adding process method
public void process(List<Time> time) {
for(Time t : time) {
showField.setText(String.valueOf(t.getHours()) + ": " + String.valueOf(t.getMinutes())+ ": " + String.valueOf(t.getSeconds()));
}
}
your line
if(time.getSeconds() == 0) time.setSeconds(60);
needs to be
if(time.getSeconds() == 0) time.setSeconds(59);
And invert this tow lines:
time.setSeconds(time.getSeconds() - 1);
publish(time);
like this:
publish(time);
time.setSeconds(time.getSeconds() - 1);
The deduction is correct but it's not showing the result because when seconds reaches cero the conditional it's executed, not showing the intermediate time.
Change this line:
if(time.getSeconds() == 0)
for this one:
if(time.getSeconds() < 0)
And this:
if(time.getHours() == 0 & time.getMinutes() == 0 & time.getSeconds() == 0)
if(time.getHours() == 0 & time.getMinutes() == 0 & time.getSeconds() < 0)
I did not dig at your logic, but you can achieve the same using Calendar which looks more simple.
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hours);
c.set(Calendar.MINUTE, minutes);
c.set(Calendar.SECOND, seconds);
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date d = c.getTime();
System.out.println(format.format(d));
while(count) {
c.set(Calendar.SECOND, c.get(Calendar.SECOND)-1); //decrement 1 second at a time
d = c.getTime();
System.out.println(format.format(d));
Thread.sleep(1000); //Pause for a second between each print
}
I have used SimpleDateFormat("HH:mm:ss") for simplicity. If you need different fields of time, then you can use Calendar.get(..) method to get the same

how to write generics extensions for standart objects in java?

I beginner in Java and I ask tell me some words about Java tradition of writing generic code. I wrote helper class for pushing items into generic sorted collections in code below and I want to know it is accepted? Or I should extends some base class of collections? Or other ways to welcome more in Java?
package com.rkovalev.Helper;
import java.util.Comparator;
import java.util.List;
public abstract class ListExtensions {
public static <T> void addOnCompare(List<T> collection, T item, Comparator<T> comparator) {
synchronized(collection) {
int i = 0;
int size = collection.size();
if (size == 1) {
int diff = comparator.compare(item, collection.get(0));
switch(diff) {
case 1: i++; break;
default: break;
}
} else {
int range = size - 1;
i = size / 2;
int left = 0;
int right = range;
while(true) {
if (i <= 0) { i = 0; break; }
if (i > range) { i = range; break; }
int diff = comparator.compare(item, collection.get(i));
if (diff == 0) break;
else {
if (diff == -1) right = i;
if (diff == 1) left = i;
int near = i + diff;
if (near < 0) { i = 0; break; }
if (near > range) { i = range + 1; break; }
int diff_near = comparator.compare(item, collection.get(near));
if (diff_near == 0) { i = diff_near; break; }
if (diff_near == diff) {
int step = (right-left)/2;
if (step == 0) step = 1;
switch(diff){
case -1:
right = i;
i = i - step; break;
case 1:
left = i;
i = i + step; break;
}
} else if (diff > diff_near) {
i = near; break;
} else { break; }
}
}
}
collection.add(i, item);
}
}
}
If you want to make extra "generic" functionality available for all collection classes, then writing the functionality as a static method in a "helper" class is the right way to go.
Adding the method to a base class of the existing collection classes would not work. It would entail modifying the standard Java class library, and nobody in their right mind would do that. (It is technically possible, but you would be creating a portability nightmare for your code. Not to mention legal issues if you used the trademarked term "Java" in connection with your code.)

Categories

Resources