C# equivalent to Java's scn.nextInt( ) - c#

In Java, if we want to read an user input from the console, we can do the following.
Scanner scn = new Scanner (System.in);
int x;
x = scn.nextInt(); //Receive integer input
In C#, I am assuming we do this:
int x;
x = Console.Read(); //Receive integer input
But when I enter 7 , the output is 55.
The other 2 options for reading inputs are ReadLine() which is probably used for reading strings, and ReadKey() which is proabably for detecting which key you pressed (Please correct me if I am wrong).
Please don't tell me that we have to use ReadLine and parse the entire value to int everytime, that will be awful :-(
EDIT: In SO, a similar question was raised (c# Console.Read() and Console.ReadLine() problems), but all the solutions given was to use int.TryParse and series of codes just to receive a int or double input, which I find it too inconvenient just to do a simple task.
I found out that we could actually do this:
int a = int.Parse(Console.ReadLine());
So instead of asking a duplicated question,
my new question is: Is it equivalent to Java's scn.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?

Is it equivalent to Java's scanner.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?
Yes. Java's Scanner.nextInt() throws an exception when no integer input has been received, as does .NET's int.Parse(Console.ReadLine()).

This may be a year late, but...
static int GetInt() {
int integer = 0;
int n = Console.Read();
while (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
n = Console.Read();
while (n >= '0' && n <= '9') {
integer = integer * 10 + n - '0';
n = Console.Read();
}
return integer;
}
This is more or less the same as Java's nextInt() method. It doesn't support negative values as it currently is, but it can be easily implemented by checking if the first read value is '-' and if it is, multiply the final value by -1.

Yes, you need to use ReadLine, parsing the input is not so hard.Just use TryParse method:
int input;
bool isValid = int.TryParse(Console.ReadLine(),out input);
if(isValid)
{
...
}
Console.Read reads the next character from console, and it returns the ASCII code of the char, that's why you are getting 55 instead of 7.

You can use this library from NuGet which provides Java Scanner/C++ cin style input in C#: https://www.nuget.org/packages/Nakov.IO.Cin/
Sample:
using System;
using Nakov.IO;
public class EnterNumbers
{
static void Main()
{
int n = Cin.NextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
numbers[i] = Cin.NextInt();
for (int i = 0; i < n; i++)
Console.Write(numbers[i] + " ");
}
}

Related

I need to check if each digit from an integer is even or odd in c# an return even or odd

I'm new to c# language and still learning. I have to write a console application (like example) but the real problem for me is that I don't know how to access each number for the input integer and pass it on the division function (n % 2 ==0) and return even/odd for the given number.
For example:
the user input: 4444
and the console result: even
even
even
even
string inputData = Console.ReadLine(); // the 4 digit number
int number = Convert.ToInt32(inputData);
string emptyStr = String.Empty;
string divided = "even";
string notDivided = "odd";
// here .......????
if (number % 2 == 0)
{
Console.WriteLine(divided);
}
else
{
Console.WriteLine(notDivided);
}
I think this is what you are looking for.
First of all use this
Is there an easy way to turn an int into an array of ints of each digit?
After that just check every individual item in your array
public void main
{
var numbers = NumbersIn(987654321).ToArray();
foreach (int element in numbers)
{
if (element % 2 == 0)
{
Console.Write("even");
}
else
{
Console.Write("uneven");
}
}
}
public Stack<int> NumbersIn(int value)
{
if (value == 0) return new Stack<int>();
var numbers = NumbersIn(value / 10);
numbers.Push(value % 10);
return numbers;
}
https://learn.microsoft.com/en-us/dotnet/api/system.console.readline?view=netcore-3.1 you can use the hyperlink provided to use the method Console.ReadLine method for the conditional output that you are C#-ing.
You can read each key written by user in loop with:
var digit = Console.ReadKey()
Remember to parse char to int properly.
As Mong Zhu noticed, you cannot parse char value with: Int32.Parse('1'). You have to do it with string value.
So full solution is:
var digitStr = Console.ReadKey();
var digit = Int32.Parse(digitStr.KeyChar.ToString());

ID Number Generator

I keep getting an "int cannot convert to bool" error at if(number % NUMINROW), and I do not know how to fix it. I am fairly new to C#, but I know Python and how for loops work, but I am still confused.
// Program displays every possible ID number for a company
// ID number is a letter, followed by a two-digit number
// For example -- A00 or Z99
// Go to a new display line after every 20 IDs
using static System.Console;
class DebugFive3
{
static void Main()
{
char letter;
int number;
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
for(letter = 'A'; letter <= 'Z'; ++letter)
for(number = LOW; number >= HIGH; ++number)
{
if(number % NUMINROW)
WriteLine();
Write("{0}{1} ", letter, number.ToString("D2"));
}
}
}
You have error on second for and in condition if(number % NUMINROW)
static void Main(string[] args)
{
char letter;
int number;
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
for (letter = 'A'; letter <= 'Z'; ++letter)
{
for (number = LOW; number <= HIGH; ++number)
{
if (number % NUMINROW == 0)
Console.WriteLine();
else
Console.Write("{0}{1} ", letter, number.ToString("D2"));
}
}
Console.ReadLine();
}
The reason you're getting that compile error is that number % NUMINROW returns the remainder after dividing number by NUMINROW, which is an int, whereas an if condition must return a bool (and there is no implicit conversion from int to bool in C#).
One way to fix this is to modify the condition so that it compares the result of the modulus operation to another int, for example:
if(number % NUMINROW == 0)
Other Issues
There is no Console.ReadLine() at the end of the Main method, so as soon as the data is displayed, the console window will dissapear. Adding this line will pause execution until the user presses the Enter key, giving them time to see the data.
This condition is incorrect: number = LOW; number >= HIGH. It reads, "set number to LOW, then loop while number is greater than or equal to HIGH." That condition will never be true!! We should use <= instead.
The current code is completely ignoring the 20th column. To solve this, we can remove the else clause and switch the order of the code lines so that we always write the value, and then conditionally add a new line.
Assuming we want NUMINROW columns displayed, our modulus condition should compare the next number to this value, since we're starting at 0 (so the first row would be 0-19, followed by 20-39). Another reason to add one to the value before doing the comparison is that 0 modulus any number is 0, so we would have an extra new line before the first item (where number is 0).
Not a problem, really, but since we don't use the variables letter or number outside the loops, it's generally better to declare them as part of the for loop itself, to reduce their scope.
Here's a sample of how to solve these issues:
static void Main(string[] args)
{
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
for (char letter = 'A'; letter <= 'Z'; letter++)
{
for (int number = LOW; number <= HIGH; number++)
{
Write("{0}{1} ", letter, number.ToString("D2"));
if ((number + 1) % NUMINROW == 0) WriteLine();
}
}
ReadLine(); // Wait for user input
}
Output
As a side note, here's a fun little sample using System.Linq that does it all in one line (not recommended, since it's hard to read/debug, but thought it might be interesting):
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
WriteLine(string.Concat(Enumerable.Range('A', 26)
.Select(chr => string.Concat(Enumerable.Range(LOW, HIGH + 1)
.Select(num => $"{(char) chr}{num:D2}" + ((num + 1) % NUMINROW == 0
? Environment.NewLine : " "))))));
ReadLine();

Having the nth char based on a variable not working as expected

So I have pow - a list containing numbers. I have to examine other numbers like this: Get all the digits and sum the numbers from pow having the same index as the certain digit.
So if I check number 4552 I need to get pow[4]+pow[5]+pow[5]+pow[2]. Because I'm a noob I try to convert the number to string, get the characters with loop and then convert back to int to get the index. So the code is as follows for getting the sums between 4550 and 4559:
for (int i = 4550; i < 4560; i++)
{
int sum = 0;
for (int j = 0; j < i.ToString().Length; j++)
{
sum += pows[Convert.ToInt32(i.ToString()[j])]; //here is the error - index was out of range
//do something with sum (like store it in another list)
}
}
So what is wrong with that?
EDIT: To avoid confusion... pow has 10 elements, from indexes 0-9.
SOLUTION: The issue with my code was that I got the character code not the digit itself, thanks Steve Lillis. Though the solution provided by Dmitry Bychenko is far more superior to my attempt. Thank you all.
What you're looking for is similar to a digital root:
Modulus (% in C#) is easier and faster than conversion to string:
public static int DigitalRootIndex(IList<int> list, int value) {
if (value < 0)
value = -value;
int result = 0;
// for value == 4552
// result == list[4] + list[5] + list[5] + list[2]
while (value > 0) {
int index = value % 10;
result += list[index];
value /= 10;
}
return result;
}
...
int test = DigitalRootIndex(pow, 4552);
This bit of code gets a single character such as '4' which is character code 59:
c = i.ToString()[j]
Then this bit of code turns that char into an integer. It doesn't parse it like you're expecting, so the result for '4' is 59, not 4:
Convert.ToInt32(c)
Do this instead:
int.Parse(c.ToString())
Something like this (quick and dirty try)?
int currentDigit;
int sum;
for (int i = 4550; i < 4560; i++)
{
sum = 0;
currentDigit = i;
while (currentDigit > 0)
{
if (pow.Count > (currentDigit % 10))
{
sum += pow[((currentDigit % 10))];
}
}
}
Note that lists have zero based index so when you do pow[1], you are actually accessing second element in the list. Is that what you want?

C# Code Verification Program

Alright so I am making a program to verify a 4 digit code.
The computer generates a 4 digit code
The user types in a 4 digit code. Their guess.
the computer tells them how many digits are
guessed correctly in the correct place and how many digits have
been guessed correctly but in the wrong place.
The user gets 12 guesses to either win – guess the right code. Or
lose – run out of guesses.
So basically, my program doesn't seem to actually verify whether the code is correct but i cant see why not because i have if and for loops for verification, please take a look.
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int DigitOne = random.Next(0, 10);
int DigitTwo = random.Next(0, 10);
int DigitThree = random.Next(0, 10);
int DigitFour = random.Next(0, 10);
byte[] code = new byte[4];
code[0] = Convert.ToByte(DigitOne);
code[1] = Convert.ToByte(DigitTwo);
code[2] = Convert.ToByte(DigitThree);
code[3] = Convert.ToByte(DigitFour);
bool CodeCorrect = false;
Console.WriteLine(code[0] +""+ code[1] +""+ code[2]+""+code [3] );
Console.WriteLine("You have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while (AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
for (int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(Console.Read()) - 48;
}
if (UserCode.Length != 4)
{
Console.WriteLine("Error. Try Again.\n");
}
else
{
int UserDigitOne = UserCode[0];
int UserDigitTwo = UserCode[1];
int UserDigitThree = UserCode[2];
int UserDigitFour = UserCode[3];
for (int i = 0; i < 4; i++)
{
if (UserCode[i] == code[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
}
}
if (UserCode[0] == code[0] && UserCode[1] == code[1] && UserCode[2] == code[2] && UserCode[3] == code[3])
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if (AmountOfGuesses > 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
If you step through the code after it generated the number 1246, and then input the same number from the command line, convert it to a char array, then convert each char to a byte, you'll get the following four bytes:
49 50 52 54
These correspond to the ASCII representations of each char, NOT the actual numbers.
Try something like this:
int[] input = new int[4];
for(int i = 0; i < 4; i++ )
{
input[i] = Convert.ToInt32(Console.Read()) - 48;
}
The -48 should turn your ASCII code into the actual numerical representation that was provided. Console.Read() reads individual characters rather than the full line.
Also, you don't have to say:
CodeCorrect == false
This is more simply represented as:
!CodeCorrect
Similarly, if it was set to true, it would just be:
CodeCorrect
I also suggest using a for loop to set multiple elements in an array rather than manually writing out each line of code. It's not a big deal for small arrays, but it's good practice.
UPDATE: Here's a revised version of the full program:
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int[] randCombination = new int[4];
for (int i = 0; i < 4; i++)
{
randCombination[i] = random.Next(0, 10);
Console.Write(randCombination[i].ToString());
}
bool CodeCorrect = false;
Console.WriteLine("\nYou have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while(AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
string input = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(input, out n);
int correctCount = 0;
if(input.Length != 4 || !isNumeric)
{
Console.WriteLine("Error. Input code was not a 4 digit number.\n");
}
else
{
for(int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(input[i]) - 48;
if(UserCode[i] == randCombination[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
correctCount++;
}
}
if(correctCount == 4)
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if(AmountOfGuesses >= 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
}
A couple of things were changed:
Added a for loop at the top that generates a random number, enters it into an array of ints and then prints it to standard output.
I changed the way user input is read back to the Console.ReadLine(). The reason for this is to check if the user inputted a four digit integer. the int.TryParse statement makes sure the input is an int, and the Length property checks the length.
I also used a counter to count each correct guess. If 4 correct digit guesses were made, the safe is unlocked.
Your final if statement would never have evaluated because Amount of Guesses would equal 12, not be greater than it. Changed it to >= from >. Always be on the lookout for small things like this.
EDIT #2: For more information on int.TryParse, see the following:
http://www.dotnetperls.com/int-tryparse
How the int.TryParse actually works
You are comparing numbers with the character representation of a number. Each value of code[] represents an actual number. You then compare those values with the values in UserCode which is a string, meaning there is a character at each index. It is never the case that ((byte)'4') == ((byte)4) (using 4 as an example, but works for any numerical digit).
One way around this is to parse each user input character into a byte using the byte.Parse method.
For fun learning purposes look at the output from the following code:
for (char i = '0'; i <= '9'; i++)
{
Console.WriteLine("char: " + i + "; value: " + ((byte)i));
}
The output is actually:
char: 0; value: 48
char: 1; value: 49
char: 2; value: 50
char: 3; value: 51
char: 4; value: 52
char: 5; value: 53
char: 6; value: 54
char: 7; value: 55
char: 8; value: 56
char: 9; value: 57
This is due to string encoding.
I would also recommend that one you have your code working that you submit it to the fine folks at the Code Review site to review other aspects of the code which could use work.

Programmatically check if a number is a palindrome

This sounds like homework, yes it is (of someone else), I asked a friend of mine who is learning C# to lend me some of his class exercises to get the hang of it.
So as the title says: How can I check if a number is a Palindrome?
I'm not asking for source code (although its very useful), but rather that someone explained how should the code should work, so that it can be applied to many different languages.
The Solution:
#statikfx searched SO for this and found the solution.
n = num;
while (num > 0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
// If (n == rev) then num is a palindrome
I check for palindromes by converting the integer to a string, then reversing the string, then comparing equality. This will be the best approach for you since you're just starting out.
Since you're working in C# and this is homework, I'll use very obscure-looking Python that won't help you:
def is_palindrome(i):
s = str(i)
return s[::-1] == s
Convert that to C# and you'll have your answer.
Main idea:
Input number: 12321
Splitting the digits of the number, put them into an array
=> array [1, 2, 3, 2, 1]
Check if array[x] = array[arr_length - x] for all x = 0..arr_length / 2
If check passed => palindrome
There are many ways. Probably the simplest is to have 2 indexes, i at beginning and j at end of number. You check to see if a[i] == a[j]. If so, increment i and decrement j. You stop when i > j. When looping if you ever reach a point where a[i] != a[j], then it's not a palindrome.
Here's some working code. The first function tests if a number is palidromic by converting it to a string then an IEnumerable and testing if it is equal to its reverse. This is enough to answer your question. The main function simply iterates over the integers testing them one by one.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static bool IsPalindromic(long l)
{
IEnumerable<char> forwards = l.ToString().ToCharArray();
return forwards.SequenceEqual(forwards.Reverse());
}
public static void Main()
{
long n = 0;
while (true)
{
if (IsPalindromic(n))
Console.WriteLine("" + n);
n++;
}
}
}
Update: Here is a more direct method of generating palindromes. It doesn't test numbers individually, it just generates palindromes directly. It's not really useful for answering your homework, but perhaps you will find this interesting anyway:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
bool oddLength = true;
ulong start = 1;
while (true)
{
for (ulong i = start; i < start * 10; ++i)
{
string forwards = i.ToString();
string reverse = new string(forwards.ToCharArray()
.Reverse()
.Skip(oddLength ? 1 : 0)
.ToArray());
Console.WriteLine(forwards + reverse);
}
oddLength = !oddLength;
if (oddLength)
start *= 10;
}
}
}
My solution:
bool IsPalindrome(string str)
{
if(str.Length == 1 || str.Length == 0) return true;
return str[0] == str[str.Length-1] && IsPalindrome(str.Substring(1,str.Length-2));
}
Here's some pseudocode:
function isPalindrome(number) returns boolean
index = 0
while number != 0
array[index] = number mod 10
number = number div 10
index = index + 1
startIndex = 0;
endIndex = index - 1
while startIndex > endIndex
if array[endIndex] != array[startIndex]
return false
endIndex = endIndex - 1
startIndex = startIndex + 1
return true
Note that that's for base 10. Change the two 10s in the first while loop for other bases.
The following function will work for both numbers as well as for strings.
public bool IsPalindrome(string stringToCheck)
{
char[] rev = stringToCheck.Reverse().ToArray();
return (stringToCheck.Equals(new string(rev), StringComparison.OrdinalIgnoreCase));
}
zamirsblog.blogspot.com
in theory you want to convert the number to a string. then convet the string to an array of characters and loop the array comparing character (i) with character (array length - i) if the two characters are not equal exit the loop and return false. if it makes it all the way through the loop it is a Palindrome.
Interesting. I'd probably convert the number to a string, and then write a recursive function to decide whether any given string is a palendrome.
int n = check_textbox.Text.Length;
int check = Convert.ToInt32(check_textbox.Text);
int m = 0;
double latest=0;
for (int i = n - 1; i>-1; i--)
{
double exp = Math.Pow(10, i);
double rem = check / exp;
string rem_s = rem.ToString().Substring(0, 1);
int ret_rem = Convert.ToInt32(rem_s);
double exp2 = Math.Pow(10, m);
double new_num = ret_rem * exp2;
m=m+1;
latest = latest + new_num;
double my_value = ret_rem * exp;
int myvalue_int = Convert.ToInt32(my_value);
check = check - myvalue_int;
}
int latest_int=Convert.ToInt32(latest);
if (latest_int == Convert.ToInt32(check_textbox.Text))
{
MessageBox.Show("The number is a Palindrome number","SUCCESS",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
MessageBox.Show("The number is not a Palindrome number","FAILED",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
public class Main {
public static boolean Ispalindromic(String word) {
if (word.length() < 2) {
return true;
}
else if (word.charAt(0) != word.charAt(word.length() - 1)) {
return false;
} else {
Ispalindromic(word.substring(1, word.length() - 1));
}
return true;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String word = sc.nextLine();
System.out.println(Ispalindromic(word) ? "it is palidromic" : "it is not palidromic");
}
}
This is my solution coming from a beginner:
Console.Write("Enter a number to check if palindrome: ");
bool palindrome = true;
int x = int.Parse(Console.ReadLine());
/* c is x length minus 1 because when counting the strings
length it starts from 1 when it should start from 0*/
int c = x.ToString().Length - 1;
string b = x.ToString();
for (int i = 0; i < c; i++)
if (b[i] != b[c - i])
palindrome = false;
if (palindrome == true)
Console.Write("Yes");
else Console.Write("No");
Console.ReadKey();
You need to reverse the number then compare the result to the original number.
If it matches, you have a palindrome. It should work irrespective of the number being even, odd or symmetric.
public static bool IsNumberAPalindrome(long num)
{
return long.Parse(string.Join("", num.ToString().ToCharArray().Reverse().ToArray())) == num ? true : false;
}
The implementation is bellow:
public bool IsPalindrome(int x) {
string test = string.Empty;
string res = string.Empty;
test = x.ToString();
var reverse = test.Reverse();
foreach (var c in reverse)
{
res += c.ToString();
}
return test == res;
}
You have a string, it can have integers, it can have characters, does not matter.
You convert this string to an array, depending on what types of characters the strings consist of, this may use to toCharArray method or any other related method.
You then use the reverse method that .NET provides to reverse your array, now you have two arrays, the original one and the one you reversed.
You then use the comparison operator (NOT THE ASSIGNMENT OPERATOR!) to check if the reversed one is the same as the original.
something like this
bool IsPalindrome(int num)
{
var str = num.ToString();
var length = str.Length;
for (int i = 0, j = length - 1; length/2 > i; i++, j-- ){
if (str[i] != str[j])
return false;
}
return true;
}
you could even optimise it

Categories