46
Nov 13 '20 edited Nov 13 '20
The function never returns -1, it just quits! This one does return -1 so that someone could use a while loop to get the digit:
public static int evalDigit(string in, int max) {
int result = -1;
try {
result = String.parseInt(in.trim());
if (result > max) {
System.out.println(String.format("The digit entered was too high (max is %d), try again", max));
result = -1;
}
if (result < 0) {
System.out.println("Negative digits not allowed, try again");
result = -1;
}
}
catch (NumberFormatException e) {
System.out.println("Invalid digit was entered, try again");
}
return result;
}25
u/HolySpecs Nov 13 '20
I just declared result as -1 because I didn't want the program to pass something if the data entered wasn't valid. Also, I wasn't allowed to use loops of any kind so yay more pain for me. It was an exercise to practice using recursive functions.
7
u/DesiresQuiet Nov 13 '20
What loop?
2
u/HolySpecs Nov 13 '20
One of the conditions I was given was that I couldn't use for loops, while loops or do while loops for the entirety of the code
3
1
u/halfanothersdozen Nov 14 '20
You can't use loops, huh?
Why?
I swear these classes don't prepare to code in the real world.
0
3
u/AutoModerator Nov 13 '20
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/lovegro, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
You can find some examples in the reddit help documentation.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/LifeHasLeft Nov 13 '20
That was my first thought. Exiting this way hasn’t seemed like a good idea to me since maybe when I was in my first classes. But I could argue proper error handling is a skill in and of itself
9
u/jubiman Nov 13 '20
Just use Interger.parseInt(str);
3
u/HolySpecs Nov 13 '20 edited Nov 13 '20
I wanted to do that but the normal inputs for the program were like:
+99 9 -98 &4 &4+89 (this line is wrong)so if I did use Integer.parseInt(str) then I would get errors if, for example:
9+9was entered
6
u/jubiman Nov 13 '20
It will still return an error with this as it will go to the default case for 9+9. I’d recommend implementing a string searching algorithm before using parseint to then do the + operation
1
u/HolySpecs Nov 13 '20
The thing is that this kind of calculator is only allowed to take in inputs like +99, not 9+9, even though the second one makes more sense. Sorry if I sound a bit annoying.
2
u/icuninghame Nov 13 '20
You're learning Polish notation and stuff right?
It might be easier to reverse the input string first. (ex. if the user inputs +3+45, use a string reversing algorithm to give you 54+3+) this will make it easier to parse inputs with multiple operations, since its in the correct order of operations now. For +3+45 = 54+3+, 54+ = 5+4 = 9, then 93+ = 9+3 = 12. If you were in the original notation, you'd have to add extra logic in your string parsing to find which operation to do first.
When its reversed, you can simply take the first two characters of the string, (in ex above that's 5 and 4) make sure they're valid numbers 0-9, then perform the operation that is after them (+). Return the result as your first digit (9), then read the second digit (3) and the operation after it (+). Perform the operation and continue the above until you reach the end of the String, at which point you print the result to the console.
The hardest part is the String parsing, but if you get that right, isolating the operations and the digits, it'll be a lot easier to work with.
1
u/CollieOop Nov 13 '20
So instead you made a function that will call System.exit(2) on those inputs being entered instead of throwing an exception?
1
Nov 13 '20
You could also create an char array and fill it with "0" to "9" Then go through that array and if you inputChar==charArray[i] return i
Under the for loop you return an error like -2 or whatever. Because parseInt will also read "10" Which is not a valid digit...
49
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Nov 13 '20
Image Transcription: Code
//gets the digit value and returns it as an int and if not valid, exists
public static int evalDigit(String in){
int result = -1;
switch (in){
case "0":
result = 0;
break;
case "1":
result = 1;
break;
case "2":
result = 2;
break;
case "3":
result = 3;
break;
case "4":
result = 4;
break;
case "5":
result = 5;
break;
case "6":
result = 6;
break;
case "7":
result = 7;
break;
case "8":
result = 8;
break;
case "9":
result = 9;
break;
default:
System.out.println("Invalid digit was entered, try again");
System.exit(2);
}
return result;
}I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
23
u/OptimalMain Nov 13 '20
If(in >= 48 && in <= 57){ result = in - 48 }
39
u/ILikeSahne Nov 13 '20
Well but you are fucked when you don't know ascii, this is better: if(in >= '0' && in <= '9') { result = in - '0'; }
8
u/HolySpecs Nov 13 '20
I would do that but I can't, I was tasked to only take in single digits, which is fun 🙃
5
u/jim3692 Nov 13 '20
Does this work on Java? I know that it works on C and C++, but "in" must be char type.
4
u/qh4os Nov 14 '20
Actually the code they put doesn’t work at all — or rather it does, but not as they intended.
In this case they were actually comparing an address to a number (assuming String => char* in the case of C), which is perfectly valid, but that condition is likely never going to evaluate as true.
But even in Java, character literals are just numbers, so the comparison should be fine if that error is corrected
6
u/emacsos Nov 13 '20
You're going to need to try and get the first character though. This is a string, not a char
2
u/HolySpecs Nov 13 '20
Good point, I think I typed String out of habit but then it is part of a recursive function and I didn't wanna break it so yh 🙃
2
3
u/SquirrelBlind Nov 13 '20
it's String, not char.
3
u/Tyfyter2002 Nov 13 '20
Which is part of the reason this is bad code, instead of using
charit usesStringand closes the program with an error message if the string given isn't a single character2
21
u/jess-sch Nov 13 '20
Eh, this isn't so bad. A good compiler will recognize this and optimize it awa--
Oh nvm this seems to be java
2
7
u/ekolis Nov 14 '20
System.exit(2);
So yeah, let's not even throw an exception, let's just print an error message to the console (from a library, it seems, so there might not even be a console) and crash the whole program...
5
3
u/hhellloo Nov 13 '20
I think this is better.
public static int evalDigit(string x)
{
int result = Convert.ToInt32(x);
if(result > 9 || result < 0)
{
result = -1;
}
return result;
}Edit: Oh, it is in Java, I thought it was c#
2
u/AutoModerator Nov 13 '20
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/hhellloo, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
You can find some examples in the reddit help documentation.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
2
u/Chroniaro Nov 13 '20
Pretty sure this would still compile in C#, but the camelCase method name and capital S in String kinda give it away
2
1
1
u/wktr_t Nov 14 '20
I think I'm leaving this sub, people seem to have gained access to code from my side projects.
1
u/Kllngii Nov 14 '20
The thing that bothers me most is that the type of in is string, not char, yet its evaluate digit not digits. Also -1 will never be returned but this is totally fine to spot errors while coding.
1
1
u/M3ther Nov 14 '20
This could actually be done simply by:
public static int evalDigit(String in) {
int result = -1;
int input = -1;
try {
input = Integer.parseInt(in);
if (input >= 0 && input < 10) {
result = Integer.parseInt(in);
}
else {
System.out.println("Invalid digit was entered, try again");
System.exit(2);
}
}
catch (Exception e) {
System.out.println("Invalid digit was entered, try again");
System.exit(2);
}
return result;
}1
1
16
u/HolySpecs Nov 13 '20 edited Nov 13 '20
So I was tasked to make a recursive parsing calculator and it could only take in single digits from 0 to 9, which resulted in me doing this mess. It was either this or using if statements so I chose the former.
Edit 1:
This was a task given to me from a teacher and they gave me specific requirements such as:
I can't use loops (no while, do repeat or for loops)
the format for the inputs are:
where + is for add, - is for subtract, and & is for sum from one to that number
This means if I want to, say do 3+4+5 I'd have to enter
Thanks for the responses guys, it's really interesting to see other's perspectives!
Edit 2: Just realised I should've said Switch-case in the title, not switch-catch. I was thinking of try-catch.
Edit 3: the result = - 1 is just a placeholder, it's not really important