Build Error with no Logical/Syntax Errors - c#

I was beginning to create a command line program that allowed me to complete problem 4 on Project Euler.
https://projecteuler.net/problem=4
While I was in the middle of scripting the program, I decided to debug (I'm using Visual Studio Suite 2015)
When it began, it had a message pop up and show that the program itself has "Build Errors."
I have absolutely no idea what happened.
In the version below (C#), the script has no logical errors, and it has no syntax errors either.
Could you please tell me what's wrong with it?
Thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem_4
{
class Program
{
static void Main(string[] args)
{
//Check Palindrome
//Not complete code.
int originalValue = 9009;
int oppositeValue = 0; ;
int carryOppositeValue;
int placeValue = 0;
bool completedCycle = false;
int numCycles = 0;
int numCycles2 = 0;
int[] array = { 0 };
for(placeValue = numCycles; completedCycle; placeValue++)
{
array[placeValue] = originalValue % 10;
originalValue = originalValue / 10;
if(originalValue >= 0)
{
numCycles++;
} else
{
completedCycle = true;
Console.WriteLine("The number has " + numCycles + "Place Values");
}
}
for(placeValue = 0; placeValue < 50; placeValue += 10)
{
if (numCycles2 == 0)
{
oppositeValue = array[0];
}
else
{
carryOppositeValue = placeValue * array[placeValue / 10];
oppositeValue += carryOppositeValue;
}
}
}
}
}

I compiled this code and got no errors. I would suggest doing a build/clean.
If that doesn't work I would delete the bin and obj folders then recompile.

Related

Why my C# Code isn't Printing the Required Output

I attempting to create a program that uses multiple methods that would print out base numbers, exponents, and their resulting solutions. I am trying to get it to run and it's nearly completed, but I am encountering a couple issues. The code itself seems to run, but doesn't appear to print out on Visual Studio. I did run it on an online compiler and got this as an output:
It seems I am missing something in my code, but I am unclear as to what I may be missing. This is the code I have created for the project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Program
{
static void Main(string[] args)
{
//Our initialized variables.
int intMinBase = 1;
int intMaxBase = 100;
int intMinExpo = 1;
int intMaxExpo = 10;
//Our arrays for the project, all at a length of 5.
long[] baseNumbers = new long[5];
long[] exponents = new long[5];
long[] results = new long[5];
//Randomize the baseNumbers and exponents!
Random randInt = new Random();
for (long i = 0; i < 5; i++)
{
baseNumbers[i] = randInt.Next(intMinBase, intMaxBase);
exponents[i] = randInt.Next(intMinExpo, intMaxExpo);
}
PrintArrays(baseNumbers, exponents, results);
}
//This is potentially experimental code for the Power Method.
public static int Power(int baseNum, int exponent)
{
int answer;
if (exponent == 1)
{
answer = 1;
}
else
{
answer = baseNum * Power(baseNum, exponent - 1);
}
return answer;
}
//The new method to be printed. Is this the correct manner to display this?
public static void PrintArrays(long[] baseNum, long[] exponent, long[] result)
{
Console.WriteLine($"Base\tExponent\tResult");
for (int print = 0; print < result.GetUpperBound(0); print++)
{
Console.WriteLine(baseNum[print]+"\t"+exponent[print]+"\t"+result[print]);
}
}
}
}
My question is mainly am I missing something and why isn't it appearing to print in Visual Studio yet it's appearing on an online compiler? I suspect the answer to the first part of the question has to do with the methods I used, but I am unsure.
First error: Nowhere is the method Power called and nowhere is the array results filled.
Solution example:
for (long i = 0; i < 5; i++)
{
baseNumbers[i] = randInt.Next(intMinBase, intMaxBase);
exponents[i] = randInt.Next(intMinExpo, intMaxExpo);
results[i] = Power(baseNumbers[i], exponents[i]);
}

I need to find all the peaks and valleys in a list of data points using c#

This is my entire program. I have been working on this project for a week now and I am simply stuck. I have managed to read the CSV file and put the information in two lists that I then converted into arrays. Now I don't HAVE to do it like this. It's just simply what I managed to write and work and make sense in my head. This is where I've managed to get to and where I'm stuck. All I need is to be able to parse out ALL the peaks, or maximums, and valleys, or minimums, from the data points, and display them. If I can get that to happen then I can finally be done with this program. Any help and suggestions, code, anything like that would greatly appreciate. Like I said if you have a better formula that I can plug in and use without hard-coding points (because there's over 2000 of them) and display the outcome in a listbox or something then that would make my day. Thank y, everyone,ne in advance
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
double firstX, firstY, secondX, secondY, thirdX, thirdY, rw, cl = 0.0;
int count = 0;
string x = "";
string y = "";
byte MinMax = 0; //0 equals rising, 1 equals falling
double Max = new Array[];
//double Min = new Array[];
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (var reader = new StreamReader(#"D:\data.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listB.Add(values[1]);
string[] xPoints = listA.ToArray();
string[] yPoints = listB.ToArray();
while (yPoints.Last() != null)
{
if (Convert.ToDouble(yPoints.First()) == 0.0)
{
firstY = Convert.ToDouble(yPoints.First());
}
if (Convert.ToDouble(yPoints.First()) != 0.0 && secondY == 0.0)
{
secondY = Convert.ToDouble(yPoints.Last());
if (secondY > firstY)
{
MinMax = 0;
}
else
{
MinMax = 1;
}
}
if (secondY != 0.0 && thirdY == 0.0)
{
thirdY = Convert.ToDouble(yPoints.Last());
if (MinMax == 0 && thirdY > secondY)
{
firstY = secondY;
secondY = thirdY;
}
else
{
Max[count,0] = secondY;
}
}
}
listBox1.Items.Add(values[0]);
listBox2.Items.Add(values[1]);
}
}
}
}
}
This snippet will get valleys and peaks on an array of y values, ignoring [0]
public void GetValleysAndPeaks(double[] yValues, out List<int> peakIndexes, out List<int> valleyIndexes)
{
peakIndexes = new List<int>();
valleyIndexes = new List<int>();
bool directionUp = yValues[0] <= yValues[1];
for(int i = 1; i < yValues.Length - 1; i++)
{
if(directionUp && yValues[i + 1] < yValues[i])
{
peakIndexes.Add(i);
directionUp = false;
}
else if(!directionUp && yValues[i + 1] > yValues[i])
{
valleyIndexes.Add(i);
directionUp = true;
}
}
}

Kattis phonelist issue

Once I run the following local, it is woking fast, but when I submit it to Kattis, It only exceeds 2/5 and I get Time Limit Exceeded.
Any suggestion?
I have tried with a input file with 10000 numbers and it is still fast localy :S
using System;
namespace phonelist
{
class Program
{
static void Main(string[] args)
{
int nrOfPhoneNrs = 0;
bool consistent;
int nrOfTestCases = Convert.ToInt32(Console.ReadLine().Trim());
for (byte i = 0; i < nrOfTestCases; i++)
{
consistent = false;
nrOfPhoneNrs = Convert.ToInt32(Console.ReadLine().Trim());
string[] phList = new string[nrOfPhoneNrs];
int n = 0;
while (n < nrOfPhoneNrs)
{
phList[n] = Console.ReadLine();
n++;
}
Array.Sort(phList);
int runs = nrOfPhoneNrs - 1;
for (int p = 0; p < runs; p++)
{
if (phList[p + 1].StartsWith(phList[p]))
{
consistent= true;
break;
}
}
Console.WriteLine(consistent? "NO" : "YES");
}
}
}
}
I think that your main problem is that you're using StartsWith and Array.Sort methods.
I don't want to give you too detailed advice (so that you can still solve it by yourself) but let me just suggest considering a different data structure than an array of strings, perhaps HashSet<string>.

Port Selection and Batch Runner Application

I have never written an application, so I will post the entirety of the code (80 lines). (I come from a background of putting together scripts.)
My goal is to load, or create a list of "used" ports, choose a number within a range that isn't on the list, and if the amount of tries to reach an unused port reaches 129, to run a windows batch file.
This also would turn the chosen port into a .cmd
(some of this is an amalgamation of sources from SO)
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.IO;
namespace randomport
{
class Core
{
public const int
minval = 8001,
maxval = 8128;
public static int[] usedPorts = new int[]{};
public static int
chosenPort = 0,
tries = 0,
timeout = 10;
public static bool read = false;
public static void Main()
{
if(!read)
{
Read();
read = true;
}
RandGen();
}
public static void RandGen()
{
Process proc = null;
Random rand = new Random();
if(tries < 129) chosenPort = rand.Next(minval, maxval);
else
{
proc.StartInfo.FileName = #"C:\Users\Administrator\Desktop\TerrariaServer\filebin\sendservfull.bat";
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : timeout * 100 * 60
);
}
for(int i = 0; i < usedPorts.Length; i++)
{
if(chosenPort != usedPorts[i])
{
Write();
// Application.Exit();
}
else
{
tries += 1;
return;
}
}
}
public static void Read()
{
using (StreamReader sr = new StreamReader(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt"))
{
string[] values = sr.ReadToEnd().Split(';');
for(int i = 0; i < values.Length; i++)
{
int.TryParse(values[i], out usedPorts[i]);
}
}
}
public static void Write()
{
File.AppendAllText(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt", "set port="+chosenPort+";");
File.Move(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt", Path.ChangeExtension(#"C:\Users\Administrator\Desktop\TerrariaServer\filebin\activeports.txt", ".cmd"));
}
}
}
I have a little work to do on the final export (like removing ";").
The script compiles, but does not run as intended. Something is definitely wrong, but I am unaware of it. If it is something obvious, I guess that would be handy, otherwise if it is simply format and so on, I clearly need to do a little more studying.
Compiled using visual studio 2008 express this time, and cleaned it up. It was hard to tell which were the issues without a debugger, such as a missing parenthesis.
File writing, compiling, and crashing solved..
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.IO;
namespace randomport
{
class Core
{
public static int[] usedPorts = new int[] { };
public static int
minval = 8001,
maxval = 8129,
chosenPort = 0,
timeout = 10,
temp = 1024;
public static bool read = false;
public static void Main(string[] args)
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
if (!Directory.Exists(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt")))
{
Directory.CreateDirectory(String.Concat(path, "\\desktop\\TerrariaServer\\filebin"));
// using (StreamWriter sw = File.CreateText(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt"))) { }
}
if (!Directory.Exists(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\chosenport.cmd")))
{
Directory.CreateDirectory(String.Concat(path, "\\desktop\\TerrariaServer\\filebin"));
using (StreamWriter sw = File.CreateText(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\chosenport.cmd"))) { }
}
if (args.Length > 0)
{
if (args[0] == "-noread")
{
}
else if (args[0] == "-read" || args[0] == "-default")
{
if (!read)
{
Read();
read = true;
}
}
}
else
{
if (!read)
{
Read();
read = true;
}
}
if (args.Length >= 3)
{
if (args[1] != "-default" || args[1] != "0")
{
int.TryParse(args[1], out temp);
if (temp > 1024 && temp < 65535)
{
minval = temp;
}
}
if (args[2] != "-default" || args[2] != "0")
{
int.TryParse(args[2], out temp);
if (temp > 1024 && temp < 65535)
{
maxval = temp;
}
}
}
RandGen();
}
public static void RandGen()
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
Random rand = new Random();
chosenPort = rand.Next(minval, maxval);
for (int i = 0; i < usedPorts.Length; i++)
{
if (chosenPort != usedPorts[i])
{
Write();
}
else return;
}
}
public static void Read()
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
if (!File.Exists(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt")))
{
File.Create(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt"));
}
using (StreamReader sr = new StreamReader(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt")))
{
string[] values = sr.ReadToEnd().Split(';');
usedPorts = new int[values.Length];//Initialize the array with the same length as values
for (int i = 0; i < values.Length; i++)
{
int.TryParse(values[i], out usedPorts[i]);
}
}
}
public static void Write()
{
string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
File.AppendAllLines(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\activeports.txt"), new string[] { chosenPort + ";" });
using (StreamWriter sw2 = File.CreateText(String.Concat(path, "\\desktop\\TerrariaServer\\filebin\\chosenport.cmd")))
{
sw2.WriteLine("set port=" + chosenPort);
}
Environment.Exit(0);
}
}
}

Having trouble getting past NullReferenceException [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I'm a newbie in programming, especially in c#. I have written some code but I keep getting an error when running it and I can't move on until I get that fixed.
The error in question is a NullReferenceException. It also tells me "Object reference not set to an instance of an object".
It seems like a pretty clear error message indicating that an object hasn't been instantiated yet. However I thought I had done that. I hope someone can explain to me what I'm doing wrong. Here's my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace EvenHelemaalOvernieuw
{
class Globals
{
public static int size = 50;
public static int factor = 3;
public static int puzzleNumber = 1;
public static Square[,] allSquares = new Square[Globals.factor * Globals.factor, Globals.factor * Globals.factor];
public static String path = #"" + factor.ToString() + "\\" + puzzleNumber.ToString() + ".txt";
public static int[,][,] values = new int[factor, factor][,];
public Globals() { }
public void setSize(int s)
{
size = s;
if (size > 100)
{
size = 100;
}
if (size < 20)
{
size = 20;
}
}
public void setFactor(int f)
{
factor = f;
if (factor > 5)
{
factor = 5;
}
if (factor < 2)
{
factor = 2;
}
}
public Square getSquare(int x, int y)
{
return allSquares[x, y];
}
public static void readPuzzle()
{
List<int> conversion = new List<int>();
int count = 0;
using (StreamReader codeString = new StreamReader(path))
{
String line = codeString.ReadToEnd();
Array characters = line.ToCharArray();
foreach (char a in characters)
{
if (a.ToString() != ",")
{
conversion.Add(Convert.ToInt32(a));
}
}
for (int panelX = 0; panelX < factor; panelX++)
{
for (int panelY = 0; panelY < factor; panelY++)
{
for (int squareX = 0; squareX < factor; squareX++)
{
for (int squareY = 0; squareY < factor; squareY++)
{
values[panelX, panelY][squareX, squareY] = conversion[count];
count++;
}
}
}
}
}
}
}
}
The line that is indicated by the error message is near the bottom and reads values[panelX, panelY][squareX, squareY] = conversion[count];.
The problem is the following line
public static int[,][,] values = new int[factor, factor][,];
This is an array of arrays but this code only creates the outer array. The inner array is uninitialized and will be null. Hence when the following code runs it will throw a NullReferenceException trying to access the inner array
values[panelX, panelY][squareX, squareY] = conversion[count];
To fix this just initialize the array elements right before the 3rd nested loop
values[panelX, panelY] = new int[factor, factor];
for (int squareX = 0; squareX < factor; squareX++)

Categories