How to put dynamic array in function C#? - arrays

This my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class RetardedStudent
{
public String Name = "1";
public int IQ;
public void PrintName()
{
Console.Write("Student Name ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(Name);
Console.ResetColor();
Console.Write(" Student Test Result: ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(IQ);
Console.ResetColor();
Console.WriteLine();
}
}
public class Program
{
public unsafe void SortRetardedStudents(RetardedStudent[] Retards)
{
int IQ;
string Name;
int RetardsNumber = Retards.Length;
for (int i = 0; i < RetardsNumber; i++)
{
for (int j = 0; j < RetardsNumber - i - 1; j++)
{
if (Retards[j].IQ > Retards[j + 1].IQ || (Retards[j].IQ == Retards[j + 1].IQ) && (String.Compare(Retards[j].Name, 0, Retards[j + 1].Name, 0, Math.Max(Retards[j].Name.Length, Retards[j + 1].Name.Length)) > 0))
{
IQ = Retards[j].IQ;
Name = Retards[j].Name;
Retards[j].IQ = Retards[j + 1].IQ;
Retards[j].Name = Retards[j + 1].Name;
Retards[j + 1].IQ = IQ;
Retards[j + 1].Name = Name;
}
}
}
}
static void Main(string[] args)
{
unsafe
{
Console.Write("Input number of students:");
Console.WriteLine();
int RetardsNumber;// = Convert.ToInt32(Console.ReadLine());//Convert не прокатывает если ввести не число
Int32.TryParse(Console.ReadLine(), out RetardsNumber);//на случай ввода не числа не будет вылета - будет словно ввели 0
if (RetardsNumber < 1)
{
Console.WriteLine("You entered zero/nonnumeric values as number of students. Programm execution is finished");
Console.ReadLine();
return;
}
RetardedStudent[] Retards = new RetardedStudent[RetardsNumber];
for (int i = 0; i < RetardsNumber; i++)//fill students and their scores
{
Retards[i] = new RetardedStudent();
Console.Write("Input Name and score for student # {0} ", i + 1);
String StudentNameAndScore = Console.ReadLine();
int SpaceIndex = StudentNameAndScore.LastIndexOf(" ");
if (SpaceIndex != -1)
{
Retards[i].Name = StudentNameAndScore.Remove(SpaceIndex, StudentNameAndScore.Length - SpaceIndex);
Int32.TryParse(StudentNameAndScore.Remove(0, SpaceIndex + 1), out Retards[i].IQ);
}
else
{
Retards[i].Name = StudentNameAndScore;
Retards[i].IQ = 0;
}
}
if (RetardsNumber == 1)
{
Console.WriteLine("You entered 1 student " + Retards[0].Name + " with iq score test result: " + Retards[0].IQ + " Programm execution is finished because no need in sorting");
Console.ReadLine();
return;
}
RetardedStudent tempRetard = new RetardedStudent();
SortRetardedStudents(&Retards);
for (int i = 0; i < RetardsNumber; i++)
{
for (int j = 0; j < RetardsNumber - i - 1; j++)
{
if (Retards[j].IQ > Retards[j + 1].IQ || (Retards[j].IQ == Retards[j + 1].IQ) && (String.Compare(Retards[j].Name, 0, Retards[j + 1].Name, 0, Math.Max(Retards[j].Name.Length, Retards[j + 1].Name.Length)) > 0))
{
tempRetard.IQ = Retards[j].IQ;
tempRetard.Name = Retards[j].Name;
Retards[j].IQ = Retards[j + 1].IQ;
Retards[j].Name = Retards[j + 1].Name;
Retards[j + 1].IQ = tempRetard.IQ;
Retards[j + 1].Name = tempRetard.Name;
}
}
}
Console.WriteLine();
Console.WriteLine("sorted by score then by Name");
Console.WriteLine();
for (int i = 0; i < RetardsNumber; i++)
{
Console.Write("# {0} ", i + 1);
Retards[i].PrintName();
}
// Console.WriteLine("X format: {0:X}",99999);
Console.ReadLine();
}
//
}
}
}
I try to call SortRetardedStudents but whatever i do i always encounter errors. I tried to use unsafe, i added property to project whicj allows me to run unsafe code.
Right now my error is CS0208
Please help to solve the problem. I'm very bad with understanding pointers and references evem after videos.

I'm sure there is no reason to use unsafe code here.
It's looks like you miss static in your origin code.
public static void SortRetardedStudents(RetardedStudent[] Retards)

Related

Reverse an Array without using reverse Function and other array the same array to be reverse all elements in the same array. size fix

// I am tring but cant do it
int[] arr = {1,3,4,2,5,6};
int n = arr.length,x = 0;
for (int i = 0 ; i < n; i++ ) {
x++;
System.out.println(arr[i]);
}
//try this:
public class reverseArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = new int[] { 1,3,4,2,5,6 };
System.out.print("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
// method #1: by using extra array
System.out.println();
System.out.print("Reversed array method 1: ");
int j = 0;
int revArr[] = new int[] { arr.length };
for (int i = arr.length - 1; i >= 0; i--) {
revArr[j] = arr[i];
System.out.print(revArr[j] + " ");
}
// method #2: without using extra array
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
System.out.println();
System.out.print("Reversed array method 2: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

Dynamic memory C, realloc exception

I am trying to write code using dynamic memory allocation, and facing the problem that when realloc() is called in genPointLinkArray(), the program throws an exception: ConsoleApplication1.exe has triggered a breakpoint.
I am using Visual Studio 15 and running the program in Debug mode.
struct graphPoint
{
point p;
int value;
};
struct graphLink
{
point start;
graphPoint end;
};
graphLink* genPointLink(char map[10][10], point start, graphPoint primaryPoint[22], int *linksNum)
{
graphLink *lin = (graphLink*)0;
(*linksNum) = 0;
for (int i = 0; i < 22; i++)
{
if (!ifWay(map, start, primaryPoint[i].p))
{
(*linksNum)++;
if(*linksNum == 1)
lin = (graphLink*)malloc(sizeof(graphLink));
else
{
lin = (graphLink*)realloc(lin, (*linksNum) * sizeof(graphLink));
}
(lin + (*linksNum - 1))->start = start;
(lin + (*linksNum - 1))->end = primaryPoint[i];
}
}
return lin;
}
graphLink* genPointLinkArray(char map[10][10], graphPoint primaryPoint[22], int *linksNum)
{
graphLink *links = (graphLink*)0, *l;
int currentNum = 0;
*linksNum = 0;
for (int i = 0; i < 22; i++)
{
l = genPointLink(map, primaryPoint[i].p, primaryPoint, &currentNum);
if(currentNum != 0)
if (*linksNum == 0)
links = (graphLink*)calloc(currentNum, sizeof(graphLink));
else
links = (graphLink*)realloc(links, ((currentNum + *linksNum) * sizeof(graphLink)));
*linksNum = *linksNum + currentNum;
for (int i = 0; i < currentNum; i++)
{
links[*linksNum - 1 + i].end = l[i].end;
links[*linksNum - 1 + i].start = l[i].start;
}
}
for (int i = 0; i < *linksNum; i++)
{
printf("(%d ; %d) -> (%d ; %d) : %d\n", links[i].start.x, links[i].start.y, links[i].end.p.x, links[i].end.p.y, links[i].end.value);
}
return links;
}
Your problem is the following part of code
*linksNum = *linksNum + currentNum;
for (int i = 0; i < currentNum; i++)
{
links[*linksNum - 1 + i].end = l[i].end;
links[*linksNum - 1 + i].start = l[i].start;
}
You update the *linksNum before the loop, so inside the loop you are addressing the links "array" out of bound: Undefined Behavior.

Java Program - Patternmaker | How to make odd columns show?

for my homework I need to make a pattern using for nested loops. It needs to look like this:
pattern for 5 rows and 7 columns
However, when I was writing my code I could not figure out what to do make columns, if an odd number, to appear. I figured I needed to add another If/else statement. Here is my code:
public class PatternMaker {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Declaration
int numrows = 5;
int numcols = 7;
String str1= "XX";
String str2 = "OO";
String sep = "***";
if (numcols % 2 == 0) { // if columns is even
// for each row
for (int i = 1; i <= numrows; i++) {
// for each column
for (int k = 0; k < numcols/ 2; k++) {
if ( i % 2 == 1) { // for odds
if(k > 0) {
System.out.print(sep + str1 + sep+ str2);
}
else
System.out.print(str1 + sep + str2);
}
else { // for evens
if(k > 0) {
System.out.print(sep + str2 + sep + str1);
}
else
System.out.print(str2 + sep + str1);
}
}
System.out.println();
}
}
else { // if columns is odd
// for each row
for (int i = 1; i <= numrows; i++) {
// for each column
for (int k = 0; k < (numcols/ 2); k++) {
if ( i % 2 == 1) { // for odds
if(k > 0) {
System.out.print(sep + str1 + sep+ str2);
}
else
System.out.print(str1 + sep + str2);
}
else { // for evens
if(k > 0) {
System.out.print(sep + str2 + sep + str1);
}
else
System.out.print(str2 + sep + str1);
}
}
System.out.println();
}
}
Here you are :
// Declaration
int numrows = 5;
int numcols = 7;
String str1 = "XX";
String str2 = "OO";
String sep = "***";
for (int i = 0; i < numrows; i++) {
for (int j = 0; j < numcols; j++) {
if (j != 0) {
System.out.print(sep);
}
if (i % 2 == 0) {
if (j % 2 == 0) {
System.out.print(str1);
} else {
System.out.print(str2);
}
} else if (j % 2 == 0) {
System.out.print(str2);
} else {
System.out.print(str1);
}
}
System.out.println("");
}

Loop wont stop, even with limit set (count++)

I just cannot seem to get this to stop looping after the count (5) is reached. IT just keeps asking away. IS there something I'm not seeing?
Any help is greatly appreciated.
Scanner keyboard = new Scanner(System.in);
int count = 0;
double answer = 0;
int randomInt1;
int randomInt2;
randomInt1 = (int)(1 + Math.random() * 10 - 1 +1);
randomInt2 = (int)(1 + Math.random() * 10 - 1 +1);
//System.out.println("Please answer the following problem: ");
//System.out.println(randomInt1 + "+" + randomInt2 + "=");
//answer = keyboard.nextDouble();
count=1;
while(count < 5)
{
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if(answer != (randomInt1 + randomInt2))
{
System.out.println("Sorry, that is not correct.");
count++;
break;
}
if(answer == (randomInt1 + randomInt2))
{
System.out.println("Nice!");
count++;
break;
}
}
return answer;
}
}
****UPDATED
count=0;
while(count < 5)
{
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if(answer != (randomInt1 + randomInt2))
{
System.out.println("Sorry, that is not correct.");
}
else if(answer == (randomInt1 + randomInt2))
{
System.out.println("Nice!");
}
count++;
break;
}
return answer;
Avoid using break on your code. Use else instead of the second if statement. Also, you should better indent your code. It helps reading.
If you want to count 5 times, you should do:
count = 0;
while(count < 5) {
...(your code here)
}
Why don't you increase count outside the if condition.
count = 0;
while(count < 5) {
if(condition1){
// ...
}
else{
// ...
}
count++;
}
Update:
Below is the complete code, which may be like what you want.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
double answer = 0;
int randomInt1;
int randomInt2;
randomInt1 = (int) (1 + Math.random() * 10 - 1 + 1);
randomInt2 = (int) (1 + Math.random() * 10 - 1 + 1);
while (count < 5) {
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if (answer != (randomInt1 + randomInt2)) {
System.out.println("Sorry, that is not correct.");
} else if (answer == (randomInt1 + randomInt2)) {
System.out.println("Nice!");
break;
}
count++;
}
}
}

How to let Stage show the pictures after timer

After I click start button, my program will not show the second scene and thread , until the thread is finish. And the thread will not run correctly(grass didn't increase).
public class test111 extends Application {
private static int grass_i=130;
private static int grass_j=200;
private static int[][] map = new int[grass_i][grass_j];//草地資料grassdata
private static int totalgrass; //grass total number
private static int totalgrassrest; //grass rest number
private static int months=1; //月
private Timer timer;//時間
//GUI
Scene menusc ;
//START後的視窗
BorderPane bpAll = new BorderPane();
Pane playView = new Pane();
Scene mainsc = new Scene(bpAll);
//草
Image littlegrassImg = new Image(getClass().getResourceAsStream("map_littlegrass.png"));
Image midiumgrassImg = new Image(getClass().getResourceAsStream("map_midiumgrass.png"));
Image muchgrassImg = new Image(getClass().getResourceAsStream("map_muchgrass.png"));
Rectangle2D[][] viewportRect = new Rectangle2D[130][200];
private static ImageView[][] mapView = new ImageView[130][200];
//時間
#Override
public void start(Stage primaryStage) throws InterruptedException {
//MENU
Pane menu = new Pane();
menusc = new Scene(menu);
menu.setPrefSize(1000, 800);
Image MenuImg = new Image(getClass().getResourceAsStream("Menu_title.jpg"));
Image StartImg = new Image(getClass().getResourceAsStream("Start.jpg"));
menu.getChildren().add(new ImageView(MenuImg));
Button StartBt = new Button();
StartBt.setPrefSize(450, 150);
StartBt.setGraphic(new ImageView(StartImg));
StartBt.setMaxSize(450, 150);
StartBt.setLayoutX(300);
StartBt.setLayoutY(600);
menu.getChildren().addAll(new ImageView(MenuImg),StartBt);
primaryStage.setMinHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMinWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setMaxHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMaxWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setScene(menusc);
primaryStage.setTitle("Hypnos' yard");
//START
StartBt.setOnAction(e->{
BorderPane bp2 = bp2();
menusc = new Scene(bp2);
primaryStage.setScene(menusc);
});
primaryStage.show();
}
public BorderPane bp2(){
playView = playView();
bpAll = new BorderPane();
bpAll.setPrefSize(1000, 800);
playView.setPrefSize(1000, 650); //庭院
bpAll.setTop(playView);
Random ran = new Random();
totalgrass = (ran.nextInt(50)*1000)+48000;
totalgrassrest = totalgrass;
grasscreate();
//設定初始草地construct the initial grass
grassGraphicsLoading(); //loading grass pictures
return bpAll;
}
public Pane playView(){
playView = new Pane();
while(months<12){
timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
month();
}
};//after program executing 0.2s, a month past
timer.schedule(task, 200);
try {
Thread.sleep(200);
}
catch(InterruptedException e6) {
}
timer.cancel();
}
return playView;
}
//月month
protected void month(){
if(months<13){
grassgrow(totalgrass*2);//grass growth
Platform.runLater(new Runnable(){
#Override
public void run(){
grassGraphicsLoading();
}
});
months++;
}
}
//把草地資料帶入圖形loading grass pictures
private void grassGraphicsLoading(){
for (int i = 0; i < grass_i; i++) { // 設定imageView的圖形和位置
for (int j = 0; j < grass_j; j++) {
viewportRect[i][j] = new Rectangle2D(j * 5, i * 5, 5, 5);
if (170 <= j && j <= grass_j - 1) {
mapView[i][j] = new ImageView(muchgrassImg);
} else if (140 <= j && j < 170) {
mapView[i][j] = new ImageView(muchgrassImg);
} else {
if (map[i][j] == 0) {
mapView[i][j] = new ImageView(littlegrassImg);
} else if (map[i][j] == 1 || map[i][j] == 2) {
mapView[i][j] = new ImageView(midiumgrassImg);
} else {
mapView[i][j] = new ImageView(muchgrassImg);
}
}
playView.getChildren().add(mapView[i][j]);
mapView[i][j].setViewport(viewportRect[i][j]);
mapView[i][j].setX(j * 5);
mapView[i][j].setY(i * 5);
}
}
}
public static void main(String[] args) {
launch(args);
}
// 每經過30天(一個月)草地+1grassgrowth
protected void grassgrow(int sum) {
for (int i = 0; i < grass_i; i++) {
for (int j = grass_j - 1; j >= 0; j--) {
if (map[i][j] < 4 && totalgrass <sum) {
map[i][j] += 1;
totalgrass++;
}
if (totalgrass == 104000||totalgrass ==sum) {
break;
}
}
}
}
//建構草地construct grass
protected void grasscreate() {
for (int j = grass_j - 1; j >= 0; j--) {
for (int i = grass_i - 1; i >= 0; i--) {
if (170 <= j && j <= grass_j - 1) {
map[i][j] = 0;
} else if (140 <= j && j < 170) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest <= 0) {
map[i][j] = 0;
} else if (4 * (j + 1) * grass_i <= totalgrassrest) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest < 4) {
map[i][j] = totalgrassrest;
totalgrassrest = 0;
} else {
map[i][j] = rancreate();
totalgrassrest -= map[i][j];
}
}
}
totalgrass -= totalgrassrest;
totalgrassrest = 0;
}
// 一格(5X5)內草地數量隨機1-4平米z there is 1-4 grass inside a rectangle
private int rancreate() {
Random ran = new Random();
int grass = ran.nextInt(5);
return grass;
}
}`

Resources