C
C#2y ago
shawski.

✅ runtime error

using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Result
{

/*
* Complete the 'plusMinus' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/

public static void plusMinus(List<int> arr)
{
int positive = 0;
int negative = 0;
int zero = 0;

for (int i = 0; i > arr.Count; i++)
{
if (arr[i] < 0)
{
negative++;
}
else if (arr[i] > 0)
{
positive++;
}
else if (arr[i] == 0)
{
zero++;
}

}
Console.WriteLine(string.Format("{0.0.000000}\n", (positive / arr.Count)) + string.Format("{0.0.000000}\n", (negative / arr.Count)) + string.Format("{0.0.000000}",zero/arr.Count));
}

}

class Solution
{
public static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine().Trim());

List<int> arr = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(arrTemp => Convert.ToInt32(arrTemp)).ToList();

Result.plusMinus(arr);
}
}
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Result
{

/*
* Complete the 'plusMinus' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/

public static void plusMinus(List<int> arr)
{
int positive = 0;
int negative = 0;
int zero = 0;

for (int i = 0; i > arr.Count; i++)
{
if (arr[i] < 0)
{
negative++;
}
else if (arr[i] > 0)
{
positive++;
}
else if (arr[i] == 0)
{
zero++;
}

}
Console.WriteLine(string.Format("{0.0.000000}\n", (positive / arr.Count)) + string.Format("{0.0.000000}\n", (negative / arr.Count)) + string.Format("{0.0.000000}",zero/arr.Count));
}

}

class Solution
{
public static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine().Trim());

List<int> arr = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(arrTemp => Convert.ToInt32(arrTemp)).ToList();

Result.plusMinus(arr);
}
}
I made this algorithm that is supposed to receive an input and gather all the negative numbers into one variable and positive variables into another. in then divided it by the number of items in the given list.
73 Replies
shawski.
shawski.OP2y ago
This error was thrown however
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Text.ValueStringBuilder.ThrowFormatError()
at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object arg0)
at Result.plusMinus(List`1 arr) in /tmp/submission/20221204/23/03/hackerrank-12ebdeb1541a3d3b298eaa5a029f1ef7/code/Solution.cs:line 46
at Solution.Main(String[] args) in /tmp/submission/20221204/23/03/hackerrank-12ebdeb1541a3d3b298eaa5a029f1ef7/code/Solution.cs:line 59
Aborted (core dumped)
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Text.ValueStringBuilder.ThrowFormatError()
at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object arg0)
at Result.plusMinus(List`1 arr) in /tmp/submission/20221204/23/03/hackerrank-12ebdeb1541a3d3b298eaa5a029f1ef7/code/Solution.cs:line 46
at Solution.Main(String[] args) in /tmp/submission/20221204/23/03/hackerrank-12ebdeb1541a3d3b298eaa5a029f1ef7/code/Solution.cs:line 59
Aborted (core dumped)
for example
6
-4 3 -9 0 4 1
6
-4 3 -9 0 4 1
if given an input like this
0.500000
0.333333
0.166667
0.500000
0.333333
0.166667
It should print this
Angius
Angius2y ago
Use $tryparse
MODiX
MODiX2y ago
The TryParse pattern is considered best practice of parsing data from a string: - a TryParse method returns true or false to inform you if it succeeded or not, so you can use it directly in a condition, - since C# 7 you can declare a variable that will be used as an out argument inline in an argument list, - it forces you to check if the out argument contains valid data afterwards, Avoid: Convert.ToInt32 — it's a bad choice for parsing an int. It exists only for backwards compatibility reasons and should be considered last resort.
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
(Note: Convert does contain useful conversion methods: To/FromBase64String, To/FromHexString, ToString(X value, int toBase), ToX(string? value, int fromBase)) Avoid: int.Parse — you have to use a try/catch statement to handle invalid input, which is a less clean solution.
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
Use int.TryParse https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
Int32.TryParse Method (System)
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.
Angius
Angius2y ago
Convert.ToWhatever() throws whatever.TryParse() doesn't, just returns false Also, run the debugger to see what exactly causes this error
shawski.
shawski.OP2y ago
alright
Angius
Angius2y ago
Some of the things you're trying to parse to an integer, isn't a valid integer
shawski.
shawski.OP2y ago
theres a couple things i should say so the main method wasnt written by me i am solving a problem and that's just how it was im only editing the plusMinus method
Angius
Angius2y ago
Cool cool The answer remains
shawski.
shawski.OP2y ago
wait then wdym dont use Int.Parse or Convert.ToInt32?
Angius
Angius2y ago
Angius
Angius2y ago
Line 46 That's where the issue is
shawski.
shawski.OP2y ago
Console.WriteLine(string.Format("{0.0.000000}\n", (positive / arr.Count)) + string.Format("{0.0.000000}\n", (negative / arr.Count)) + string.Format("{0.0.000000}", zero / arr.Count)));
Console.WriteLine(string.Format("{0.0.000000}\n", (positive / arr.Count)) + string.Format("{0.0.000000}\n", (negative / arr.Count)) + string.Format("{0.0.000000}", zero / arr.Count)));
thats line 46
Angius
Angius2y ago
uh
int.Parse(
string.Format("{0.0.000000}\n", (positive / arr.Count)) + string.Format("{0.0.000000}\n", (negative / arr.Count)) + string.Format("{0.0.000000}", zero / arr.Count)
)
int.Parse(
string.Format("{0.0.000000}\n", (positive / arr.Count)) + string.Format("{0.0.000000}\n", (negative / arr.Count)) + string.Format("{0.0.000000}", zero / arr.Count)
)
Yeah Well The result of appending those three formatted strings will never in a million years be a valid integer It has dots, it has new lines, it has all sorts of things What looks like
8.93712
9.12342
0.11982
8.93712
9.12342
0.11982
is as far removed from being an integer as something vaguely numeric can possibly be
shawski.
shawski.OP2y ago
yes
Angius
Angius2y ago
Why do you even want to parse it to an integer? It doesn't seem necessary
shawski.
shawski.OP2y ago
i wasnt trying to. i sent u the code where i had that there
Angius
Angius2y ago
?
shawski.
shawski.OP2y ago
refer to the code i sent in the description of this post as the most up to date one
Angius
Angius2y ago
So... why did you say line 46 has the int.Parse() in it..? If the most recent code doesn't..?
shawski.
shawski.OP2y ago
im not sure. i put it by accident i think
Angius
Angius2y ago
So line 46, even without int.Parse(), still throws the format error?
shawski.
shawski.OP2y ago
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Text.ValueStringBuilder.ThrowFormatError()
at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object arg0)
at Result.plusMinus(List`1 arr) in /tmp/submission/20221204/23/30/hackerrank-a170d9b68469cb16ffbb9fd7bfb6de66/code/Solution.cs:line 46
at Solution.Main(String[] args) in /tmp/submission/20221204/23/30/hackerrank-a170d9b68469cb16ffbb9fd7bfb6de66/code/Solution.cs:line 59
Aborted (core dumped)
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Text.ValueStringBuilder.ThrowFormatError()
at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object arg0)
at Result.plusMinus(List`1 arr) in /tmp/submission/20221204/23/30/hackerrank-a170d9b68469cb16ffbb9fd7bfb6de66/code/Solution.cs:line 46
at Solution.Main(String[] args) in /tmp/submission/20221204/23/30/hackerrank-a170d9b68469cb16ffbb9fd7bfb6de66/code/Solution.cs:line 59
Aborted (core dumped)
error with int.Parse removed
Angius
Angius2y ago
Ah, I see what the issue is I didn't see it initially because I never use string.Format() since string interpolation exists "{0.0.000000}\n" should be "{0:0.000000}\n"
shawski.
shawski.OP2y ago
do you suggest i use string interpolation instead?
Angius
Angius2y ago
Yes
shawski.
shawski.OP2y ago
im not sure how to do it with that oh thats what i messed up on. ty i kind of was doing that from mostly memory
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
var num = 8.824;
Console.WriteLine(string.Format("Number {0:0.00000}", num));
Console.WriteLine($"Number {num:0.00000}");
var num = 8.824;
Console.WriteLine(string.Format("Number {0:0.00000}", num));
Console.WriteLine($"Number {num:0.00000}");
Console Output
Number 8.82400
Number 8.82400
Number 8.82400
Number 8.82400
Compile: 590.156ms | Execution: 74.727ms | React with ❌ to remove this embed.
Angius
Angius2y ago
Here's how to achieve the same with string interpolation
shawski.
shawski.OP2y ago
holy that is soo much more clean
shawski.
shawski.OP2y ago
why did it return all 0s?
shawski.
shawski.OP2y ago
int positive = 0;
int negative = 0;
int zero = 0;

for (int i = 0; i > arr.Count; i++)
{
if (arr[i] < 0)
{
negative++;
}
else if (arr[i] > 0)
{
positive++;
}
else if (arr[i] == 0)
{
zero++;
}
}
int positive = 0;
int negative = 0;
int zero = 0;

for (int i = 0; i > arr.Count; i++)
{
if (arr[i] < 0)
{
negative++;
}
else if (arr[i] > 0)
{
positive++;
}
else if (arr[i] == 0)
{
zero++;
}
}
i loop over all the elements to get how many positives, negatives, and 0s there are
Angius
Angius2y ago
What's your string? Seems something wrong with the output string, not with the values Although you can, of course, make sure by using the debugger
shawski.
shawski.OP2y ago
Console.WriteLine(string.Format("{0:0.000000}\n", (positive / arr.Count))
Console.WriteLine(string.Format("{0:0.000000}\n", (positive / arr.Count))
this is how i calculate the output for positive numbres
Angius
Angius2y ago
Ah, so you didn't use string interpolation
shawski.
shawski.OP2y ago
not yet
Angius
Angius2y ago
I thought that might've been the issue
shawski.
shawski.OP2y ago
ill change it to that rn
Angius
Angius2y ago
Ah, I know why Integer division Cast one of the operands to a double (double)positive / arr.Count for example
shawski.
shawski.OP2y ago
alright
Console.WriteLine($"{(double)positive / arr.Count:0.000000}"
Console.WriteLine($"{(double)positive / arr.Count:0.000000}"
it prints "0.000000"
Angius
Angius2y ago
Try
Console.WriteLine($"{((double)positive / arr.Count):0.000000}"
Console.WriteLine($"{((double)positive / arr.Count):0.000000}"
or
Console.WriteLine($"{((double)positive) / arr.Count:0.000000}"
Console.WriteLine($"{((double)positive) / arr.Count:0.000000}"
or
Console.WriteLine($"{(double)positive / (double)arr.Count:0.000000}"
Console.WriteLine($"{(double)positive / (double)arr.Count:0.000000}"
or
Console.WriteLine($"{((double)positive / (double)arr.Count):0.000000}"
Console.WriteLine($"{((double)positive / (double)arr.Count):0.000000}"
Some parentheses here and there might help
shawski.
shawski.OP2y ago
tried those all same result
Angius
Angius2y ago
Huh
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
int a = 1;
int b = 9;
($"{(double)a / b:0.000000}", $"{a / (double)b:0.000000}")
int a = 1;
int b = 9;
($"{(double)a / b:0.000000}", $"{a / (double)b:0.000000}")
Result: ValueTuple<string, string>
{
"item1": "0.111111",
"item2": "0.111111"
}
{
"item1": "0.111111",
"item2": "0.111111"
}
Compile: 523.124ms | Execution: 48.761ms | React with ❌ to remove this embed.
Angius
Angius2y ago
It should work just fine
shawski.
shawski.OP2y ago
yeah i would think so. im not sure where i messed up.
Angius
Angius2y ago
I guess you could try pulling that (double)positive / arr.Count to a variable and using the debugger to check what the value is
shawski.
shawski.OP2y ago
alr
Angius
Angius2y ago
Maybe it's so small that 6 decimal places is not enough to show anything
shawski.
shawski.OP2y ago
i might need a little break. been going at this for a while. my brain is tired.
Angius
Angius2y ago
Yeah, get a break, drink some water, come back to it when you feel like it
shawski.
shawski.OP2y ago
alright thank you for helping me
shawski.
shawski.OP2y ago
shawski.
shawski.OP2y ago
i did some debugging i just made a list to test this code there are 2 positive numbers and 1 zero i made a break point when it reaches line 41, positive = 0 how does that make sense positive should be 2 in this case @Angius i think thats been my problem this whole time although i cant see a reason why it would be 0
Angius
Angius2y ago
That does seem super weird indeed I'd probably start by turning that for loop into a foreach, just to make sure it's not an issue Doesn't seem to be and probably isn't But it's best to get rid of as many moving parts as possible
shawski.
shawski.OP2y ago
alright i dont think ive ever used a foreach let me figure it out gimme a sec
Angius
Angius2y ago
Let's you avoid the issue that @Box⸬læk⸬<'static>(Box⸬new(Aaron⸩ pointed out, with
shawski.
shawski.OP2y ago
turning that into a less than seemed to fix it i thought it was a greater than tho i guess i just forgot the syntax a little..
Angius
Angius2y ago
Loop runs as long as that condition is true It's a run condition, not a stop condition Also, foreach just does that all for you lol
shawski.
shawski.OP2y ago
should i use foreach rather than a for loop when i can? im more familiar with for loops
Angius
Angius2y ago
Foreach is much easier to use Use whatever suits you, through, and learn as you go
shawski.
shawski.OP2y ago
all my tests pass after changing the greater than symbol to less than in the for loop :/ such a little thing i missed that took me this long.. im gonna try to replicate this with a foreach and see which one i like more
Angius
Angius2y ago
It's always the little things lol
shawski.
shawski.OP2y ago
shawski.
shawski.OP2y ago
i figured foreach out pretty quick that seems much easier are there cases where one is objectively better than the other?
Angius
Angius2y ago
Pretty much always foreach Unless you need the index, then for
shawski.
shawski.OP2y ago
the index? yeah the tests all passed with the foreach. wow that was a lot cleaner
Angius
Angius2y ago
The number of the element in the collection
shawski.
shawski.OP2y ago
oh yeah is there an alternative to all those if statements?
Angius
Angius2y ago
I'd probably use a switch expression That said, I'm on mobile now, so it'd be hard to write it out lol I'll let you do some googling, and if nothing comes up, I'll write the code up when I'm at my PC again
shawski.
shawski.OP2y ago
alright
Angius
Angius2y ago
Ah, no, wait, a switch expression probably won't work here... unless we get fancy with tuple deconstruction Those ifs are prolly your best bet Easiest to understand and work just fine I'd maybe turn the last else if into just an else
shawski.
shawski.OP2y ago
yeah i was about to say i have no idea how im gonna use a switch here lol good point. not sure why i had it typed like that. @Angius is there a method that i can utilize to round to the nearest 5? here actually imma close this. im done with that problem. ill open a new one if i need help with something else
Accord
Accord2y ago
Closed!
Want results from more Discord servers?
Add your server