How can I make int input to string input in C#? How can I change the int input to string input, so the user can write letters to the textbox, instead of numbers? I have tried myself, but the code won't work anymore. I know the solution is easy, but can't figure it out..
Here is my code:
public partial class MainWindow : Window
{
int[] arvat = new int[10];
int i = 0;
int k = 0;
public MainWindow()
{
InitializeComponent();
}
private void btnNimi_Click(object sender, RoutedEventArgs e)
{
int nimet = int.Parse( txtNimi.Text);
if (i < arvat.Length)
{
arvat[i] = nimet;
i++;
txtNimi.Text = "";
txtNimi.Focus();
}
else
{
MessageBox.Show("Kaikki arvat on syƶtetty.");
txtNimi.Text = "";
}
}
private void btnArpa_Click(object sender, RoutedEventArgs e)
{
int arpa = 0;
Random r = new Random();
arpa= r.Next(0, 9);
txbArvonta.Text = "";
for (int i = 0; i < arvat.Length; i++)
{
txbTeksti.Text = "\n" + "Kaikki osallistuneet: " + "\n";
txbArvonta.Text += arvat[i] + "\n";
int arpominen = arvat [k];
txbVoittaja.Text = "Ja voittaja on: " + arvat[arpa].ToString() + "\n" + "Onnea voittajalle!";
}
Instead of using Int.Parse, try using Int.TryParse to determine if the input will evaluate to a number before storing the result.
int number = 0;
bool isNumeric = Int32.TryParse(arvat[i], out number);
if (isNumeric)
{
Console.WriteLine("'{0}' is a number {1}.", arvat[i], number);
}
else
{
Console.WriteLine("'{0}' is text.", arvat[i]);
}
Related
I try to make a lock on the incrementer "counter" in the Countrange method.
The counter should count under some conditions in the threads. If I complete the threads in order (not parallel) i get the right counter value over and over, but when i try to lock like i do in de program, it still isn't threadsafe, because i get diffrent counter values when i run the program a few times.
{
class Program
{
static int e, p, b, m;
static int counter = 0;
static int lok = 0;
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputs = input.Split(' ');
counter = 0;
p = Convert.ToInt32(inputs[4]);
e = Convert.ToInt32(inputs[2]);
b = Convert.ToInt32(inputs[1]);
m = Convert.ToInt32(inputs[3]);
Thread[] ts = new Thread[p];
for (int t = 0; t < p; t++)
{
ts[t] = new Thread(countrange);
}
for (int t = 0; t < p; t++)
{
ts[t].Start(t);
}
for (int t = 0; t < p; t++)
{
ts[t].Join();
}
Console.Write(counter);
//Console.ReadKey();
}
public static void countrange(object mt)
{
int to = eind * (((int)mt + 1) / p) + verdeler + b;
int from = eind * (((int)mt) / p) + verdeler - a + b;
for (int i = from; i < to; i++)
{
proef = proef + moduler * keer;
}
{
if (proef % m == 0)
lock (mt)
{
counter++;
}
}
}
}
}
}
I made the lock static, now it works
I need to write an application that fist converts a string to unicode and then add 2 to the unicode value to create a new string.
Basically, if the input is: password is RhYxtz, then the output should look like: rcuuyqtf ku TjAzvb
the following code is what I have so far:
public static void main(String[] args){
System.out.print ("Enter text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
int length = text.length();
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
int currentChar2 = currentChar+2;
String s = String.format ("\\u%04x", currentChar2);
System.out.println ("Encoded message: " + s);
}
}
The problem is that I don't know how to convert the unicode back into a letter string and how to keep the format the same as the input. Could anyone help me? Thanks.
Unicode code points can be gathered in java 8 as:
public static String encryped(String s) {
int[] cps = s.codePoints()
.mapToInt((cp) -> cp + 2)
.toArray();
return new String(cps, 0, cps.length);
}
or in a loop with codePointAt in earlier versions.
Java char (2 bytes) are UTF-16, and their int value is not always a Unicode symbol aka code point.
Try this:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
System.out.print ("Enter text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
int length = text.length();
String s = "";
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
if (currentChar == ' '){
s += currentChar;
} else {
s += (char) (currentChar + 2);
}
}
System.out.println ("Encoded message: " + s);
}
}
This should work for US ASCII letters:
StringBuilder buf = new StringBuilder(length);
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
if (currentChar < 128 && Character.isLetter(currentChar)) {
if (currentChar == 'y' || currentChar == 'z'
|| currentChar == 'Y' || currentChar == 'Z') {
buf.append((char) (currentChar + 2 - 26));
} else {
buf.append((char) (currentChar + 2));
}
} else {
buf.append(currentChar);
}
}
System.out.println(buf.toString());
I've been trying to create a program where it takes an array input through an object and passes the parameter (simulation of ArrayList).
I keep getting the java.lang.ArrayIndexOutOfBoundsException in which I'm guessing I'm not accessing the array properly..
What can I do to enhance the test object and/ or the constructor?
public class MyArrayList{
public int[] x;
public MyArrayList( ){
x = new int[0];
}
public MyArrayList(int[] k)
{
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
public void add(int index).......
public int size().....
public int get(int index).....
public void set(int index, int value).......
public String toString( )........
Below is the class I am having trouble with.
public class TestMyArrayList
{
public static void main(String[] args)
{
MyArrayList test = new MyArrayList();
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
test.add(2);
test.set(1,3);
int a, b;
String c;
a = test.size( );
b = test.get(5);
c = test.toString( );
System.out.println("The size of the array is" + a);
System.out.println("The value at that position is " + b);
System.out.println("The resulting string is: " + c);
}
}
This line from your constructor is the only location (in the code you've shown) where the array x is initialized:
x = new int[0];
And it creates a zero length array. Assuming you are not reinitializing the array somewhere else then all these lines will definitely fail:
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
Because your array length is zero. So:
Initialize your array to a more sensible value
Consider encapsulating the array so that callers cannot directly access it. This will make it much easier to code up your application in the long run
Side note (aka bonus):
This other constructor of yours:
public MyArrayList(int[] k) {
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
has some issues as well:
You should reinitialize your array x to be the same size as the supplied array, prior to copying over the values.
The assignment k = x is basically a no-op, because it doesn't actually change what k was pointing to outside of the method.
Overall, it should look more like this:
public MyArrayList(int[] k) {
super();
if(k != null) {
x = new int[k.length];
for (int i = 0; i < x.length; i++) {
x[i] = k[i];
}
} else {
x = null;
}
}
I am writing a program that does simple math problems. What I am trying to do is to make it so that even if I input a string into the the scanner level it will not give me an error. The level is to choose the difficulty of the math problems. I have tried parseInt, but am at a loss of what to do now.
import java.util.Random;
import java.util.Scanner;
public class Test {
static Scanner keyboard = new Scanner(System.in);
static Random generator = new Random();
public static void main(String[] args) {
String level = intro();//This method intorduces the program,
questions(level);//This does the actual computation.
}
public static String intro() {
System.out.println("HI - I am your friendly arithmetic tutor.");
System.out.print("What is your name? ");
String name = keyboard.nextLine();
System.out.print("What level do you choose? ");
String level = keyboard.nextLine();
System.out.println("OK " + name + ", here are ten exercises for you at the level " + level + ".");
System.out.println("Good luck.");
return level;
}
public static void questions(String level) {
int value = 0, random1 = 0, random2 = 0;
int r = 0, score = 0;
int x = Integer.parseInt("level");
if (x==1) {
r = 4;
}
else if(x==2) {
r = 9;
}
else if(x==3) {
r = 50;
}
for (int i = 0; i<10; i++) {
random1 = generator.nextInt(r);//first random number.
random2 = generator.nextInt(r);//second random number.
System.out.print(random1 + " + " + random2 + " = ");
int ans = keyboard.nextInt();
if((random1 + random2)== ans) {
System.out.println("Your answer is correct!");
score+=1;
}
else if ((random1 + random2)!= ans) {
System.out.println("Your answer is wrong!");
}
}
if (score==10 || score==9) {
if (score==10 && x == 3) {
System.out.println("This system is of no further use.");
}
else {
System.out.println("Choose a higher difficulty");
}
System.out.println("You got " + score + " out or 10");
}
else if (score<=8 && score>=6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Do the test again");
}
else if (score>6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Come back for extra lessons");
}
}
}
The first error I see is that you tried to Integer.parseInt() a String "level" instead of the String variable named level
int x = Integer.parseInt("level");
should be
int x = Integer.parseInt(level);
Also, when defining level you can use keyboard.nextInt instead of keyboard.nextLine
String level = keyboard.nextInt();
Then, you wouldn't have to do an Integer.parseInt() operation later on
I have been debugging this program to find the error but couldn't succeed in that. For some reason, it is displaying an error - array index out of bounds in this line
moves[nCount].sDirection = sStep[0]; I know, this forum is not meant for debugging, im sorry for that.
class Program
{
struct move
{
public char sDirection;
public int steps;
}
static void Main(string[] args)
{
int nNumOfInstructions = 0;
int nStartX = 0, nStartY = 0;
move[] moves = new move[nNumOfInstructions];
nNumOfInstructions=Convert.ToInt32(Console.ReadLine());
string sPosCoOrd = Console.ReadLine();
nStartX = Convert.ToInt32(sPosCoOrd[0]);
nStartY = Convert.ToInt32(sPosCoOrd[2]);
string sStep = "";
for (int nCount = 0; nCount < nNumOfInstructions; nCount++)
{
sStep = Console.ReadLine();
int length = sStep.Length;
moves[nCount].sDirection = sStep[0];
moves[nCount].steps = Convert.ToInt32(sStep[1]);
}
Console.ReadLine();
}
}
In your code, the moves array is created as an array of zero length. For any index, accessing this array will inevitably throw an Array index out of bounds
You probably want to do it this way:
class Program
{
struct move
{
public char sDirection;
public int steps;
}
static void Main(string[] args)
{
int nNumOfInstructions = Convert.ToInt32(Console.ReadLine());
move[] moves = new move[nNumOfInstructions];
string sPosCoOrd = Console.ReadLine();
int nStartX = Convert.ToInt32(sPosCoOrd[0]);
int nStartY = Convert.ToInt32(sPosCoOrd[2]);
string sStep = String.Empty;
for (int nCount = 0; nCount < nNumOfInstructions; nCount++)
{
sStep = Console.ReadLine();
int length = sStep.Length;
moves[nCount].sDirection = sStep[0];
moves[nCount].steps = Convert.ToInt32(sStep[1]);
}
}
}