-2
    using System;

class MainClass {
  public static void Main (string[] args) {
   
   int n1;

   while (n1 <= 0) {
     n1 = int.Parse(Console.ReadLine());
   }
   }
  }

the Console keeps saying "use of unassigned local variable" and when i try it with 'do While' it just doesn't repeat the code inside. I'm really new to coding and i would really appreciate some help.

1 Answers1

0

Change

int n1;

To

int n1 = 0;

The compiler is complaining because you didn't give n1 a value before you used it in the while loop. Making it zero (or less) ensures the while loop will run to ask the user

At some point you might want to ask the user for another number. Rather than repeat this code, make a method out of it. Make the method return an int and take a string question to print out so you can vary what you ask. Have the while loop print the question and then read the answer. Consider also using int.TryParse so that if the user enters non numbers it doesn't crash the program

Final point, your question title says "keep asking until the user enters a negative number" but while(n1<=0) doesn't do this, it does the opposite and will "keep asking while the user enters negative numbers" (i.e. "until the user enters a positive number")

Rafalon
  • 4,450
  • 2
  • 16
  • 30
Caius Jard
  • 72,509
  • 5
  • 49
  • 80