Java.lang.NumberFormatException thrown - java

I am trying to write a program for converting positive binary inputs into hex.
Why am i getting this errors while compiling my binary to hex converter..
Exception in thread "main" java.lang.NumberFormatException: For input string: "148.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at BinToHex.convertbintohex(BinToHex.java:24)
at Test.main(Test.java:4)
Here is my BinToHex class
import java.io.*;
public class BinToHex {
double tempDec,fractionpart;
long longofintpart,templongDec;
String inpu ="1001.01";
String hexOutput,intpart,tempDecString,hex = null;
static int i = 1;
public void convertbintohex() {
if (inpu.contains(".")) {
int placesAfterPoint = inpu.length() - inpu.indexOf(".") - 1;//every thing
long numerator = Long.parseLong(inpu.replace(".", ""), 2);//goes
double decimalOfInput = ((double) numerator) / (1L << placesAfterPoint);//alright till here
while (true) {
tempDec = decimalOfInput * 16;
if ((int)tempDec == tempDec) {
tempDecString = String.valueOf(tempDec);
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
break;
} else {
intpart = String.valueOf((long)tempDec);
longofintpart = Long.valueOf(intpart).longValue();
if(i==1){
hex=Long.toHexString(longofintpart);
hexOutput = hex + ".";
i=i+1;
}else{
hexOutput = hexOutput + hex;
}
fractionpart = tempDec-(int)tempDec;
decimalOfInput = fractionpart;
}
}
} else {
// this part is ok
tempDecString = String.valueOf(Integer.parseInt(inpu, 2));
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
}
System.out.println(hexOutput);
}
}
and my Test class..
public class Test{
public static void main(String args[]){
BinToHex i = new BinToHex();
i.convertbintohex();
}
}
sorry for such a question ;-)
really need help

Long.parseLong "Parses the string argument as a signed long". 148.0 is a double.
You're using a cast in the "if" statement, but not afterwards:
if ((int)tempDec == tempDec) {
tempDecString = String.valueOf(tempDec);
templongDec = Long.parseLong(tempDecString, 10);
instead, try:
if ((long)tempDec == tempDec) {
tempDecString = String.valueOf((long)tempDec);
templongDec = Long.parseLong(tempDecString, 10);
You're already doing that later on in the else statement, you just missed it above. I think there are other issues in this code but this should answer the original question.

Related

NZEC error for ACODE spoj

I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.

Comparing two time values [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have participated in a challenge, in which the requirement is to compare two time values t1 and t2, and print First if t1 occurs before t2 ; otherwise, print Second.
And, t1 != t2.
Sample Input:
2
10:19PM 02:49AM
08:49AM 09:10AM
Sample Output:
Second
First
My code:
import java.util.*;
public class Solution {
static String timeCompare(String t1, String t2){
// Complete this function
String half1 = t1.substring(t1.length()-2); // gets AM/PM value
String half2 = t2.substring(t2.length()-2);
String time1 = t1.substring(0, t1.length()-2);
String time2 = t2.substring(0, t2.length()-2);
//System.out.println(time1);
int hour1 = Integer.parseInt(time1.split(":")[0]);
int hour2 = Integer.parseInt(time2.split(":")[0]);
int min1 = Integer.parseInt(time1.split(":")[1]);
int min2 = Integer.parseInt(time2.split(":")[1]);
if(hour1 == 12) {
hour1 = 0;
//System.out.println(hour1);;
}
if(hour2 == 12) {
hour2 = 0;
}
//System.out.println(hour1+" , "+hour2);
if(half1.equals(half2)){
// System.out.println(1);
if(hour1 == hour2){
if(min1 > min2){
return "Second";
}
else{
return "First";
}
}
else if(hour1 > hour2){
return "Second";
}
else{
//System.out.println(2);
return "First";
}
}
else if (half1 == "AM"){
return "First";
}
else{
return "Second";
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int a0 = 0; a0 < q; a0++){
String t1 = in.next();
String t2 = in.next();
String result = timeCompare(t1, t2);
System.out.println(result);
}
}
}
I am not sure what am I doing wrong. But only 1 out of 10 test cases passed.
Can you tell what's wrong?
half1 == "AM" Here you have made a mistake. For String comparison , You need to use String#equals() method.
So change that line with half1.equals("AM"). This will do your work.
Refer to example here:
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime t1 = LocalTime.of(10, 10, 0)
LocalTime t2 = LocalTime.of(11, 11, 0);
int result = t2.compareTo(t1);
if(result < 0){
System.out.println("Second");
}else if(result > 0 ){
System.out.println("First");
}else{
System.out.println("Same Time");
}
}
}
The code above generates the following result:
Second

issue in debugging code for class

so i'm doing a project for my Computer Science class where i'm building a wheel of fortune game, and for some reason im having an error with debugging my code. if anyone can help, id be very greatful.
** full code in comments wont let me post it ***
public class WheelOfFortune {
private String Hidden;
public WheelOfFortune(String g) {
Hidden = g;
}
public String getHint(String g) {
String letter, HL, result = "";
int x = g.length(), y = 0;
for (int i = 0; i < x; i++) {
letter = g.substring(i, i + 1);
HL = Hidden.substring(i, i + 1);
if (letter.equals(HL)) {
result += letter;
y = Hidden.indexOf(letter);
}
if (y == -1) result = "*";
else result = "+";
return result;
}
}
}
public class Puzzle {
public static void main(String[] args) {
WheelOfFortune guess = new WheelOfFortune("HARPS");
String turn = guess.getHint("AAAAA");
System.out.println(turn);
}
}
Your code didn't even compile because of a missing return statement after the for loop. With this and other errors corrected, your getHint() is:
public String getHint(String g)
{
String letter, HL, result = "";
int x = g.length();
for (int i = 0; i < x; i++)
{
letter = g.substring(i, i + 1);
HL = Hidden.substring(i, i + 1);
if (letter.equals(HL)) result += letter;
else
if (Hidden.contains(letter)) result += "+";
else
result += "*";
}
return result;
}

Java Array Bound Exception

I'm trying to make a program for a password security, but many times I get Java Array Index Out of Bounds Exception...I tried to fix, but nothing, this is my code:
import java.util.Arrays;
public class BruteForce {
public static void main(String[] args) {
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true) {
if (attempt.equals(password)) {
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while (index >= 0) {
if (cg[index] == cs[cs.length - 1]) {
if (index == 0) {
cg = new char[cg.length + 1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString() {
return String.valueOf(cg);
}
}
When I try to add special char(s):
import java.util.Arrays;
public class BruteForce
{
public static void main(String[] args)
{
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true)
{
if (attempt.equals(password))
{
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength)
{
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment()
{
int index = cg.length - 1;
while(index >= 0)
{
if (cg[index] == cs[cs.length-1])
{
if (index == 0)
{
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
}
else
{
cg[index] = cs[0];
index--;
}
}
else
{
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString()
{
return String.valueOf(cg);
}
}
And I get something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -65
The difference between
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
and
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##"
is that in the first case, the characters are in ascending order (characters in java have a value).
Arrays.binarySearch requires the array to be in ascending order.
If you use
"#.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
instead (or use Arrays.sort in the BruteForce constructor) it should work.
Always remember to post the exact code that you are using!

How do I input&solve expressions like sin(60)*50/4 in my simple calculator(without GUI) in Java?

I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}

Categories