Problems With Strings!
I am very new to java programming so please, any help would be much appreciated.
I am having trouble with my university assignment in the sense that i am trying to create a simple base converter whos only function will be to convert a number that has been input from base 16 to base 10.
I want to b able to make the program display an error message saying there was an invalid input if a number outside of the hexadecimal range is given, (ie. if the hex number was 'abg' it would be invalid, since hex is 0-9 and ABCDEF).
What method can i use to make a boolean statement whether it is valid or not so that i can use that boolean in an if-else statement?
Thanks in advance, any help is much appreciated.
Also a note, I must make this program using strings, criteria for the marks say that we cannot use any of the (int radix) and printf statements.
You could write a method like this boolean isValid(String input) {
// Test input character-by-character, in a loop.
// If you find an invalid char, immediately return false.
// If you get to the end of the loop without having returned false, return true.
}
...
boolean inputValid = isValid(input);
What specific part are you having trouble with?
jverda at 2007-7-11 23:57:36 >

Below is a segment of my code. What I want is the string number to consist of only the elements in the string buffer but in no particular order.
Thanks a million for your time.
{
String buffer = ("0123456789ABCDEFabcdef");
int base = 10;
int remainder;
String dec = "";
System.out.print("Enter the integer in base 16: ");
String number = keyboard.nextLine();
if (number.contentEquals(buffer))
{
System.out.println("Working");
}
else
{
System.out.println("not working");
}
You could try to parse it and catch the exception. No point reinventing the wheel.
You're not allowing negative numbers?Integer.parseInt is certainly the easiest way to see if a string can represent a number in a given base. If you need to eliminate negatives, then you could just test if (number < 0) after a successful parse.
jverda at 2007-7-11 23:57:36 >

> You could try to parse it and catch the exception. No> point reinventing the wheel.The OP did say this was a homework assignment. I'm guessing the point is for him to implement the logic himself / herself.- Adam
> > You could try to parse it and catch the exception.
> No
> > point reinventing the wheel.
>
> The OP did say this was a homework assignment. I'm
> guessing the point is for him to implement the logic
> himself / herself.
Then he needs to figure out his algorithm and write it out precisely and in complete detail, and then figure out how each step translates to Java. The code he posted looks like just a wild guess that was hucked at the wall to see what'd stick.
jverda at 2007-7-11 23:57:36 >

> Below is a segment of my code. What I want is the
> string number to consist of only the elements
> in the string buffer but in no particular
> order.
>
> Thanks a million for your time.
>
>
> {
> String buffer =
> ("0123456789ABCDEFabcdef");
>int base = 10;
> int remainder;
>String dec = "";
> System.out.print("Enter the integer in base 16: ");
>String number = keyboard.nextLine();
> if (number.contentEquals(buffer))
>{
>System.out.println("Working");
> }
>else
> {
>System.out.println("not working");
>}
I don't think you really want to use a StringBuffer here. Searching in strings, even in StringBuffer is slow (not that it's going to make a huge difference for a homework assignment).
If I was really going to implement something like this, I would use this (admittedly, it's bad form to omit the break in switch statements, but in this case, it serves a purpose):
private static boolean isValidHexChar(char c) {
switch (c) {
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
case '8': case '9': case 'a': case 'A': case 'b': case 'B': case 'c': case 'C':
case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': case '+': case '-':
return true;
}
return false;
}
This is going to be about as fast as it can get, and it will also be handy when it becomes time to actually calculate the value of the number, because you can use each different case to return a different value.
- Adam
Thank you Adam! That solves my problem. I knew the mathematical algorith for converting between bases but i was unsure how to restrict input to hex, i was thinking of using if..else if statements but a breakless switch seems much more logical.
Thank you all for your time and effort. It was much appreciated!
Cheers,
Peter
ok so ive got another dilemma.
i am on my way into writing the hexadecimal to decimal part of my base converter program and i have come across a problem that has stumped me for hours.
i have the following java code.
String reference = "0123456789ABCDEF";
double total =0;
String hex = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your hex number");
String input = keyboard.nextLine();
for (int i = input.length()-1; i<=0; i--)
{
hex = hex + input.charAt(i);
}
for (int j = 0; j >= hex.length()-1; j++)
{
total = total+(Math.pow(16,j))*((hex.charAt(j)).indexOf(reference));
}
System.out.println("The hex number: "+input+" is: "+total+" in decimal format.");
what i want is the the bit ((hex.charAt(j)).indexOf(reference)) simply to return the character at the index of 'j' in the string 'hex' and then to find the index of that returned character in the string 'reference'. When i compile the code as it is above, i get the following error:
javac Hex.java
Hex.java:28: char cannot be dereferenced
total = total+(Math.pow(16,j))*((hex.charAt(j)).indexOf(reference));
^
i cannot understand what the problem in the code is. As i said before i am a noob at java programming so any help would be much appreciated.
Thank you for your time and effort,
Peter
((hex.charAt(j)).indexOf(reference))What do you think that's supposed to do?Please explain the overall purpose of it, and then explain what you think each piece does.
jverda at 2007-7-11 23:57:36 >

I have figured it out. What i needed was 2 variables in the for loop and some proper syntax.
My code now looks like:
import java.util.*;
public class Hex
{
public static void main(String args[])
{
String reference = "0123456789ABCDEF";
double total =0;
String hex = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your hex number");
String in = keyboard.nextLine();
String input = in.toUpperCase();
for (int j = input.length()-1, i=0; j>=0 ; j--, i++)
{
total = total+(Math.pow(16,i))*(reference.indexOf(input.charAt(j)));
}
System.out.println("The hex number: "+input+" is: "+total+" in decimal format.");
}
}
It converts decimal to hex. now i need to figure a way to ensure only valid hex numbers are entered into the 'input', for example i want an error message to occur if a number containing a non hex, (such as abbg) is intered into the keyboard for the variable input.
Thank you all for your help.
> Thank you Adam! That solves my problem. I knew the
> mathematical algorith for converting between bases
> but i was unsure how to restrict input to hex, i was
> thinking of using if..else if statements but a
> breakless switch seems much more logical.
> Thank you all for your time and effort. It was much
> appreciated!
Well, you could check that the character codes fall in certain limits. But this has other advantages, and it's not so much about logic.
This sort of operation (I expect) would be carried out quite often, so it should be very fast. The switch statement is implemented as a lookup table in the byte code (at least, it is recommended to be done that way in the vm spec). This makes it much faster than a cascading set of if ... then ... else blocks.
The better part about that implementation, though, is that its purpose is very clear. It states decisively exactly what characters ARE allowed, and all others are not. To somebody reading your code, you can't ask for much better than that. The other solution (arithmetic on character codes) requires people to have their ascii chart in front of them to understand what each line of code means, in order to find a bug, if one exists.
- Adam
