I m trying to take an input from the user through my console in golang by using fmt.Scanln(). It is working fine under normal circumstances. However, whenever I take input in a loop, the inputs are correct in the first iteration but during the next iterations of a loop, an extra smiley is added in the front of the received string. I don't know what the problem is. Will be very thankful if anyone proposes some solution.
func (a *Block) fillBlock() {
fmt.Println("Block Details:")
fmt.Print("Enter Block Name: ")
fmt.Scanln(&a.Data)
for i := 0; i < Students; i++ {
fmt.Print(i, "Enter Student Roll# ")
fmt.Scanln(&a.Grades[i].Rollno)
fmt.Print(i, "Enter Student Grade# ")
fmt.Scanln(&a.Grades[i].Grade)
}
fmt.Println("\nInput Data:")
fmt.Println("Data: ",a.Data)
// Iterating over each student
for i := 0; i < Students && (a.Grades[i].Rollno != "" && a.Grades[i].Grade != ""); i++ {
fmt.Println("Rollno: " + string(i) + a.Grades[i].Rollno)
fmt.Println("Grade: " + string(i) + a.Grades[i].Grade)
}
}
This is wrong:
fmt.Println("Rollno: " + string(i) + a.Grades[i].Rollno)
Instead, use
fmt.Println("Rollno: " + strconv.Itoa(i) + a.Grades[i].Rollno)
Or, better:
fmt.Printf("Rollno: %d %s\n",i a.Grades[i].Rollno)
Related
As a JS dev jumping right into Go, I've hit a deadend trying to print multiple descriptions if the length of commits is more than one. I don't have much time left to complete this and I've been searching for longer than I wish. Any idea on how I could either restructure this or get this to work?
case github.PushPayload:
push := payload.(github.PushPayload)
repo := push.Repository.Name
owner := push.Repository.Owner.Login
ownerUrl := push.Repository.Owner.HTMLURL
ownerAvatar := push.Repository.Owner.AvatarURL
ref := push.Ref
refTrim := strings.Replace(ref, "/.*/", "", -1)
commits := push.Commits
for _, commit := range commits {
message := commit.Message
url := commit.URL
id := commit.ID
idShort := id[0:6]
committer := commit.Committer.Username
description := "[`" + idShort + "`](" + url + ") " + message + " - " + committer
}
if len(commits) == 1 {
discord.ChannelMessageSendEmbed(channelID, &discordgo.MessageEmbed{
Color: 0x00B1FF,
Description: description,
Title: "[" + repo + ":" + refTrim + "] 1 new commit! 🔧",
Author: &discordgo.MessageEmbedAuthor{
Name: owner,
URL: ownerUrl,
IconURL: ownerAvatar,
},
})
} else {
discord.ChannelMessageSendEmbed(channelID, &discordgo.MessageEmbed{
Color: 0x00B1FF,
Description: description,
Title: "[" + repo + ":" + refTrim + "] " + string(len(commits)) + " new commits! ⚒️",
Author: &discordgo.MessageEmbedAuthor{
Name: owner,
URL: ownerUrl,
IconURL: ownerAvatar,
},
})
}
PS: Ignore string(len(commits)) I know that's incorrect, I'm stuck trying to figure this out first and foremost. Also ignore: refTrim := strings.Replace(ref, "/.*/", "", -1), which isn't correct either.
you have to declare description variable before the loop and then add commit descriptions to it as below inside the loop.
Note: I emitted other code blocks here.
description := ""
for _, commit := range commits {
description = description + "commit description here"
}
description += "commit description here" also can be used inside the loop. But I have added above to more understanding.
I'm trying to make a function that reads a collection of data from JSON file, but I keep receiving this error
panic: runtime error: index out of range
and it's not importing all the data from json file,
I think there's something wrong in my for loop.
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// initialize Int array
var interns Int
// initialize Com array
var companies Com
// unmarshal byteArray
json.Unmarshal(byteValue, &interns)
json.Unmarshal(byteValue, &companies)
// iterate through every student within our students array and
// print out the student ID, first & last name
for i := 0; i < len(interns.Int); i++ {
fmt.Println("Student first name: " + interns.Int[i].Name.FirstName)
fmt.Println("Student last name: " + interns.Int[i].Name.LastName)
fmt.Println("Company name: " + companies.Com[i].CompanyName)
fmt.Println("Company email address: " + companies.Com[i].CompanyEmail + "\n")
}
Because you are using len of Int array to iterate Com array while len of Com array is different so the program will panic when iterate to an index that Com array is not available
//Program panics if [i] is not valid
fmt.Println("Company name: " + companies.Com[i].CompanyName)
fmt.Println("Company email address: " + companies.Com[i].CompanyEmail + "\n")
Split the loop into two to iterate and it will works
// iterate Int array
for i := 0; i < len(interns.Int); i++ {
fmt.Println("Student first name: " + interns.Int[i].Name.FirstName)
fmt.Println("Student last name: " + interns.Int[i].Name.LastName)
}
// iterate Com array
for i := 0; i < len(companies.Com); i++ {
fmt.Println("Company name: " + companies.Com[i].CompanyName)
fmt.Println("Company email address: " + companies.Com[i].CompanyEmail + "\n")
}
I’ve the following code which needs to get int value and add it to a string with string suffix. E.g.
At start I'm getting this
"fds data "
After the if statement it should like this
"fds data 10 M"
This is the code:
ltrCfg := "fds data "
if len(cfg.ltrSharedDicts) > 0 {
ltrCfg += strconv.Itoa(cfg.ltrSharedDicts["c_data"])
ltrCfg += "M"
} else {
ltrCfg += "10M"
}
out = append(out, ltrCfg)
ltrCert := “fds data "
if len(cfg.ltrSharedDicts) > 0 {
ltrCert += strconv.Itoa(cfg.ltrSharedDicts["d_data"])
ltrCert += "M"
} else {
ltrCert += “20M"
}
out = append(out, ltrCert)
The code is working but I wonder for the first fork of the if statement
if len(cfg.ltrSharedDicts) > 0 {
ltrCfg += strconv.Itoa(cfg.ltrSharedDicts["c_data"])
ltrCfg += "M"
Is there a better way to achieve it?
For readability, I would write:
cd, ok := cfg.ltrSharedDicts["c_data"]
if !ok {
cd = 10
}
out = append(out, fmt.Sprintf("fds data %dM", cd))
It is necessary to create a program that will on the basis of input N car number plate ( eg . " KR 635 B " ) to count the number of vehicles from individual places . At the end of the program to print the amount of vehicles coming from a particular place , and the number of vehicles whose region is not recognized . Places that recognizes :
KR - Karlovac
BJ Bjelovar ...
I need a piece of code that identifies the first part of plate lets say: " KR " , because when I use if ( input = " KR " );
then recognizes only if I enter " KR " and not the entire registration .
You can use the StartsWith method to check the beginning of a string. Example:
if (plate.StartsWith("KR")) {
...
}
If you are checking for muliple vales, you might want to get that part of the string as a separate string. You can get the first two characters:
string region = plate.Substring(0, 2);
Or the characters up to the first space:
string region = plate.Substring(0, plate.IndexOf(' '));
bool again = true;
//variable
int bje = 0;
int zgr = 0;
int spt = 0;
int vzn = 0;
int npo = 0;
//petlja za y/n
while(again)
{
// program unutar loopa
Console.WriteLine("Unesite registarsku oznaku: ");
string unos = Console.ReadLine();
if (unos == "bj")
//
bje++;
else if (unos == "zg")
//
zgr++;
else if (unos == "sp")
//
spt++;
else if (unos == "vz")
//
vzn++;
else
npo++;
Console.WriteLine("Bjelovar: " + bje);
Console.WriteLine("zagreb: " + zgr);
Console.WriteLine("split: " + spt);
Console.WriteLine("varazdin: " + vzn);
Console.WriteLine("Nepoznato: " + npo);
// za ponovan unos loop
Console.WriteLine();
Console.WriteLine("Ponovni unos? (Da/Ne)");
string YN = Console.ReadLine();
while (YN != "Y" && YN != "N" )
{
Console.WriteLine("Wrong entry. Again? (Y/N)");
YN = Console.ReadLine();
}
if (YN == "n")
{
again = false;
}
}
See i need those "if statments" changed for that word recognition and just done that is under the if statment.
if (question == "What is the market?") {
post = "You can find it # " + store.market + ".";
response.sendfile("src/index.html");
}
I got a input text box that when a user writes Name? The computer says "My name is (me.name).
This code is in the server.js
But what i would like to do.. If a user write Name? like 3 times or so. it will come up a error that says You have asked me to many times or something in that way.
i tryd with for (var i=0;i < 3; ++i)
textbox = "Error"
But i cant get it to work. Im not the best programmer but im trying. Can it be done with a simple loop or do i need something more?
Try this:
var n=0, a=0, d=0;
if (question == "Name?") {
if(n<3)
answ = "I am " + me.name + ".";
else
answ = "You asked me that " + n + " times.";
response.sendfile("public/index.html");
n++;
} else if (question == "Age?") {
if(a<3)
answ = "I am " + me.age + " years old.";
else
answ = "You asked me that " + a + " times.";
response.sendfile("public/index.html");
a++;
} else if (question == "Do you have a name?") {
if(d<3)
answ = "My name is:" + me.Name";
else
answ = "You've asked me that " + d + " times.";
response.sendfile("public/index.html");
d++;
}
Basically you're keeping track in a,n, and d how many times they asked the question, and changing you're response accordingly.