Why I'm getting crash when I'm trying to set float numbers? - crash

I wrote a small calculator program, and when I try to set float numbers it gives me the following crash log:
**Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:9)
Process finished with exit code 1**
My code is :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the calculator program: " );
System.out.println( "\n Please enter 2 numbers :");
Scanner scanner = new Scanner(System.in);
float number1 = scanner.nextInt();
float number2 = scanner.nextInt();
float sumOfNumbers = number1 + number2;
float subtractionOfNumbers = number1 - number2;
float multiplicationOfNumbers = number1 * number2;
float divisionOfNumbers = number1 / number2;
System.out.println("Please choose what operation do you want - (+)/(-)/(*)/(/): ");
System.out.println(" 1 = + / 2 = - / 3 = * / 4 = /");
int operation = scanner.nextInt();
switch (operation) {
case 1:
System.out.println("The sum of " +number1+ " and " +number2 + " is " +sumOfNumbers);
break;
case 2:
System.out.println("The subtraction of " +number1+ " and " +number2 + " is " +subtractionOfNumbers);
break;
case 3:
System.out.println("The multiplication of " +number1+ " and " +number2 + " is " +multiplicationOfNumbers);
break;
case 4:
System.out.println("The division of " +number1+ " and " +number2 + " is " +divisionOfNumbers);
break;
}
}
}
Why I'm getting crash when I'm trying to set float numbers?

scanner.nextInt() returns an integer, not a float. Either type cast it to a float, or use scanner.nextFloat() instead

Related

Obtaining attendance logs from ZKTEco device using their SDK with C#

I'm attempting to integrate a ZKTEco U650-C with my company's systems to automatically fetch attendance logs but I'm having trouble connecting to the device using C#.
I managed to download the SDK from their website which includes the ZKHID, ZKCamera DLL files, and the SDK wrapper so I could import and use the functions from them.
In Visual Studio, I couldn't reference the ZKHID and ZKCamera DLL files because they are unmanaged. Although, I was able to reference the ZKBioModuleSDKWrapper because it uses PInvoke.
Some operations such as connecting to the device using the TcpClient class, initializing, and terminating the device were successful. However, using other operations such as opening the device and getting the device configuration couldn't be made because I don't know how to get the device handle.
Am I using the wrong set of SDK or is it something else? Any help would be appreciated.
It turns out I was using the wrong set of SDK. ZKTEco took down the SDK download link from their official website so I had to downloaded the correct SDK from a private server.
I added the zkemkeeper.dll reference as normal in Visual Studio, made some changes to the code, and I managed to receive the attendance logs.
using zkemkeeper;
namespace ZKTEco_Biometric_Device_Integration
{
internal class Program
{
public Program()
{
}
public enum CONSTANTS
{
PORT = 4370,
}
static void Main(string[] args)
{
Console.WriteLine("Connecting...");
CZKEM objCZKEM = new CZKEM();
if (objCZKEM.Connect_Net("192.168.1.11", (int)CONSTANTS.PORT))
{
objCZKEM.SetDeviceTime2(objCZKEM.MachineNumber, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
Console.WriteLine("Connection Successful!");
Console.WriteLine("Obtaining attendance data...");
}
else
{
Console.WriteLine("Connection Failed!");
}
if (objCZKEM.ReadGeneralLogData(objCZKEM.MachineNumber))
{
//ArrayList logs = new ArrayList();
string log;
string dwEnrollNumber;
int dwVerifyMode;
int dwInOutMode;
int dwYear;
int dwMonth;
int dwDay;
int dwHour;
int dwMinute;
int dwSecond;
int dwWorkCode = 1;
int AWorkCode;
objCZKEM.GetWorkCode(dwWorkCode, out AWorkCode);
//objCZKEM.SaveTheDataToFile(objCZKEM.MachineNumber, "attendance.txt", 1);
while (true)
{
if (!objCZKEM.SSR_GetGeneralLogData(
objCZKEM.MachineNumber,
out dwEnrollNumber,
out dwVerifyMode,
out dwInOutMode,
out dwYear,
out dwMonth,
out dwDay,
out dwHour,
out dwMinute,
out dwSecond,
ref AWorkCode
))
{
break;
}
log = "User ID:" + dwEnrollNumber + " " + verificationMode(dwVerifyMode) + " " + InorOut(dwInOutMode) + " " + dwDay + "/" + dwMonth + "/" + dwYear + " " + time(dwHour) + ":" + time(dwMinute) + ":" + time(dwSecond);
Console.WriteLine(log);
//logs.Add(log);
}
}
//Console.ReadLine();
}
static void getAttendanceLogs(CZKEM objCZKEM)
{
string log;
string dwEnrollNumber;
int dwVerifyMode;
int dwInOutMode;
int dwYear;
int dwMonth;
int dwDay;
int dwHour;
int dwMinute;
int dwSecond;
int dwWorkCode = 1;
int AWorkCode;
objCZKEM.GetWorkCode(dwWorkCode, out AWorkCode);
//objCZKEM.SaveTheDataToFile(objCZKEM.MachineNumber, "attendance.txt", 1);
while (true)
{
if (!objCZKEM.SSR_GetGeneralLogData(
objCZKEM.MachineNumber,
out dwEnrollNumber,
out dwVerifyMode,
out dwInOutMode,
out dwYear,
out dwMonth,
out dwDay,
out dwHour,
out dwMinute,
out dwSecond,
ref AWorkCode
))
{
break;
}
log = "User ID:" + dwEnrollNumber + " " + verificationMode(dwVerifyMode) + " " + InorOut(dwInOutMode) + " " + dwDay + "/" + dwMonth + "/" + dwYear + " " + time(dwHour) + ":" + time(dwMinute) + ":" + time(dwSecond);
Console.WriteLine(log);
}
}
static string time(int Time)
{
string stringTime = "";
if (Time < 10)
{
stringTime = "0" + Time.ToString();
}
else
{
stringTime = Time.ToString();
}
return stringTime;
}
static string verificationMode(int verifyMode)
{
String mode = "";
switch (verifyMode)
{
case 0:
mode = "Password";
break;
case 1:
mode = "Fingerprint";
break;
case 2:
mode = "Card";
break;
}
return mode;
}
static string InorOut(int InOut)
{
string InOrOut = "";
switch (InOut)
{
case 0:
InOrOut = "IN";
break;
case 1:
InOrOut = "OUT";
break;
case 2:
InOrOut = "BREAK-OUT";
break;
case 3:
InOrOut = "BREAK-IN";
break;
case 4:
InOrOut = "OVERTIME-IN";
break;
case 5:
InOrOut = "OVERTIME-OUT";
break;
}
return InOrOut;
}
}
}

How to Convert Geohash to Geometry in BigQuery?

PostGIS has this function ST_GeomFromGeoHash to get the bounding box geometry of the geohash area (https://postgis.net/docs/ST_GeomFromGeoHash.html), but it has not been ported to BigQuery yet. Is there any workaround?
I've implemented the following BigQuery UDF that converts a geohash of arbitrary precision to a bounding box geometry:
CREATE OR REPLACE FUNCTION dataset.geohash_to_bbox(geohash STRING)
RETURNS STRING
LANGUAGE js AS """
var BASE32_CODES = "0123456789bcdefghjkmnpqrstuvwxyz";
var BASE32_CODES_DICT = {};
for (var i = 0; i < BASE32_CODES.length; i++) {
BASE32_CODES_DICT[BASE32_CODES.charAt(i)] = i;
}
var ENCODE_AUTO = 'auto';
var MIN_LAT = -90;
var MAX_LAT = 90;
var MIN_LON = -180;
var MAX_LON = 180;
var decode_bbox = function (hash_string) {
var isLon = true,
maxLat = MAX_LAT,
minLat = MIN_LAT,
maxLon = MAX_LON,
minLon = MIN_LON,
mid;
var hashValue = 0;
for (var i = 0, l = hash_string.length; i < l; i++) {
var code = hash_string[i].toLowerCase();
hashValue = BASE32_CODES_DICT[code];
for (var bits = 4; bits >= 0; bits--) {
var bit = (hashValue >> bits) & 1;
if (isLon) {
mid = (maxLon + minLon) / 2;
if (bit === 1) {
minLon = mid;
} else {
maxLon = mid;
}
} else {
mid = (maxLat + minLat) / 2;
if (bit === 1) {
minLat = mid;
} else {
maxLat = mid;
}
}
isLon = !isLon;
}
}
return "POLYGON (( " + minLon + " " + minLat + ", " + maxLon + " " + minLat + ", " + maxLon + " " + maxLat + ", " + minLon + " " + maxLat + ", " + minLon + " " + minLat + "))";
};
return decode_bbox(geohash);
""";
Example usage:
select <dataset>.geohash_to_geom("ttnfv2u");
>> POLYGON((77.2119140625 28.6083984375, 77.2119140625 28.65234375, 77.255859375 28.65234375, 77.255859375 28.6083984375, 77.2119140625 28.6083984375))
BigQuery has ST_GEOGPOINTFROMGEOHASH which returns the central point. There is currently no function that returns the box though. The UDF in another answer is often a reasonable workaround, but you should be aware of its usage limitation.
GeoHash normally represents a rectangle on a flat 2D map. BigQuery works with Geography, with geodesic edges, so an edge between two points with same latitude does not follow the parallel, but being geodesic line is a shorter route closer to the pole. So the BigQuery polygon is a bit different from 2D box. You can often ignore the differences, but it might give you wrong results depending on how you use this polygon.

Check the null or empty record condition

I wanted to know if I did this code well, to check if the coding of a record is null or empty, getTraduction (), if I did something wrong, just let me know where I went wrong.
because I would like to have even null records printed
public void getTraduttoreIt_CLASS_HDR_NLS() throws Exception {
List<ClassHdrNls> db2 = getListCLASS_HDR_NLS();
List<DizioPt> sqlServer = getListDizioPt();
BufferedWriter scrivi = new BufferedWriter(
new FileWriter("C:/Users/francesco/Desktop/Table_ClassHdrNls_Sez3.txt"));
for (int i = 0; i < db2.size(); i++) {
for (int j = 0; j < sqlServer.size(); j++) {
if (db2.get(i).getNlsClassName().equals(sqlServer.get(j).getKeyword())) {
System.out.println("-------------------FILE N°3---------------------------");
System.out.println("-------------------ITALIANO---------------------------");
System.out.println("CLASS_NAME: " + db2.get(i).getClassName());
scrivi.newLine();
scrivi.write("CLASS_NAME: ");
scrivi.write(db2.get(i).getClassName());
scrivi.newLine();
System.out.println("NLS_CLASS_NAME: " + db2.get(i).getNlsClassName());
scrivi.write("NLS_CLASS_NAME: ");
scrivi.write(db2.get(i).getNlsClassName());
scrivi.newLine();
System.out.println("NLS_PL_CLASS_NAME: " + db2.get(i).getNlsPlClassName());
scrivi.write("NLS_PL_CLASS_NAME: ");
scrivi.write(db2.get(i).getNlsPlClassName());
scrivi.newLine();
System.out.println("KEYWORD: " + sqlServer.get(j).getKeyword());
scrivi.write("KEYWORD: ");
scrivi.write(sqlServer.get(j).getKeyword());
scrivi.newLine();
System.out.println("LINGUA ITALIANO: " + db2.get(i).getLanguage() + " ***");
scrivi.write("LINGUA ITALIANO: ");
scrivi.write(db2.get(i).getLanguage() + " ***");
scrivi.newLine();
// Faccio un controllo se il valore è diverso da null o il record è vuoto
if (sqlServer.get(j).getTraduzione() == null || sqlServer.get(j).getTraduzione().isEmpty()) {
System.out.println("TRADUZIONE: ***********");
scrivi.write("TRADUZIONE: ");
scrivi.write("*******************");
scrivi.newLine();
} else {
System.out.println("TRADUZIONE: " + sqlServer.get(j).getTraduzione());
scrivi.write("TRADUZIONE: ");
scrivi.write(sqlServer.get(j).getTraduzione());
scrivi.newLine();
}
System.out.println("-------------------------------------------------------");
scrivi.flush();
}
}
}
scrivi.close();
}
Output:
Print only non-null and non-empty records.
I also want to print null records
this line:
if (db2.get(i).getNlsClassName().equals(sqlServer.get(j).getKeyword()))
could be why you are not printing null values, since it forces printing only after there is a match.
You should inspect your data (print all of it) to see what you are getting.
If you are finding null values, then that means printing inside the if condition is what's stopping you from seeing the null values get printed.

Quick help turning sum into mean

I was helped earlier in creating this code that would create a histogram of a randomint. Everything looks good except I accidently had the output as a sum instead of a mean of all the numbers that were randomly chosen.I dont want to mess anything up so I was just going to ask, How can I convert this sum into a mean output instead?
import java.util.Random;
class Assignment4
{
public static void main(String[] args)
{
Random r = new Random();
int sum = 0;
int[] bins = new int[10];
for(int i = 0; i < 100; i++)
{
int randomint = 1 + r.nextInt(10);
sum += randomint;
bins[randomint-1]++;
//System.out.print(randomint + ", ");
}
System.out.println("Sum = " + sum);
System.out.println("Data shown below: ");
for (int i = 0; i < bins.length; i++)
{
int binvalue = bins[i];
System.out.print((i+1) + ": ");
for(int j = 0; j < binvalue; j++)
{
System.out.print('*');
}
System.out.println(" (" + binvalue + ")");
}
}
}
Never mind figured it out.... just turned System.out.println("Sum = " + sum); into System.out.println("Mean = " + sum/100);

sql prepared statements insertion succeeds but no entries are visible in the table

I am using sql prepared statements in my application.
The statements are prepared fine and executed fine.
After that ,when I see the table, there are no entries.
Code snippet:
void DirEntTable::do_init()
{
m_insertIntoSrvrEntTable.setStatement("INSERT INTO " + tableName() + " (entKey, srvrType, serverID, serverEntID) VALUES (" + entKeyField + ", " + srvrTypeField + ", " + serverIDField + ", " + serverEntIDField + ")");
m_insertIntoSrvrEntTable.setConnection(m_db);
if ((rc = m_insertIntoSrvrEntTable.prepare()) != SQLITE_OK)
{
LOGDEBUG("DirEntTable", "insertIntoSrvrEntTable prepare failed (%d) table %s\n", rc, tableName().c_str());
}
}
eErrorT DirEntTable::insertIntoSrvrEntTable(const int entryId, const int serverType,
const std::string &serverID, const std::string &serverEntID)
{
LOGDEBUG(__FUNCTION__, "\nvalues : entryId = %d, serverType = %d, serverID = %s, serverEntID =%s\n",entryId,serverType,serverID.c_str(),serverEntID.c_str());
eErrorT rc = kNoError;
m_insertIntoSrvrEntTable.bindInt(entKeyField, entryId);
m_insertIntoSrvrEntTable.bindInt(srvrTypeField, serverType);
m_insertIntoSrvrEntTable.bindText(serverIDField, serverID);
m_insertIntoSrvrEntTable.bindText(serverEntIDField, serverEntID);
if (!m_insertIntoSrvrEntTable())
{
rc = kFuncReturnedError;
}
m_insertIntoSrvrEntTable.reset();
return rc;
}
Output:
values : entryId = 46, serverType = 2, serverID = gds0, serverEntID =gds:330
query "INSERT INTO gdsEntries (entKey, srvrType, serverID, serverEntID) VALUES (:entKey, :srvrType, :serverID, :serverEntID)"
Please help me in understanding what could be wrong.