Why this simple program doesn't work?
using System;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
string name;
string all;
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("enter name");
name = Console.ReadLine();
Console.WriteLine(name);
all =string.Concat(all, name);
}
Console.WriteLine("all the names are ");
// Console.WriteLine(s1);
}
}
}
It gives an error and does not cascade all strings?
Thanks
You need to initialize the value of variable all. Here's a sample that works:
static void Main(string[] args)
{
string name;
string all = null;
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("enter name");
name = Console.ReadLine();
Console.WriteLine(name);
all = string.Concat(all, name);
}
Console.WriteLine("all the names are ");
Console.WriteLine(all);
}
Note, however, that there are no separators added beween the three names. If someone would enter "one" and "two" and "three", for instance, then the output would be "onetwothree". Maybe you want something different, maybe not.
Related
private string GenerateID()
{
}
private void auto()
{
AdmissionNo.Text = "A-" + GenerateID();
}
with prefix of A like below
A-0001
A-0002 and so on .
You can use below code.
private string GenerateId()
{
int lastAddedId = 8; // get this value from database
string demo = Convert.ToString(lastAddedId + 1).PadLeft(4, '0');
return demo;
// it will return 0009
}
private void Auto()
{
AdmissionNo.Text = "A-" + GenerateId();
// here it will set the text as "A-0009"
}
Look at this
public class Program
{
private static int _globalSequence;
static void Main(string[] args)
{
_globalSequence = 0;
for (int i = 0; i < 10; i++)
{
Randomize(i);
Console.WriteLine("----------------------------------------->");
}
Console.ReadLine();
}
static void Randomize(int seed)
{
Random r = new Random();
if (_globalSequence == 0) _globalSequence = r.Next();
Console.WriteLine("Random: {0}", _globalSequence);
int localSequence = Interlocked.Increment(ref _globalSequence);
Console.WriteLine("Increment: {0}, Output: {1}", _globalSequence, localSequence);
}
}
Whether it is an windows application or not is IMHO not relevant. I'd rather care about thread safety. Hence, I would use something like this:
public sealed class Sequence
{
private int value = 0;
public Sequence(string prefix)
{
this.Prefix = prefix;
}
public string Prefix { get; }
public int GetNextValue()
{
return System.Threading.Interlocked.Increment(ref this.value);
}
public string GetNextNumber()
{
return $"{this.Prefix}{this.GetNextValue():0000}";
}
}
This could easily be enhanced to use the a digit count. So the "0000" part could be dynamically specified as well.
Whenever I run this code, it works pretty smoothly, until the while loop runs through once. It will go back and ask for the name again, and then skip String b = sc.nextLine();, and print the next line, instead.
static Scanner sc = new Scanner(System.in);
static public void main(String [] argv) {
Name();
}
static public void Name() {
boolean again = false;
do
{
System.out.println("What is your name?");
String b = sc.nextLine();
System.out.println("Ah, so your name is " + b +"?\n" +
"(y//n)");
int a = getYN();
System.out.println(a + "! Good.");
again = askQuestion();
} while(again);
}
static public boolean askQuestion() {
System.out.println("Do you want to try again?");
int answer = sc.nextInt();
if (answer == 1) {
return true;
}
else {
return false;
}
}
static int getYN() {
switch (sc.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
}
Also, I'm trying to create this program in a way that I can ask three questions (like someone's Name, Gender, and Age, maybe more like race and whatnot), and then bring all of those answers back. Like, at the very end, say, "So, your name is + name +, you are + gender +, and you are + age + years old? Yes/No." Something along those lines. I know there's a way to do it, but I don't know how to save those responses anywhere, and I can't grab them since they only occur in the instance of the method.
Don't try to scan text with nextLine() AFTER using nextInt() with the same scanner! It may cause problems. Open a scanner method for ints only...it's recommended.
You could always parse the String answer of the scanner.
Also, using scanner this way is not a good practice, you could organize questions in array an choose a loop reading for a unique scanner instantiation like this:
public class a {
private static String InputName;
private static String Sex;
private static String Age;
private static String input;
static Scanner sc ;
static public void main(String [] argv) {
Name();
}
static public void Name() {
sc = new Scanner(System.in);
String[] questions = {"Name?","Age","Sex?"};//
int a = 0;
System.out.println(questions[a]);
while (sc.hasNext()) {
input = sc.next();
setVariable(a, input);
if(input.equalsIgnoreCase("no")){
sc.close();
break;
}
else if(a>questions.length -1)
{
a = 0;
}
else{
a++;
}
if(a>questions.length -1){
System.out.println("Fine " + InputName
+ " so you are " + Age + " years old and " + Sex + "." );
Age = null;
Sex = null;
InputName = null;
System.out.println("Loop again?");
}
if(!input.equalsIgnoreCase("no") && a<questions.length){
System.out.println(questions[a]);
}
}
}
static void setVariable(int a, String Field) {
switch (a) {
case 0:
InputName = Field;
return;
case 1:
Age = Field;
return;
case 2:
Sex = Field;
return;
}
}
}
Pay attention on the global variables, wich stores your info until you set them null or empty...you could use them to the final affirmation.
Hope this helps!
Hope this helps!
using System;
namespace rummykhan
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Test t1 = new Test();
}
}
}
class Test
{
public int first;
public int second;
}
}
im trying to make 100 objects but i wish these objects are named automatically using some random string. im unable to figure out.. thanx for help in advance..
EDIT
Looking at my own question after a year, actually i was looking for a way by which i was able to create object by my own chosen name. e.g.
string tmp = "obj1";
var tmp = new Foo();
i was thinking that someway obj1 value may kick in and i could call my variable using obj1, which is totally moronic.
Just store the objects in a List.
example:
List<Test> tests = new List<Test>();
for (int i = 0; i < 100; i++)
{
tests.Add(new Test());
}
Currently your code will destroy t1 after each iteration of the loop. you could do something like this to preserve 100 coppies of test in memory
using System;
namespace rummykhan
{
class Program
{
static void Main(string[] args)
{
List<Test> lstClasses = new List<Test>();
for (int i = 0; i < 100; i++)
{
lstClasses.Add(new Test());
}
}
}
class Test
{
public int first;
public int second;
}
}
write like this.
Test[] dynamic = new Test[100];
for (int i=0; i< 100; i++)
{
dynamic[i] = new Test();
}
I am very much a beginner at Java programming I'm in the middle of writing a program that sorts names in alphabetical order. How can I code an "if" statement so that it only accepts alphabetical characters? In my code I have "if (in.hasNext() != String)" which is clearly wrong, but im just trying anything now. Here is my code.
import java.util.*;
public class AlphaOrder
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
System.out.println("Enter a name, enter \"Sort\" to sort the names alphabetically, enter \"Quit\" to end: ");
Scanner in = new Scanner(System.in);
while (in.hasNext())
{
names.add(in.next());
if (in.hasNext("Sort"))
{
System.out.println("The names in alphabetical order are: " + names);
}
if (in.hasNext("Quit"))
{
System.out.println("This Program has stopped.");
}
if (in.hasNext() != String)
{
System.out.println("Please enter only alphabetical characters.");
}
}
}
}
1) You probably want to change your logic a bit:
import java.util.*;
public class AlphaOrder
{
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
System.out.println("Enter a name, enter \"Sort\" to sort the names alphabetically, enter \"Quit\" to end: ");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String sLine = in.next ();
if (sLine.equals ("Sort")) {
System.out.println("The names in alphabetical order are: " + names);
doSort ();
}
if (sLine.equals ("Sort")) {
System.out.println("This Program has stopped.");
doExit ();
}
if (!isAlpha (sLine)) {
System.out.println("Please enter only alphabetical characters.");
continue;
}
names.add(sLine);
}
}
}
2) There are lots of ways to check "isAlpha()". I would look at "regular expressions":
http://www.vogella.com/articles/JavaRegularExpressions/article.html
3) Here's one "naive" implementation:
boolean isAlpha (String s)
{
String s2 = s.toUpperCase();
for (int i = 0; i < s2.length(); i ++) {
if (s2.charAt(i) < 'A' || s2.charAt(i) > 'Z')
return false;
}
return true;
}
Just a quick one, I want to continuously add digits to a string. The first thing I did is to remove the last character of the string, now digits starting from 1 should be continuously added to it. The snippet is below:
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
class Class1
{
public static String source = "#box1";
static string dest;
public static void Main(String[] args)
{
try
{
if (source.Length > 0)
{
dest = source.Substring(0, source.Trim().Length - 1);
}
Console.WriteLine(dest);
Console.ReadLine();
}
catch(Exception e){ e.ToString(); }
}
}
}
The output should look like this:
#box1
#box2
#box3
#box4
#box5
and so on.....
If you have a max :
for (int i = 1; i <= max; i++)
{
Console.WriteLine("#Box" + i);
}
With no maximum, but that is not a good idea:
count = 1
while (1 > 0)
{
Console.WriteLine("#Box" + count);
count++;
}
You can also do no max with the for loop, but I just wanted to give you more options in loops.
Information on loops http://csharp.net-tutorials.com/basics/loops/
Thanks, guys,
I got it solved this way. Sorry that I have to post the real code I'm using it for. I'm much occupied than to edit the pseudo code again.
public static String RegistrationFailedPanels = UserValidations.RegistrationFailedPanels;
public static String CloseFailedPanel = UserValidations.CloseFailedPanel;
static int count = 0;
public void LoginFailed(String InputConstant, String FailedLogin)
{
++count;
InputConstant = RegistrationFailedPanels.Substring(0, RegistrationFailedPanels.Trim().Length-1);
FailedLogin = CloseFailedPanel.Substring(0, CloseFailedPanel.Trim().Length-1);
new LoginValidations(driver).WaitForATime(InputConstant +count);
driver.FindElement(By.CssSelector(FailedLogin +count)).Click();
}