ReadLine - Array index out of bounds - c#-4.0

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]);
}
}
}

Related

How is a JPEG file formated?

I'm trying to write Bytes into a JPEG file, but I don't know the file's format and so the Bytes aren't in the right place of the image after writing into the file.
Does somebody know?
There are several markers that must appear in a JPEG file stream. I believe you can easily find the detailed description of the tags listed below on Internet.
SOI(0xFFD8) Start of Image
APP0(0xFFE0) Application
[APPn(0xFFEn)] (alternative)
DQT(0xFFDB) Define Quantization Table
SOF0(0xFFC0) Start of Frame
DHT(0xFFC4) Difine Huffman Table
SOS(0xFFDA) Start of Scan
DRI(0xFFDD) Define Restart Interval,(alternative)
...Image Stream
EOI(0xFFD9) End of Image
Those markers are followed by lengths in BIG ENDIAN format. You can decode Image Stream that exactly follows DRI using the huffman trees you decoded by DQT. For easier illustration, here are some functions I have written on my own in Java that decodes a header of JPEG, but without doubt there are many better JPEG Java projects on Github that you can refer to.
public int[][] cutX(byte[] x){
int s = x.length;int k = 1;int i = 2;int j;
d2[0][0]=Tool.unsignDecoder(x[1]);d2[1][0]=0;d2[2][0]=1;
while(d2[0][k-1]!=218){
d2[1][k]=i;
d2[0][k]=Tool.unsignDecoder(x[i+1]);
i=i+2+Tool.unsignDecoder(x[i+2])*256+Tool.unsignDecoder(x[i+3]);
d2[2][k]=i-1;
k=k+1;
}
for (j=s-1;j<i;j--){
if((Tool.unsignDecoder(x[j-1])==255)&&(Tool.unsignDecoder(x[j])==217)) break;
}
d2[0][k]=217;d2[1][k]=i;d2[2][k]=j+1;
return d2;
}
public void cutdata(byte[] x,int[][] d){
int a =Tool.indexOf_1(d[0],218);
int b =Tool.indexOf_1(d[0],217);
head = Arrays.copyOfRange(x, 0, d[2][a]+1);
byte[] im = Arrays.copyOfRange(x, d[1][b], d[2][b]-1);//-2:delete the last EOI message.
im1 = new byte[im.length];
int j=0;int i=0;//dynamically record the length of the revised sequence
while(i<im.length){
im1[j]=im[i];
j++;
if((i!=im.length-1)&&(Tool.unsignDecoder(im[i])==255)&&(Tool.unsignDecoder(im[i+1]))==0){
i++;//move rightward i
}
i++;
}
im1=Arrays.copyOfRange(im1, 0, j);//delete zeros in the end of the sequence
}
public void sof(byte[] x,int[][] d){
int z = Tool.indexOf_1(d[0],192);
int i = d[1][z];
int[] temp = new int[19];
for(int j=0;j<19;j++){
temp[j]=Tool.unsignDecoder(x[j+i]);
}
int ph=i+5;int pw=i+7;
size[0] = Tool.unsignDecoder(x[ph])*256+Tool.unsignDecoder(x[ph+1]);
size[1] = Tool.unsignDecoder(x[pw])*256+Tool.unsignDecoder(x[pw+1]);
i += 11;//skip some unused letters
for(int j=0;j<3;j++){
int k = Tool.unsignDecoder(x[i]);
Q[j][0] = (k & 0xF0)/16;
Q[j][1] = k & 0x0F;
i += 3;
}
}
public void hfm(byte[] x,int[][] d){
//the DHT marker may appear several times in a JPEG, or several huffman trees can be found in a single DHT.
ArrayList res =Tool.indexOf(d[0],196);int thisLength;int pointer;int pointerOrigin;
int a;int huffLength = 0;
for(int z=0;z<res.size();z++){
a=(int) res.get(z);
pointer = d[1][a];pointerOrigin = d[1][a]+2;//please follow the straight-forward moving of this pointer
thisLength = Tool.unsignDecoder(x[pointer+2])*256+Tool.unsignDecoder(x[pointer+3]);
int[] temp = new int[thisLength+4];
for(int i=0;i<thisLength;i++){
temp[i]=Tool.unsignDecoder(x[pointer+i]);
}
pointer += 4;
while(huffLength<thisLength){
int mode = Tool.unsignDecoder(x[pointer]);pointer += 1;
int[] huff_num = new int[16];int total=0;
for(int i=0;i<16;i++){//码字总个数
huff_num[i] = x[pointer+i];total+=huff_num[i];
}
pointer +=16;int codePointer=0;int code=0;
int[][] huffmanTree = new int[3][total];
for(int i=0;i<16;i++){
if(i!=0){
code *= 2;
}
for(int j=0;j<huff_num[i];j++){
huffmanTree[0][codePointer]=i+1;
huffmanTree[1][codePointer]=code;
huffmanTree[2][codePointer]=Tool.unsignDecoder(x[pointer+codePointer]);
code++;codePointer++;
}
}
huffLength += pointer + codePointer - pointerOrigin;pointer += codePointer;
pointerOrigin = pointer;
switch(mode){
case(0):d0 = huffmanTree;break;
case(1):d1 = huffmanTree;break;
case(16):a0 = huffmanTree;break;
case(17):a1 = huffmanTree;break;
}
}
}
}
public void dri(byte[] x,int[][] d){
int z = Tool.indexOf_1(d[0],221);
if(z!=-1){
int pointer = d[1][z];
int len = Tool.unsignDecoder(x[pointer+2])*256+Tool.unsignDecoder(x[pointer+3]);
int[] temp = new int[len+2];
for(int i=0;i<len;i++){
temp[i]=Tool.unsignDecoder(x[pointer+i]);
}
DRI = Tool.unsignDecoder(x[d[1][z]+4])*256+Tool.unsignDecoder(x[d[1][z]+5]);}
}
public void sos(byte[] x,int[][] d){
int z = Tool.indexOf_1(d[0],218);int a = d[1][z];
int len = Tool.unsignDecoder(x[a+2])*256+Tool.unsignDecoder(x[a+3]);
int[] temp = new int[len+2];
for(int j=0;j<len+2;j++){
temp[j]=Tool.unsignDecoder(x[j+a]);
}
int pointer = d[1][z]+6;
for(int j=0;j<3;j++){
treeSelect[j] = Tool.unsignDecoder(x[pointer]);
pointer += 2;
}
}

How can I make int input to string input C#

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]);
}

Passing an array of object from one class to another

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;
}
}

Algorithm for Hyper String

I want to know about the algorithm to solve HyperString Problem.
You can find the description at https://www.hackerrank.com/challenges/hyper-strings.
Can it be solved by dynamic programming?
Any help would be highly apreciated.
public class HyperString {
//Abubaker Tagelsir
private static int n,m,sum=1;
private static void temp(String u,String []d)
{
for(int i=0 ; i<d.length;i++)
{
if((u.length()+d[i].length())<=m)
{
sum++;
temp(u+d[i],d);
}
}
}
private static int Input3(String [] d)
{
sum +=d.length;
for(int i=0;i<d.length;i++){
for(int j=0;j<d.length;j++)
{
if((d[i].length()+d[j].length())<=m)
{
sum++;
temp(d[i]+d[j],d);
}
}
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String h = sc.nextLine();
StringTokenizer tz = new StringTokenizer(h);
String h1 = tz.nextToken();
n = Integer.parseInt(h1);
String h2 = tz.nextToken();
m = Integer.parseInt(h2);
//Input2();
String [] d = new String[n];
for(int i=0;i<n;i++)
{
d[i] = sc.nextLine();
}
System.out.println(Input3(d));
}
}

Reverse String Palindrome

Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.
import java.util.Random;
public class IterativePalindromGenerator {
public static void main(String[] args) {
Random random = new Random();
int floorValue = 1;
int cielingValue = 20;
int randomNumber = random.nextInt(cielingValue - floorValue)
+ floorValue;
String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomNumber; i++) {
char generatedLetters = alphabetLetters.charAt(random
.nextInt(alphabetLetters.length()));
String generatedLetterSTRINGType = Character
.toString(generatedLetters);// converts char to string
System.out.print(generatedLetterSTRINGType);
}
}
}
To reverse a string you can use StringBuffers reverse() method:
public String reverse(String stringToReverse) {
return new StringBuffer(stringToReverse).reverse().toString();
}
Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.
package DiskreteMathe;
import java.util.*;
public class AufgabePalindromTestRekursiv {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter text here:");
String text= sc.next();
System.out.println(testPalindrom(text));
}
public static boolean testPalindrom (String text){
if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
return true;
if(text.charAt(0)!=text.charAt(text.length()-1)){
return false;
} else {
text = text.substring(1, text.length()-1);
return testPalindrom(text);
}
}
}
When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).
Here is my code:
public class PalindromeGenerator {
public static void main(String[] args) {
String str = "abc";
String reverse_str = "";
for (int n = str.length(); n>0; n--){
reverse_str += str.substring(n-1, n);
}
String even_str = str + reverse_str;
String odd_str = str.substring(0, str.length()-1) + reverse_str;
System.out.println(even_str); // print "abccba"
System.out.println(odd_str); //print "abcba"
}
}
I Hope this can help you.

Resources