Error using while loop in java - c#

I'm a newbie in java from c# background. In c# when i want to make sure the user cannot does null data in the Console Application i make a loop like
static void Main(string[] args)
{
Console.WriteLine("Enter your name : ");
string name = Console.ReadLine();
while (name == "")
{
Console.WriteLine("Enter your name : ");
name = Console.ReadLine();
}
}
Now I want to implement the same in java. I am using
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter your name : ");
String pname;
Scanner scan=new Scanner(System.in);
pname=scan.next();
while ("".equals(pname))
{
System.out.println("Enter your name : ");
pname=scan.next();
}
}
But when a null value is entered, the output doesn't show the Enter your name again it only moves one line waiting for a value to be entered.
What am i doing wrong?

Try using nextLine() instead. next() only gets up to the next space, nextLine() gets the next linebreak. I vaguely remember this from my java class in college.

while ("".equals(pname))
{
System.out.println("Enter your name : ");
pname=scan.next();
}
Instead use
while (pname.equals(""))
{
System.out.println("Enter your name : ");
pname=scan.next();
}
If you look at javadocs for equals, you will know what i am talking about.
And also a hint, i started using buffred reader when i started coding in java

You can use:
while (pname == null || "".equals(pname))
{
System.out.println("Enter your name : ");
pname = scanner.nextLine();
}

I also faced similar type of problem once. The problem is not in while loop. It is in reusing same Scanner object. Try creating new Scanner object each time.
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter your name : ");
String pname;
Scanner scan=new Scanner(System.in);
pname=scan.next();
while (pname.equals(""))
{
System.out.println("Enter your name : ");
scan = new Scanner(System.in);
pname=scan.next();
}
}

Related

c# - While loop coding theory, making a login and register sysem

I have coded a system based of the theory that while loops can work anywhere in a system. So once a while loop has been passed by it can run. Here is a simple version of my code:
using System;
namespace test___login
{
class Program
{
static void Main(string[] args)
{
string location = "homepage";
while (location.Equals("Homepage", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("homepage");
Console.WriteLine("WHere to now: ");
location = Console.ReadLine();
}
while (location.Equals("login", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("login");
Console.WriteLine("Where to now: ");
location = Console.ReadLine();
}
}
}
}
So I assumed that once the variable changes from "login" to "homepage" in the second while loop, would mean the first while loop would run once again. Is my theory on how the code works wrong or am i simply not typing the right thing. I just started last week so sorry for the basic question
It wouldn't run again, because the code has already executed past that line so unless you call it again, the next thing down the line will execute, in your case nothing - this is called procedural programming.
Why don't you make one while loop, and a switch statement instead.
bool run = true;
while (run)
{
Console.WriteLine("WHere to now: ");
string location = Console.ReadLine();
switch(location.ToLower()){
case "homepage":
Console.WriteLine("HomePage");
break;
default:
run = false;
break;
}
}
Not with the way you have your code currently structured. It will exit the application. You need to surround all of that with one more while loop, which can be similar to your other loops. See below:
using System;
namespace test___login {
class Program
{
static void Main(string[] args)
{
string location = "homepage";
while (!location.ToUpper().Equals("EXIT"))
{
while (location.Equals("Homepage", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("homepage");
Console.WriteLine("WHere to now: ");
location = Console.ReadLine();
}
while (location.Equals("login", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("login");
Console.WriteLine("Where to now: ");
location = Console.ReadLine();
}
}
}
}
}

does not contain a static main method for suitable entry point

Keep getting the error message does not contain a static main method for suitable entry point. Would anyone be able to explain this error to me and possibly help me fix it? Thanks. New to C#
{
class Authenticator
{
private Dictionary<string, string> dictionary = new Dictionary<string, string>();
public void IntialValues()
{
dictionary.Add("username1", "password1");
dictionary.Add("username2", "password2");
dictionary.Add("username3", "password3");
dictionary.Add("username4", "password4");
dictionary.Add("username5", "password5");
}
public bool Authenticate(Boolean authenticated)
{
Console.WriteLine("Please enter a username");
string inputUsername = Console.ReadLine();
Console.WriteLine("Please enter your password");
string inputPassword = Console.ReadLine();
if (dictionary.ContainsKey(inputUsername) && dictionary[inputUsername] == inputPassword)
{
authenticated = true;
}
else
{
authenticated = false;
}
return authenticated;
}
}
}
If all of your code consists only of the block shown above then the error is more than clear. A Main method is required in your program.
The Main method is, by convention, the default point where the code starts executing. You can get here a more in depth explanation
So, for example, you need to add the following code
class Authenticator
{
static void Main(string[] args)
{
Authenticator au = new Authenticator();
au.InitialValues();
if(au.Authenticate())
Console.WriteLine("Authenticated");
else
Console.WriteLine("NOT Authenticated");
Console.WriteLine("Press Enter to end");
Console.ReadLine();
}
// Move the boolen variable inside the method
public bool Authenticate()
{
bool authenticated = false;
Console.WriteLine("Please enter a username");
string inputUsername = Console.ReadLine();
Console.WriteLine("Please enter your password");
string inputPassword = Console.ReadLine();
if (dictionary.ContainsKey(inputUsername) && dictionary[inputUsername] == inputPassword)
{
authenticated = true;
}
else
{
authenticated = false;
}
return authenticated;
}
}
By the way, you should remove the parameter passed in input to the Authenticate method. You should declare it as an internal variable, set it depending on the outcome of the check and return it.
However, you could remove that variable altogether writing
....
return (dictionary.ContainsKey(inputUsername)) &&
(dictionary[inputUsername] == inputPassword)
}
All executable programs must have a Main function somewhere in the project that is compiled to the exe.
If you just want to compile a class (eg to a dll) then you have to set that as the "project type" in visual studio.
The easiest way is to create a new project, but select class library as project type, and then paste your code in there. Alternatively you can use the command line to compile a file to a dll like so:
c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /target:library Authenticator.cs

Strange behaviour with clipboard in C# console application

Consider this small program:
class Program
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Please copy something into the clipboard.");
WaitForClipboardChange();
Console.WriteLine("You copied " + Clipboard.GetText());
Console.ReadKey();
}
static void WaitForClipboardChange()
{
Clipboard.SetText("xxPlaceholderxx");
while (Clipboard.GetText() == "xxPlaceholderxx" &&
Clipboard.GetText().Trim() != "")
Thread.Sleep(90);
}
}
I run it, and I copy a string from Notepad. But the program just gets an empty string from the clipboard and writes "You copied ".
What's the problem here? Is there something that makes clipboard access behave weirdly in a console application?
This is Windows 7 SP1 x86, .NET 4 Client Profile.
Use this function
static string GetMeText()
{
string res = "starting value";
Thread staThread = new Thread(x =>
{
try
{
res = Clipboard.GetText();
}
catch (Exception ex)
{
res = ex.Message;
}
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
return res;
}
In this line:
Console.WriteLine("You copied " + Clipboard.GetMeText());
The problem is that the clipboard only works with certain threading models (ApartmentState.STA) so you have to make a new thread and give it that model this code does that.
I can reproduce the problem with your code on .NET 4 Client Profile, but when I switch to .NET 4 or 4.5 it works as expected.
However, the ClipBoard.GetText() manual states:
Use the ContainsText method to determine whether the Clipboard contains text data before retrieving it with this method.
I take that as an instruction, not a suggestion, so, try this:
class Program
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Please copy something into the clipboard.");
WaitForClipboardChange();
Console.WriteLine("You copied " + Clipboard.GetText());
Console.ReadKey();
}
static void WaitForClipboardChange()
{
Clipboard.Clear();
while (!Clipboard.ContainsText())
Thread.Sleep(90);
}
}
It does show the copied text, although I must say this lets my system hang horribly when I copy some text.
This works for me:
static void Main(string[] args)
{
Console.WriteLine("Please copy something into the clipboard.");
string text = WaitForClipboardChange();
Console.WriteLine("You copied " + text);
}
static string WaitForClipboardChange()
{
string placeholderText = "xxPlaceholderxx";
Clipboard.SetText(placeholderText);
string text = null;
do
{
Thread.Sleep(90);
text = Clipboard.GetText();
}
while (string.IsNullOrWhiteSpace(text) || text.Equals(placeholderText));
return text;
}
Your current code explicitly waits for first change from "xxPlaceholderxx" to anything (your condition is "not particular string AND not empty" which turns false as soon as string changes from "xxPlaceholderxx" to anything, including ""):
while (Clipboard.GetText() == "xxPlaceholderxx"
&& Clipboard.GetText().Trim() != "")
You probably want || (or) instead of and:
// assuming System.Windows.Forms.Clipboard
static void WaitForClipboardChange()
{
Clipboard.SetText("xxPlaceholderxx");
while (Clipboard.GetText() == "xxPlaceholderxx"
|| string.IsNullOrWhiteSpace(Clipboard.GetText()))
Thread.Sleep(90);
}

C# - Using Settings

I've recently written this short application in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checker
{
class Program
{
static void Main(string[] args)
{
Properties.Settings.Default.Save();
Program re = new Program();
re.next();
}
public void next()
{
Console.WriteLine("Have you already entered name?");
int ch = int.Parse(Console.ReadLine());
if (ch == 0)
{
Console.WriteLine("What is your name?");
String name = Console.ReadLine();
Console.WriteLine("Thank you!");
Console.ReadKey();
}
Console.WriteLine("Your name is " + name);
}
}
}
Now, I've created a settings file, and created a "name" variable there, with the "String" type.
The scope of it is "User".
So I want it to load the "name" variable with the properties line, but I can't even compile the program because of this error:
Error 1 The name 'name' does not exist in the current context
How can I solve it?
The answer to your problem becomes a little more apparent when you indent:
String name;
if (ch == 0)
{
Console.WriteLine("What is your name?");
name = Console.ReadLine();
Console.WriteLine("Thank you!");
Console.ReadKey();
}
else
{
name = Settings.Default.name;
}
Console.WriteLine("Your name is " + name);
Now you can see that you defined a String called name inside the if-block, thus using it in the Console.WriteLine outside the if-block is out of scope! Move that last Console.WriteLine inside the if-block to solve the scoping issue.
Edit: Based on your comment, your code needs a bit more logic to attain what you're trying to do. I updated my snippet above to accomplish what I think you're trying to do.
You declared that variable inside the if block.
As the compiler is trying to tell you, it doesn't exist outside that block.
If you want to use your Settings class, write Settings.Default.Name.
Your intentions are a bit unclear, but to me it seems as though you are trying to have the application display the name of the user if it has already been saved or ask for it if it hasn't. If that is the case, something like this should work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checker
{
class Program
{
static void Main(string[] args)
{
Program re = new Program();
re.next();
Properties.Settings.Default.Save();
}
public void next()
{
String name = Settings.Default.name;
if (String.IsNullOrEmpty(name))
{
Console.WriteLine("What is your name?");
name = Console.ReadLine();
Settings.Default.name = name;
Console.WriteLine("Thank you!");
Console.ReadKey();
}
else
{
Console.WriteLine("Your name is " + name);
}
}
}
}
In your OP, your settings were not being saved before the program exited nor were you setting the name property.

How to save contacts in an address book and list them?

I am working on making an address book in C# 2008. I need to be able to save the contacts and then later display them when the user asked for it. I also need to handle an exception when someone enters an unknown color when writing the person's favorite color.
This is my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab02
{
class Program
{
static void Main(string[] args)
{
Contact contact = new Contact();
Console.WriteLine("Please enter the person's name:");
contact.Name = Console.ReadLine();
Console.WriteLine("Please enter the person's e-mail address:");
contact.Email = Console.ReadLine();
Console.WriteLine("Please enter the person's favorite color:");
string tempColor = Console.ReadLine();
contact.Favoritecolor = (System.Drawing.KnownColor)(Enum.Parse(typeof(System.Drawing.KnownColor), tempColor));
try
{
}
catch
{
}
finally
{
Console.WriteLine("This is an unknown color. Please enter a known color");
}
}
class Color
{
enum clr
// This is a list of colors for the user to pick from.
{
Red,
Green,
Blue,
Yellow,
Purple,
Brown,
Black,
Crimson,
White,
Turqoise,
Orange,
Cyan,
Pink,
Gold,
Silver,
Bronze,
Gray,
Indigo,
Rust
}
}
}
class Contact
{
//This string represents the person's Name.
public string Name { get; set; }
//This string represents the person's Email.
public string Email { get; set; }
public System.Drawing.KnownColor Favoritecolor
{
get;
set;
}
}
}
Can anyone help me please?
Why not list all colors that the user can pick, with the Enum Value, then ask them to enter a number, try and convert it to an enum,then store it. If it fails to convert, let them know it's invalid.
Here's a little snippet to help. You'll need to make your enum public however.
Console.WriteLine("Here are a list of colors:");
foreach(Color.clr item in Enum.GetValues(typeof(Color.clr)))
{
Console.WriteLine(string.Format("{0} - {1}",(int)item,item.ToString()));
}
Console.WriteLine("Please choose your color");
string colorInput = Console.ReadLine();
int colorValue = 0;
if(!int.TryParse(colorInput, out colorValue))
{
Console.WriteLine(string.Format("{0} is not a valid number",colorInput));
return;
}
// This will give an error if they've typed a number that wasn't listed
// So need to add a bit of checking here
Color.clr tempColor = (Color.clr)colorValue;
// Your code here
You can also use the Reflection:
public static class ColorInfo
{
private static readonly PropertyInfo[] PropertiesInfo;
static ColorInfo()
{
PropertiesInfo = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static);
}
public static bool TryGetKnownColorFromString(string colorName, out KnownColor knowColor)
{
if (String.IsNullOrEmpty(colorName))//if wrong color name
{
knowColor = KnownColor.ActiveBorder;
return false;
}
try
{
foreach (PropertyInfo property in PropertiesInfo)
{
if (property.Name.Equals(colorName, StringComparison.InvariantCultureIgnoreCase))
{
knowColor = ((Color)property.GetValue(null, null)).ToKnownColor();
return true;
}
}
}
catch (Exception exc)
{
//catch GetValue & Equals methods exceptions
if (!(exc is ArgumentException || exc is TargetException ||
exc is TargetParameterCountException ||
exc is MethodAccessException ||
exc is TargetInvocationException))
{
//throw exc; //We don't want to lose information from StackTrace
throw;
}
}
knowColor = KnownColor.ActiveBorder;
return false;
}
}
Simply test:
string[] colors = { "reD", "AzUre", "Blue", "BlueViollet" };
KnownColor knowColor;
foreach (String color in colors)
{
if (ColorInfo.TryGetKnownColorFromString(color, out knowColor))
{
Console.WriteLine(knowColor.ToString());
}
else
{
Console.WriteLine("Color: {0} - not found !", color);
}
}
Output:
Red
Azure
Blue
Color: BlueViollet - not found !
Helpfull usings:
using System;
using System.Drawing;
using System.Reflection;
are you going to display them in the console app, Form App, does it need to persist the data or just hold in memory for the lifetime of the app, is your class "Contact" serializable
For simplicity sake and since this is homework make your class Contact Serializable
[Serializable]
public class Contact
{}
and use Binary serialization, I'm not going to write it all here but its fairlysimple look up Binary serialization and binaryformaters which can write a stream to disk for each contact or a list of contacts if you like.
then if this is in the console app make a readline that accepts a "List" command and hits a method that iterates them and displays the properties for each contact.
Thats as far as I will go for writing your homework unless you pay me
Okay so this line:
contact.Favoritecolor = (System.Drawing.KnownColor)(Enum.Parse(typeof(System.Drawing.KnownColor), tempColor));
Is where you are taking the value of color entered by the user, and parsing it into a known color, correct?
Seems like thats where you might run into problems. I'd see what type of exceptions can be thrown with that line, and properly handle them.
What happens if someone enters "rED" in the commandline? Should that thrown an exception? In your code example, will it throw an exception?
Additionally, you have a custom Color Class, with an enum type called "clr", but in your code, you're parsing your enum to the System.Drawing.KnownColor type. I would nix the custom class and use the built in type.
The parsing gets moved into the try block, the catch block (which catches the exception) tells the user they need to enter something known. The finally block isn't required, so was removed:
try
{
contact.Favoritecolor = (System.Drawing.KnownColor)(Enum.Parse(typeof(System.Drawing.KnownColor), tempColor));
}
catch(ArgumentException)
{
Console.WriteLine("This is an unknown color. Please enter a known color");
}
The next part is that you need a loop until a valid colour has been entered
bool isValidColour = false;
while (!isValidColour)
{
Console.WriteLine("Please enter the person's favorite color:");
string tempColor = Console.ReadLine();
try
{
contact.Favoritecolor = (System.Drawing.KnownColor)(Enum.Parse(typeof(System.Drawing.KnownColor), tempColor));
isValidColour = true;
}
catch(ArgumentException)
{
Console.WriteLine("This is an unknown color. Please enter a known color");
}
}
The above will keep looping around until a valid colour is entered.
I hope this helps.

Categories