Sort array fix code - arraylist

This method needs to sort and array and I am close with the following code but what it does is puts the list forwards to backwards i.e. if the list was "5, 4, 3" this would change it to "3, 4, 5". This is because after the if statement completes it goes back to the for and once it is finished the for it sets lowest back to 1000. How do I make it not set it back to 1000 each time?
public void sortList()
{
for(int i=0; i<myList.size(); i++)
{
int lowest = 1000;
if(myList.get(i)<lowest)
{
myList.add(0, myList.get(i));
myList.remove(i+1);
}
}
}

This :
public void sortList() {
int lowest = 1000;
for(int i=0; i<myList.size(); i++)
{
if(myList.get(i)<lowest)
{
myList.add(0, myList.get(i));
myList.remove(i+1);
}
}
}

You simply declare lowest outside of the loop, and update it in the loop.

With the example you gave, I would move the 'lowest' declaration out of the for loop, like so:
int lowest = 1000;
for(int i=0; i<myList.size(); i++)
{
if(myList.get(i)<lowest)
{
myList.add(0, myList.get(i));
myList.remove(i+1);
}
}
That way it's not reset to 1000 with each for loop. You can then update it within the loop as needed as you would any other numeric variable.

Related

How to add JSpinner output into array and check for duplicate

I'm working on a code which has a JSpinner, which gives an output and moves it to int = n, I want to save every JSpinner output and add it into an array to check for duplicates and once found the JPanel should close itself or say you lost.
Scanner s = new Scanner(System.in);
int n = (Integer) spinner.getValue();
if (isPrime(n)) {
Input.setText(n + " is a prime number");
score++;
Highscore.setText("Score: " + score);
int[] array = new int[4];
for(int i=0; i<4;i++)
{
array[i]= (Integer) spinner.getValue();
}
for (int i=0; i < 4;i++)
{
System.out.println(array[i]);
}
Spinner output into array but it fills the whole array with one number example: [3,3,3,3].
private <T> boolean duplicate(T... array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = i + 1; j < array.length; j++)
{
if (array[i] != null && array[i].equals(array[j])) {
return true;
dispose();
}
}
}
return false;
}
Duplicate check
I tried adding the user input from the JSpinner into an array and from there to check for duplicates.
Searched Online but could'nt find anything.
This if my first post so if you need anything more you can tell me.

How do I call functions within this code? Im using the visual studio software. keep getting errors that array1 and 2 are undefined

enter image description here
Sorry im new to coding . I have searched up possible solutions for this on here but they didnt work. Im also confused on why some code appears grey compared to the rest.
https://1drv.ms/w/s!Ag8vVFKVPyOg6HeYLehGjQKdvl_3?e=QHY6t9
#include <stdio.h>
// initialised variables
int i = 0;
int count = 0;
void displayfunction(void);
int month = 0;
void highervalues(float array1[12], float array2[12]);
void highervalues(float array1[12], float array2[12]) {
for (i = 12; i > 0; i--) {
if (array2[i] > array1[i]) {
count = count + 1;
}
}
}
//Reading values for array1 and array2
void displayfunction(void) {
highervalues(array1[12] , array2[12]);
for (i = 0; i < 12; i++)
{
month = month + 1; // month increases by 1 after each input
printf_s("enter values for year 1 month %d", month);
scanf_s("%f", &array1[i]);
}
for (month = 12; month > 0; month--) {
}
for (i = 0; i < 12; i++) {
month = month + 1;
printf_s("enter values for year 2 month %d", month);
scanf_s("%f", &array2[i]);
}
}
/*comapring 2 arrays and increasing count value if there are any value in array2
are greater than array1*/
int main() {
displayfunction();
int array1[12];
int array2[12];
}
You have a fundamental misunderstanding of variable scope
int main() {
displayfunction();
int array1[12];
int array2[12];
}
Those arrays are only available in main. If you want other functions to operate on them you have to pass them as paramters to those functions. Plus they dont exist at the point where you try to call displayFunction
So change
void displayfunction(void)
to
void displayfunction(float array1[12], float array2[12])
then in main do
int main() {
int a1[12];
int a2[12];
displayfunction(a1, a2);
}
Note that I have changed the names here just to emphasise that its the not the fact that the names are the same thats important.

I am trying to display SQL result on a list control using MFC

Please, I have list control on, I want to display my query result on a list control. The program runs without error, but it does not display the SQL result on the list control.
BOOL CClassDialog::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: Add extra initialization here
CString DSN;
DSN = _T("DRIVER=SQL Server;SERVER=DESKTOP-
DICUCDS\\SQL2K14;Trusted_Connection=Yes;APP=Microsoft\x00ae Visual Studio\x00ae 2013;WSID=DESKTOP-
DICUCDS;DATABASE=School");
CDatabase aDB;
try {
aDB.OpenEx(DSN);
CRecordset aRS(&aDB);
aRS.Open(CRecordset::forwardOnly, (L"SELECT DISTINCT Myclass FROM MyFacts"));
// populate Grids
ListView_SetExtendedListViewStyle(m_classlist, LVS_EX_GRIDLINES);
// Column width and heading
m_classlist.InsertColumn(1, L"Class", LVCFMT_LEFT, -1, 1);
m_classlist.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1);
m_classlist.SetColumnWidth(0, 120);
m_classlist.SetColumnWidth(1, 200);
m_classlist.SetColumnWidth(2, 200);
while(!aRS.IsEOF())
{
CString strValue;
aRS.GetFieldValue(L"Myclass", strValue);
m_classlist.SetItemText(-1, 1, strValue);
//strValue.AddString(strValue);
aRS.MoveNext();
}
aRS.Close();
aDB.Close();
}
catch (CDBException * ex)
{
TCHAR buf[255];
ex->GetErrorMessage(buf, 255);
CString strPrompt(buf);
AfxMessageBox(strPrompt);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CClassDialog::ResetListControl()
{
m_classlist.DeleteAllItems();
int iNbrOfColumns;
CHeaderCtrl* pHeader = (CHeaderCtrl*)m_classlist.GetDlgItem(0);
if (pHeader) {
iNbrOfColumns = pHeader->GetItemCount();
}
for (int i = iNbrOfColumns; i >= 0; i--) {
m_classlist.DeleteColumn(i);
}
}
Are you sure this is right? m_classlist.SetItemText(-1, 1, strValue);
If you research the official documentation for the CListCtrl (for example, here) you will see:
CString strText;
int nColumnCount = m_myListCtrl.GetHeaderCtrl()->GetItemCount();
// Insert 10 items in the list view control.
for (int i = 0; i < 10; i++)
{
strText.Format(TEXT("item %d"), i);
// Insert the item, select every other item.
m_myListCtrl.InsertItem(LVIF_TEXT | LVIF_STATE, i, strText,
(i % 2) == 0 ? LVIS_SELECTED : 0, LVIS_SELECTED, 0, 0);
// Initialize the text of the subitems.
for (int j = 1; j < nColumnCount; j++)
{
strText.Format(TEXT("sub-item %d %d"), i, j);
m_myListCtrl.SetItemText(i, j, strText);
}
}
You are making references to SetItemText but you have not actually added any elements into the list. The code before shows an example:
// Insert the item, select every other item.
m_myListCtrl.InsertItem(LVIF_TEXT | LVIF_STATE, i, strText,
(i % 2) == 0 ? LVIS_SELECTED : 0, LVIS_SELECTED, 0, 0);
I am not saying that you have to use that specific set of paramaters. But the point is that you must insert an item into the list before you can update it's properties. Or even set the properties at the moment you add it into the list.

Roslyn - replace node and fix the whitespaces

In my program I use Roslyn and I need to replace a node with a new node. For example, if I have code like
public void Foo()
{
for(var i = 0; i < 5; i++)
Console.WriteLine("");
}
and I want to insert brackes for for statement, I get
public void Foo()
{
for(var i = 0; i < 5; i++)
{
Console.WriteLine("");
}
}
I tried to use NormalizeWhitespace, but if I use it on for statement, I get
public void Foo()
{
for(var i = 0; i < 5; i++)
{
Console.WriteLine("");
}
}
However, I'd like to have for statement formatted correctly. Any hints how to do it?
EDIT:
I solved it by using:
var blockSyntax = SyntaxFactory.Block(
SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithLeadingTrivia(forStatementSyntax.GetLeadingTrivia()).WithTrailingTrivia(forStatementSyntax.GetTrailingTrivia()),
syntaxNodes,
SyntaxFactory.Token(SyntaxKind.CloseBraceToken).WithLeadingTrivia(forStatementSyntax.GetLeadingTrivia()).WithTrailingTrivia(forStatementSyntax.GetTrailingTrivia())
);
However, the answer from Sam is also correct.
You need to use .WithAdditionalAnnotations(Formatter.Annotation), but only on the specific element you want to format. Here's an example from the NullParameterCheckRefactoring project.
IfStatementSyntax nullCheckIfStatement = SyntaxFactory.IfStatement(
SyntaxFactory.Token(SyntaxKind.IfKeyword),
SyntaxFactory.Token(SyntaxKind.OpenParenToken),
binaryExpression,
SyntaxFactory.Token(SyntaxKind.CloseParenToken),
syntaxBlock, null).WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);

Add A list Items to Combobox using Dispatcher.BeginInvoke()

I want to add a List to ComboBox through Dispatcher.BeginInvoke. But when I try to put it in a loop, only last value is loading.
private void LoadToComboBox(List<string> msg)
{
for (int i = 0; i < msg.Count; i++)
{
this.Dispatcher.BeginInvoke(() => cmbListItems.Items.Add(msg[i]));
}
}
The Dispatcher.BeginInvoke() is an asynchronous call. What is happening is that by the time you are calling your cmbListItems.Items.Add() function, it is already set to msg.Count.
Try something like this:
private void LoadToComboBox(List<string> msg)
{
this.Dispatcher.BeginInvoke(() =>
{
for (int i = 0; i < msg.Count; i++) {
cmbListItems.Items.Add(msg[i]);
}
});
}