Negative int to hexadecimal conversion - java

I am converting some integers to hexadecimals but the problem i have is when i pass a negative value to convert it to hex.
Example:
String satpos = "13.0";
String satposs=satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
String nids = Integer.toHexString(satposition);
String finished = nids+"0000";
Application returns "820000" in this case and that is the correct value i need.
But if i pass:
String satpos = "-7.0";
String satposs=satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
String nids = Integer.toHexString(satposition);
String finished = nids+"0000";
Application returns "ffffffba0000" but i should get "DCA0000"
Any help is appreciated.

Based on a comment by Andreas, here is a test program that prints the values you want:
public class Test {
public static void main(String[] args) {
convert("13.0");
convert("-7.0");
}
private static void convert(String satpos) {
String satposs = satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
if (satposition < 0) {
satposition += 3600;
}
String nids = Integer.toHexString(satposition);
String finished = nids + "0000";
System.out.println(finished);
}
}
If the angle is negative, add 3600 because the angle is in tenths of a degree.

Related

How to shorten (format) String output properly?

Simple questions as a beginner making big problems.
I want to shorten (format) a String to only show 1 decimal or 2. Unlucky it is a String not a double.
String getNumber = "6.000m";
I know there is a printf() function but as far I learned it is to print multiple string in a proper order.
How can I make the output to be with only one decimal or if it has more numbers which aren't 0?
6.000 m --> 6.0
4.900 m --> 4.9
4.750 m --> 4.75
I assume it is always "m" at the end with some optional whitespace in front of it. So I remove it first using a regex.
DecimalFormat is your friend to do the rest:
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Ff {
static Pattern numberPart=Pattern.compile("([0-9.]*)\\b*m");
static DecimalFormat df=new DecimalFormat("0.0#####");
public static String format(String input)
{
Matcher m=numberPart.matcher(input);
if(m.matches())
{
return df.format(Double.parseDouble(m.group(1)));
}
return null;
}
public static void main(String args[]) {
System.out.println(format("6.000m"));
System.out.println(format("4.900m"));
System.out.println(format("4.750m"));
}
}
and the output is:
6.0
4.9
4.75
You shouldn't use regex, because it is very hard to maintain.
As an example:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-
\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:
(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-
5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|
[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\
[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
This is a part of some code to validate an email with a regex. Regexes were necessary back then when computers were slow, because regexes are fast. Nowadays you don't need them anymore and maintenance is key.
After using the test cases:
0.000 m -> 0.0
1.000 m -> 1.0
9.000 m -> 9.0
1.100 m -> 1.1
1.900 m -> 1.9
1.110 m -> 1.11
1.010 m -> 1.01
1.111 m -> 1.111
1.101 m -> 1.101
1.101m -> 1.101
I've come to this conclusion:
shortenGivenNumber(String wholeNumber); will be the Method you'll use to shorten your number. The other methods are there to make the main method more readable.
public class NumberShortener {
public String shortenGivenNumber(String wholeNumber) {
int endOfShortNumber = findEndOfNumber(wholeNumber);
String shortenedNumber = cutOutNumber(wholeNumber, endOfShortNumber);
return shortenedNumber;
}
private int findEndOfNumber(String numberWithZeroesAndM) {
int lastZero = findIndexOfZeroAfterNumber(numberWithZeroesAndM);
int endOfNumber = lastZero;
endOfNumber = handleNo0AtEndCase(numberWithZeroesAndM, lastZero, endOfNumber);
return endOfNumber;
}
private int findIndexOfZeroAfterNumber(String wholeNumber) {
int lastZero;
int searchIndex = 3;
boolean numberAfterZero;
do {
numberAfterZero = false;
lastZero = findNextIndexOfZero(wholeNumber, searchIndex);
numberAfterZero = isANumberAfterThisZero(wholeNumber, lastZero);
searchIndex++;
}while(numberAfterZero == true && valueExistsAtEnd(lastZero));
return lastZero;
}
private int findNextIndexOfZero(String wholeNumber, int searchIndex) {
return wholeNumber.indexOf("0", searchIndex);
}
private boolean isANumberAfterThisZero(String wholeNumber, int lastZero) {
boolean numberAfterZero = false;
for(int i = 1; i < 10; i++){
char characterAfterZero = getCharacterAfterZero(wholeNumber, lastZero);
char iAsChar = convertIntToChar(i);
if(isTheCharacterThisNumber(characterAfterZero, iAsChar)){
numberAfterZero = true;
}
}
return numberAfterZero;
}
private boolean valueExistsAtEnd(int lastZero) {
return lastZero != -1;
}
private int handleNo0AtEndCase(String wholeNumber, int lastZero, int endOfNumber) {
if(thisSignIsntAtEnd(lastZero)){
int indexOfSpace = getIndexOfSpace(wholeNumber);
endOfNumber = indexOfSpace;
endOfNumber = handleNoSpaceAtEndCase(wholeNumber, endOfNumber, indexOfSpace);
}
return endOfNumber;
}
private int getIndexOfSpace(String wholeNumber) {
return wholeNumber.indexOf(" ");
}
private int handleNoSpaceAtEndCase(String wholeNumber, int endOfNumber, int space) {
if(thisSignIsntAtEnd(space)) {
int indexOfM = getIndexOfM(wholeNumber);
endOfNumber = indexOfM;
}
return endOfNumber;
}
private int getIndexOfM(String wholeNumber) {
return wholeNumber.indexOf("m");
}
private char getCharacterAfterZero(String wholeNumber, int indexOfZero) {
int indexAfterZero = indexOfZero+1;
return wholeNumber.charAt(indexAfterZero);
}
private char convertIntToChar(int i) {
return (char) (i+48);
}
private String cutOutNumber(String wholeNumber, int endOfNumber) {
return wholeNumber.substring(0, endOfNumber);
}
private boolean isTheCharacterThisNumber(char characterAfterZero, char iAsChar) {
return characterAfterZero == iAsChar;
}
}
It always copies the first 3 characters(x.x). The first 0 (after the x.x), without any number following, will be used as the last index which indicates the end of the final number substring. If there are numbers over 0 until the end, it will use the space (1.123 m). If there isn't a space, it will use the m (1.123m).

A method that calls another method for Strings

I have this assignment below:
I have two methods that modify strings simultaneously.
I have searched on many posts but couldn't find the answer.
I want the second method to modify (call) the result of the first one.
I am a neophyte to Java so thanks for your patience and understanding.
Assignment:
Part 1 - Normalize Text
Write a method called normalizeText which does the following:
Removes all the spaces from your text
Remove any punctuation (. , : ; ’ ” ! ? ( ) )
Turn all lower-case letters into upper-case letters
Return the result.
The call normalizeText(“This is some \“really\” great. (Text)!?”)
should return
“THISISSOMEREALLYGREATTEXT”
Part 2 - Obfuscation
Write a method called obify that takes a String parameter (the message to be obfuscated) and returns a string in which every vowel (A, E, I, O, U, Y) is preceded by the letters “OB” (be sure to use capital letters).
If we call obify on “THISISSOMEREALLYGREATTEXT”, it should return
“THOBISOBISSOBOMOBEROBEOBALLOBYGROBEOBATTOBEXT”
My code:
public class CryptoAssessment {
public static void main(String[] args) {
normalizeText("This is some \“really\” great. (Text)!?");
}
public static void normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print(Result_after_Normalization);
}
public static void Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print(Result_after_Obfuscation);
}
}
To pass the result of a call to method1() to a call to method2():
method2(method1("foo"))
To complete your assignment:
public static void normalize(String str) {
return str.replaceAll("\\W", "").toUpperCase();
}
public static void obfuscate(String str) {
return str.replaceAll("[AEIOU]", "OB$0");
}
Ah, I get your problem. You don't want to simply pring on the Console System.out - you need to return those strings back to the caller.
public static String normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print("After normalization: "+Result_after_Normalization);
return Result_after_Normalization;
}
And lets make the other one return a String as well
public static String Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print("After obfuscation: "+Result_after_Obfuscation);
return Result_after_Obfuscation;
}
And now the main() becomes this:
public static void main(String[] args) {
String result = obfuscate(normalizeText("This is some \“really\” great. (Text)!?"));
System.out.println("Result after doing both: "+result);
}
Was typing this out last night when i ran out of battery, so ergo the delay in answering.
You can use a method's return as another method's argument, as long as the type match.
First change your methods' signature like this(make them to return a value):
public static String normalizeText(String string_to_encrypt){...}
public static String Obfuscation(String string_to_Obfuscate){...}
Then you can use the return value:
String temp = normalizeText("This is some \“really\” great. (Text)!?");
String result = Obfuscation(temp);
Or:
String result = Obfuscation(normalizeText("This is some \“really\” great. (Text)!?"));

Social.java and SocialRunner.java

I am doing a social security program where you take apart a SS #, remove the hyphens (-), and parse the 3 parts into integers and add up.
Here is the main runner:
import static java.lang.System.*;
public class SocialRunner
{
public static void main( String args[] )
{
Social social = new Social("1-1-1");
//add test cases
//social.Social("1-1-1");
//social.chopAndAdd();
//boolean check = stringlivesmatter.checkEquality();
out.println(social);
}
}
And here is the main program:
import static java.lang.System.*;
public class Social
{
private String socialNum;
private String ssNum1, ssNum2, ssNum3, sub;
private int sum;
public Social()
{
}
public Social(String soc)
{
socialNum = soc;
}
public void setWord(String w)
{
/*String ssNum1 = socialNum.substring(0,socialNum.indexOf("-"));
String ssNum2 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
String ssNum3 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
*/
}
public void chopAndAdd()
{
sub = socialNum;
ssNum1 = socialNum.substring(0,socialNum.indexOf("-"));
ssNum2 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.lastIndexOf("-"));
ssNum3 = socialNum.substring(socialNum.lastIndexOf("-")+1,0);
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
}
public String toString()
{
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
/*
String ssNum1 = socialNum.substring(0,socialNum.indexOf("-"));
String ssNum2 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
String ssNum3 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
*/
return "SS# " + socialNum + " has a total of " + sum + "\n";
}
}
With the way the two programs above are written, I am given a runtime error:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Social.toString(Social.java:46)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at SocialRunner.main(SocialRunner.java:20)
If I comment/delete:
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
from
public String toString()
I get:
SS# 1-1-1 has a total of 0
How can I avoid a runtime or logic error?
You only need to remove the dashes to get your number.
public void chopAndAdd()
{
String con = socialNum.replaceAll("-", "");
sum = Integer.parseInt(ssNum1) ;
}
You probably may need to modify this as well
public String toString()
{
this.chopAndAdd();
return "SS# " + socialNum + " has a total of " + sum + "\n";
}
and
public static void main( String args[] )
{
Social social = new Social("1-1-1");
social.chopAndAdd();
out.println(social.toString(););
}
Take your time go through and analyse very well to your understanding
Change your constructor in Social as follows so that the ssNum variables are actually set.
public Social(String soc)
{
socialNum = soc;
String[] chunks = soc.split("-");
ssNum1 = chunks[0];
ssNum2 = chunks[1];
ssNum3 = chunks[2];
}
Using String.split will break up the ssn into a String[3], each element of which will contain the numbers excluding what you split on, in this case hyphens.
e.g. [123, 12, 1234]
Then all you need to do is parse them and sum them up.
public static void main(String[] args)
{
String socialString = "123-12-1234";
System.out.println(chopAndAdd(socialString));
}
public static int chopAndAdd(String s)
{
String[] chunks = s.split("-");
int first = Integer.parseInt(chunks[0]);
int second = Integer.parseInt(chunks[1]);
int third = Integer.parseInt(chunks[2]);
return first + second + third;
}

How to parse string to get double value from it

Help me please for the next problem:
There is String pattern, assume it's public final static variable. There is string where we search. There is class, simple wrapper to double
public class Wrapper {
private double value;
public double getValue() {
return value;
}
public Wrapper(double value) {
this.value = value;
}
}
I need method
public Wrapper parse(String s, int index)
which returns Wrapper's object if string at the index is double number with maximum 2 digits after decimal point(if there is decimal point at all) and right after number ends there is String pattern after it
For example for strings
String pattern = "money";
String search = "Giveme10.25moneyplease";
parse(search, 6) returns new Wrapper(10.25)
In other cases (index less then zero, greater then length of the string, substring that starts from index isn't number at all or it's double number but it contains more then 2 digits after decimal point or there is no string pattern after number) method must return null
And another method that differs only string pattern must be first and then double number with maximum 2 digits after decimal point and all other the same
String pattern = "money"
String s = "Ihavemoney10.50"
parse1(s, 5) returns new Wrapper(10.50)
You can use DecimalFormat along with ParsePosition like this
import java.text.DecimalFormat;
import java.text.ParsePosition;
public class TestP {
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat("00.##'money'");
String search = "Giveme10.25moneyplease";
int index = 6;
//output 10.25
Number number = decimalFormat.parse(search, new ParsePosition(index));
if (number != null) {
String s = number.toString();
if (s.contains(".") && s.length() > 5) {
number = null;
}
}
System.out.println(number);
}
}

list of doubles, print a String

I have a list of values (Weather data), the people who wrote the list used the value "9999" when they did not have a value to report. I imported the text file and used the following code to take the data, and edit it:
import java.io.*;
import java.util.*;
public class weatherData {
public static void main(String[] args)
throws FileNotFoundException{
Scanner input = new Scanner(new File("PortlandWeather2011.txt"));
processData(input);
}
public static void processData (Scanner stats){
String head = stats.nextLine();
String head2 = stats.nextLine();
System.out.println(head);
System.out.println(head2);
while(stats.hasNextLine()){
String dataLine = stats.nextLine();
Scanner dataScan = new Scanner(dataLine);
String station = null;
String date = null;
double prcp = 0;
double snow = 0;
double snwd = 0;
double tmax = 0;
double tmin = 0;
while(dataScan.hasNext()){
station = dataScan.next();
date = dataScan.next();
prcp = dataScan.nextInt();
snow = dataScan.nextInt();
snwd = dataScan.nextInt();
tmax = dataScan.nextInt();
tmin = dataScan.nextInt();
System.out.printf("%17s %10s %8.1f %8.1f %8.1f %8.1f %8.1f \n", station, date(date), prcp(prcp), inch(snow), inch(snwd), temp(tmax), temp(tmin));
}
}
}
public static String date(String theDate){
String dateData = theDate;
String a = dateData.substring(4,6);
String b = dateData.substring(6,8);
String c = dateData.substring(0,4);
String finalDate = a + "/" + b + "/" + c;
return finalDate;
}
public static double prcp(double thePrcp){
double a = (thePrcp * 0.1) / 25.4;
return a;
}
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = 9999;
}
return a;
}
public static double temp(double theTemp){
double a = ((0.10 * theTemp) * 9/5 + 32);
return a;
}
}
The problem I am having is taking the values and checking for all times "9999" comes up, and printing out "----". I don't know how to take in a value of type double, and print out a String.
This code takes the values and checks for the value 9999, and does nothing with it. This is where my problem is:
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = "----";
}
return a;
}
I'm sorry if I put to much information into this question. If you need me to clarify just ask. Thanks for any help!
You need to modify your inch function to return a string, not a double.
public static String inch(double theInch){
if(theInch == 9999){
return "----";
}
return Double.toString(theInch/25.4);
}
I think the first problem might be that you're reading all the values from the Scanner as int instead of doubles. For example, based on your System.out.println() statement, I think you should actually be reading the following data types...
prcp = dataScan.nextDouble();
snow = dataScan.nextDouble();
snwd = dataScan.nextDouble();
tmax = dataScan.nextDouble();
tmin = dataScan.nextDouble();
Also, seeing as though the inch() method is only going to be used in the System.out.println() line, you'll need to change it to a String as the return type...
public String inch(double theInch){
if (theInch == 9999){
return "----";
}
return ""+(theInch/25.4);
}

Categories

Resources