Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How to input in C#? and using loop on that input.
Here is my code so far i trying
static void Main(string[] args)
{
int[] ar = new int[10002];
int n = Convert.ToInt32( Console.ReadLine() );
for( int i = 0;i < n; i++ )
{
ar[i] = Convert.ToInt32( Console.ReadLine() );
}
for ( int i = 0; i < n; i++ )
{
Console.WriteLine(ar[i]);
}
Console.ReadKey();
}
Here is a simple example of two ways of handling the invalid input in your case. One thing you can do, is just fail giving the user an information that the input was not correct. Second possibility is to treat invalid input as a null value.
This is just a simple example - usually you shouldn't fail silently (here: return a null and not complain), and you shouldn't use null values as an indicator for a special function return value. Also a good example would be not to finish the program but use a loop to ask the user repeatedly until they learn how a number looks like ;)
These all issues are left unsolved as a practice for the reader ;)
static int? ReadInteger()
{
int result;
if (!int.TryParse(Console.ReadLine(), out result))
{
return null;
}
return result;
}
static void Main(string[] args)
{
int?[] ar = new int?[10002];
int? n = ReadInteger();
if (!n.HasValue)
{
Console.WriteLine("Please input a correct integer");
return;
}
for( int i = 0;i < n.Value; i++ )
{
ar[i] = ReadInteger();
}
for ( int i = 0; i < n.Value; i++ )
{
Console.WriteLine(ar[i].HasValue
? ar[i].Value.ToString() : "Incorrect input");
}
Console.ReadKey();
}
I tried to build this as close as possible to your implementation. The other answer from BartoszKP should be used in a complete scenario.
static void Main(string[] args)
{
int[] ar = new int[10002];
int n;
if (int.TryParse(Console.ReadLine(), out n))
{
int nr;
for (int i = 0; i < n; i++)
{
if (int.TryParse(Console.ReadLine(), out nr))
{
ar[i] = nr;
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(ar[i]);
}
}
Console.ReadKey();
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For a given number n, I need to return all powers of 2 less than n, as a string in a way that elements are separated with "-". If n < 2, it needs to return an empty string.
For example:
n = 20 => 1-2-4-8-16
n = 8 => 1-2-4
I'm a beginner, so any help would be much appreciated! :)
EDIT: this is not working
using System;
class N
{
static int[] powerof2(int n)
{
int[] array = new int[n];
if (n < 2)
return new int[0];
for (int i = 0; i < 8 * sizeof(uint); i++)
{
int curr = 1 << i;
if (curr > n)
break;
array[i] = curr;
}
return array;
public override string ToString()
{
for (int i = 0; i < array.length; i++)
return (array[i] + "-");
}
}
static public void Main ()
{
int n = 10;
Console.WriteLine(powerof2(n).ToString());
}
}
You need to run the for loop with the following rule
for (int i = 1; i < n; i *= 2)
Whole solution
class Program
{
static void powerof2(int n)
{
if (n < 2)
Console.WriteLine(string.Empty);
for (int i = 1; i < n; i *= 2)
{
if (i > 1)
Console.Write("-");
Console.Write(i);
}
}
static void Main(string[] args)
{
powerof2(20);
}
Using iterator methods makes this case trivial (Fiddle):
using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int> GetPowersOf2(int maxN)
{
for (int p = 1; p < maxN; p *= 2)
{
yield return p;
}
}
public static void Main(string[] args)
{
IEnumerable<int> powersOf2LessThan20 = GetPowersOf2(20);
Console.WriteLine(string.Join("-", powersOf2LessThan20));
}
}
I suppose this is what you're looking for:
class Program
{
public static string Pow2LessThan(ulong n)
{
if (n < 2)
return "";
// start with 2^0
string res = "1";
// try further
int p = 1;
ulong cnum = 2;
while (cnum < n)
{
res += "-" + cnum.ToString();
++p;
cnum = (ulong)(1 << p);
}
return res;
}
static void Main(string[] args)
{
ulong n = 20;
Console.WriteLine(Pow2LessThan(n));
Console.ReadLine();
}
}
The reason that it's not working is: you never access the class N in any way. The call should be
Console.WriteLine(N.powerof2(n).ToString());
^^
With that modification, you'll be notified that the method powerof2() is inaccessible due to its protection level. You need to make it at least internal like so:
internal static int[] powerof2(int n)
Next, note that you're missing a } for that method.
return array;
}
With that fixed, the compiler will tell you that you can't access array inside ToString(), because the scope of array is limited to powerof2(). Make the array a field of the class like
static int[] array;
Now, the compiler complains about array.length in ToString(). Fix that by capitalizing Length.
Mistake number 6: ToString() will return in the first iteration of the loop. It will not return anything if array.Length is 0. The function should look a little bit like this:
public override string ToString()
{
string result = "";
for (int i = 0; i < array.Length; i++)
result += array[i] + "-";
return result;
}
Now, this will still not work, because the main method calls ToString() on the return value of powerof2(), which is of type int[] and not of type N. That's because your stuff is static. Make it non-static instead and create an instance of N.
static public void Main ()
{
var n = new N();
n.powerof2(10);
Console.WriteLine(n.ToString());
}
With 7 issues fixed, the output is now 1-2-4-8-0-0-0-0-0-0-, so there's still stuff to fix. Maybe you get a little bit of a feeling why everyone proposes a totally different solution.
What else to fix:
the output of course is still incorrect.
if someone inputs 4000000000 as the number, you certainly don't want to allocate 4 GB of RAM in the array.
Why allocate an array at all and not construct the string right away?
Why 8*sizeof(uint)? You can't shift more often than sizeof(uint).
class Program
{
static string powerof2(int n)
{
var str="1" ;
if (n < 2)
return "" ;
else
{
var i=1;
while(Math.Pow(i, 2)<n)
{
str+="-" +Math.Pow(2, i);
i++;
}
return str;
}
}
static void Main(string[] args)
{
powerof2(50);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am making a program that will a number of dice a number of times. I have made a method called 'RollDice'. the method works until the for loop. It returns to the main method after I type 'roll' in the console and i don't know why it won't execute the script in side the for loop. I have marked place where the code stops working. any help would be much appreciated, thanks!
using System;
using System.Collections.Generic;
namespace Dice Roller
{
class Program
{
public static void Main(string[] args)
{
int nos = 6;
int nod = 1;
int nor = 1;
string OP;
int x = 1;
while (x == 1)
{
Console.WriteLine("Random Dice Macine");
Console.WriteLine("Type 'edit' To Edit Dice Settings");
Console.WriteLine("Type 'clear' To Clear The Screan");
Console.WriteLine("Type 'exit' To Close The Aplication");
Console.WriteLine("Type 'roll' to Roll The Dice");
Console.Write("-> ");
OP = Console.ReadLine();
if (OP == "exit")
{
Environment.Exit(0);
}
else if (OP == "edit")
{
Console.Clear();
Console.WriteLine("Number Of Sides On The Dice");
Console.Write("->");
nos = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number Of Dice");
Console.Write("->");
nod = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number Of Roles");
Console.Write("->");
nor = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Setup Compleat! Press Space To Continue.");
Console.ReadKey();
Console.Clear();
}
else if (OP == "clear")
{
Console.Clear();
}
else if (OP == "roll")
{
RollDice(nor, nos, nod);
}
}
}
public static void RollDice(int nor, int nos, int nod)
{ //Code Works Here
Random gen = new Random();
List<int> numbers = new List<int>();
for (int n = 1; n < nod; n++)
{
for (int i = 1; i < nor; i++)
{ //But Not Here
numbers.Add(gen.Next(1, nos));
}
foreach (int element in numbers)
{
Console.Write(element + ", ");
}
numbers.Clear();
}
}
}
}
In for-loops the counter should start from 0 and not from 1. In your case nor and nod are equal to 1. That is why the loops are never executed.
Only thing I can see is that if nod or nor is 1 when the program reaches the for loops, the condition to end the loop is already met. Use '<=' instead in the ebd condition.
On line
for (int n = 1; n < nod; n++)
nod is 1, and n < nod check is termination for loop.
Either set i = 0 or set check n <= nod.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to make a prime number generator.
I get three errors:
<21,22> expected >
<21,23> expression > is invalid
<21,24> expected ;
translated errors from norwegian. they may not be exact
using System;
namespace Primtall
{
class Program
{
static void Main(string[] args)
{
Generator G = new Generator();
G.gen();
}
}
public class Generator
{
int a = 0;
int divident = 0;
public void gen()
{
for (a; a<100; a++;)
{
for (divident; divident <= 50;divident++)
{
int div = a/divident;
if((div % 1) == 0)
{
Console.WriteLine(a);
}
else
{
break;
}
}
}
}
}
}
There is no need to define a and divident variables as fields. You make no use of them except in the loop. In fact, using class members (fields) as loop variables will immediately render your class as "not thread safe", becuase if two seperate threads execute the gen() method on the same Generator instance they will both fail to get correct results
Change your Generator class like this: (divident starting from 1 to avoid divide by zero exception)
public class Generator
{
public void gen()
{
for (int a = 0; a < 100; a++)
{
for (int divident = 1; divident <= 50; divident++)
{
int div = a / divident;
if ((div % 1) == 0)
{
Console.WriteLine(a);
}
else
{
break;
}
}
}
}
}
You declare variables before loops, so you must leave empty first argument in for:
for (; a < 100; a++)
{
for (; divident <= 50; divident++)
{
Or better declare loop variables in loop:
for (var a = 0; a < 100; a++)
{
for (var divident = 2; divident <= a / 2; divident++)
{
Also, you have some problems in algorithm:
int div = a/divident;
if((div % 1) == 0)
Should be replaced with:
if((a % divident) == 0)
{
flag = false;
break;
}
Declare flag in first loop as true and check it after second loop finish. If it's stil true - number is prime. Also, start second loop with 2 and end with a / 2
You seem to be misunderstanding how for loops work
for(Initialise; While; Action)
so in english what you are asking it to do is
for
a where a starts at 0
while a less than 100
perform body
then increment a by 1
this in code is
For(int a = 0;a<100;a++)
{
//body
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have 2 different classes
class TollGate
{
public void Check(int []numbers, int Token)
{
int i;
for (i = 0; i < numbers.Length; i++)
{
int s = numbers[i];
if ( Token > s)
{
Console.WriteLine("You Got To Wait");
return;//this works
}
else
{
Console.WriteLine("Hold On Printing a Pass\n\"Happy Trip\"");//this doesn't
return;
}
}
}
}
class Program
{
public static void Main()
{
int[] numbers = new int[5] {1, 2, 3, 4, 5};
Random rnd = new Random();
int r = rnd.Next(numbers.Length);
int Token = (numbers[r]);
Tollgate T = New TollGate();
T.Check(numbers, Token);
Console.WriteLine("Cool");
Console.WriteLine("Hot");
Console.WriteLine("Freezing");
}
}
Can't i use two return statements. How to make it just stop, by giving the message only once but it just goes along with the loop displaying it as many times as the loop.
This may be what you want:
public void Check(int[] numbers, int Token) {
for (int i = 0; i < numbers.Length; i++) {
if ( Token > numbers[i]) {
Console.WriteLine("You Got To Wait");
return;
}
}
}
public static void Main() {
int[] numbers = new int[] {1, 2};
int[] tokens = new int[] {1,2,3,4,5};
Random rnd = new Random();
int r = rnd.Next(tokens.Length);
int Token = (tokens[r]);
Tollgate T = new TollGate();
T.Check(numbers, Token);
}
Since the logic in your for is very hard to understan I tried to guess what you are trying to do
class Tollgate
{
public void Check(int []numbers, int Token)
{
int i;
//change this for to the actual logic that you need
//for (int numbers[i] = 0; numbers[i] < numbers.Length; numbers[i]++)
for (i = 0; i < numbers.Length; i++)
{
int s = numbers[i];
if ( Token > s)
{
Console.WriteLine("You Got To Wait");
}
else
{
//handle else logic
//if need to stop the loop when this condition is met, insert a "break;" (condition is Token <= s)
}
}
}
}
class That
{
public static void Main()
{
int[] numbers = {1, 2, 3, 4, 5};
Random rnd ;
int r ;
int Token ;
Tollgate T ;
rnd = new Random();
r = rnd.Next(numbers.Length);
Token = numbers[r];
T = new TollGate();
T.Check(numbers, Token);
}
}
As King King mentioned, you can add a return statement to the loop to stop the function at that point. If you want to exit the loop but not exit the function, add a continue statement instead of return. This jumps out of the loop, and is useful in real code, even though your example code is simple enough not to need it.
bool waiting = false;
if ( Token > numbers[i]) {
Console.WriteLine("You Got To Wait");
waiting = true;
break;
}
... // add any additional logic here. can check if(waiting)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to make a program , in which the number of layers for a container and their diameters are taken input from the user. Then the user inserts a disk of certain diameter into the program. Then the disks moves through all possible layers , the process can be repeated until the container is filled or user stops adding more disks to it. Finally the program is supposed to give total number of disks contained in the container and their layer numbers. Iam badly stuck and my mind is blank now. Kindly help!
[updated code] The problem remains that the container is never fills , program keeps on inserting disks. I cant think of a logical way to let it know when container is full.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Number of Layers ? ");
int layers = int.Parse(Console.ReadLine());
int[] container = new int[layers];
int disk_number = 0;
for (int i = 0; i < layers; i++)
{
Console.Write("\nLayer num {0} : ",1+i);
container[i] = int.Parse(Console.ReadLine());
}
Console.Write("\nPress 1 to Insert disk? ");
int insert = int.Parse(Console.ReadLine());
while (insert == 1)
{
Console.Write("\nDiameter of Disk? ");
int disk_diameter = int.Parse(Console.ReadLine());
if (disk_diameter <= container[0])
{
for (int i = 0; i < layers;) {
if (disk_diameter <= container[i])
{
i++;
}
else { if (i == layers - 1) break; layers = i+1; }
}
disk_number++;
Console.Write("\nPress 1 to Insert more disk(s)? ");
insert = int.Parse(Console.ReadLine());
if (insert != 1) { Console.Write("\nNumber of disks contained in container are : {0}", disk_number); }
}
else
{
Console.Write("\nDisc blocked the surface opening of the container , no further input could be processed! \nNumber of disks contained in container are : {0}",disk_number);
break;
}
}
Console.ReadLine();
}
//static int inserting_disk(int a);
}
}
You haven't explained me what you want exactly, but here goes a much improved (on different fronts) version of your code which, hopefully, you will take as a good learning exercise. The overall structure is pretty bad, but I have intended to emulate the one in your original code such that you can understand perfectly what is going on. The "input flow" is still pretty poor and thus might stop working easily (if the right inputs are not introduced) but, at least, I have replaced your Parse with TryParse accounting for different-type inputs (e.g., a string instead of an integer).
Test the code, see what it does. Get used to the new variables (I have renamed/redefined some of them because were too confusing in its original version) and build a code delivering exactly what you are after (and, ideally, properly written).
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Number of Layers ? ");
int input0 = 0;
bool right0 = int.TryParse(Console.ReadLine(), out input0);
if (right0 && input0 > 0)
{
int tot_layers = input0;
int[] maxDiamLayer = new int[tot_layers + 1]; //better maintain the indexing as displayed to the user: starting from 1
bool[] layerDone = new bool[tot_layers + 1]; //This boolean array will make sure that you don't use the same layer more than once
int disk_number = 0;
for (int i = 1; i <= tot_layers; i++)
{
Console.Write("\nIntroduce the maximum diameter for the layer num {0} : ", i);
maxDiamLayer[i] = int.Parse(Console.ReadLine());
}
Console.Write("\nPress 1 to Insert disk? ");
input0 = 0;
right0 = int.TryParse(Console.ReadLine(), out input0);
while (right0 && input0 == 1)
{
Console.Write("\nDiameter of Disk? ");
int input = 0;
bool right = int.TryParse(Console.ReadLine(), out input);
if (!right || input <= 0)
{
Console.Write("\nWrong Diameter. ");
continue;
}
int disk_diameter = input;
bool oneInserted = false;
for (int i = 1; i <= tot_layers; i++)
{
if (disk_diameter <= maxDiamLayer[i] && !layerDone[i])
{
layerDone[i] = true;
oneInserted = true;
disk_number++;
Console.Write("\nNumber of disks contained in container are : {0}", disk_number);
Console.Write("\nPress 1 to Insert more disk(s)? ");
int input2 = 0;
bool right2 = int.TryParse(Console.ReadLine(), out input2);
if (!right2 || input2 != 1 || disk_number >= tot_layers) break;
Console.Write("\nDiameter of Disk? ");
input = 0;
right = int.TryParse(Console.ReadLine(), out input);
if (!right || input <= 0)
{
Console.Write("\nWrong Diameter. ");
break;
}
disk_diameter = input;
}
}
if (disk_number >= tot_layers)
{
Console.Write("\nAll the layers are filled");
break;
}
else
{
Console.Write("\nWrong diameter. Try again.");
}
if (!oneInserted)
{
Console.Write("\nThe disk couldn't be inserted");
Console.Write("\nPress 1 to continue ");
int input3 = 0;
bool right3 = int.TryParse(Console.ReadLine(), out input3);
if (!right3 || input3 != 1) break;
}
}
}
Console.ReadLine();
}
}
}