在同一行上打印多行字符串 [英] Print multi-line strings on same line

查看:125
本文介绍了在同一行上打印多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说的是什么。我有一个骰子程序,它打印一个骰子IE

  ------ 
| |
| |
| 1 |
------

我希望能够打印多个骰子,所以它看起来像这样:

  ------ ------ 
| | | |
| | | |
| 1 | | 3 |
------ ------

我试过 fmt.Print ,但仍然会将它们打印在彼此之下。我正在考虑创建一个函数,它打印每个对象的顶部行,但我无法弄清楚如何做到这一点。任何想法?

解决方案

这需要打印。这些数字是随机的1和6(含)之间。骰子的数量作为命令行参数。所以在我的情况下./roll 6打印6个骰子,随机数字最多6个。

 包主

$ b $ f
$ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
func main(){
numDice:= 1

if len(os.Args)> 1 {$ B $璧,ERR:!= strconv.Atoi(os.Args [1])$ ​​B $ B如果犯错=零{
fmt.Println(ERR)
}
numDice = I
}

种子:= rand.NewSource(time.Now()UnixNano()。)
randomNumber:= rand.New(种子)

die:= [] string {
------,
| |,
| |,
| | ,
------,
}

for i:= 0;我< 5; i ++ {
for j,n:= 0,numDice; j< N; J ++ {
如果我== 3 {
fmt.Printf( |%d |,randomNumber.Intn(5)1)
}否则{
fmt.Print (die [i])
}
}
fmt.Println()
}
}


what the title says. I have a dice program, and it prints a dice IE

 ------
|      |
|      |
|     1|
 ------

I want to be able to print multiple dice, so it looks like this:

 ------     ------
|      |   |      |
|      |   |      |
|     1|   |     3|
 ------     ------

I have tried fmt.Print, but that still prints them below each other. I was thinking about creating a function as well, that prints the top line of each object, but I couldn't figure out how to do this. Any ideas?

解决方案

This takes care of the printing. The numbers are randomized between 1 and 6 (inclusive). The number of dice taken as a command line argument. So in my case ./roll 6 prints 6 dice with random numbers up to 6.

package main

import (
    "fmt"
    "math/rand"
    "os"
    "strconv"
    "time"
)

func main() {
    numDice := 1

    if len(os.Args) > 1 {
        i, err := strconv.Atoi(os.Args[1])
        if err != nil {
            fmt.Println(err)
        }
        numDice = i
    }

    seed := rand.NewSource(time.Now().UnixNano())
    randomNumber := rand.New(seed)

    die := []string{
        " ------   ",
        "|      |  ",
        "|      |  ",
        "|      |  ",
        " ------   ",
    }

    for i := 0; i < 5; i++ {
        for j, n := 0, numDice; j < n; j++ {
            if i == 3 {
                fmt.Printf("|    %d |  ", randomNumber.Intn(5)+1)
            } else {
                fmt.Print(die[i])
            }
        }
        fmt.Println()
    }
}

这篇关于在同一行上打印多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆