如何在 Scala 中获取用户的输入?

发布于 2024-10-18 09:02:49 字数 47 浏览 2 评论 0原文

我想接受用户的输入。你能告诉我如何在 Scala 中以字符串形式请求用户输入吗?

I want to take input from the user. Can you please tell me how to ask for user input as a string in Scala?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

乞讨 2024-10-25 09:02:49

在 Scala 2.11 中,使用

scala.io.StdIn.readLine()

代替已弃用的 Console.readLine

In Scala 2.11 use

scala.io.StdIn.readLine()

instead of the deprecated Console.readLine.

待"谢繁草 2024-10-25 09:02:49

这是读取整数值的标准方法,

val a = scala.io.StdIn.readInt()
println("The value of a is " + a)

类似地

def readBoolean(): Boolean

从标准输入的整行读取布尔值。

def readByte(): Byte

从 stdin 读取整行的 Byte 值。

def readChar(): Char

从 stdin 读取整行的 Char 值。

def readDouble(): Double

从 stdin 读取整行的 Double 值。

def readFloat(): Float

从 stdin 读取整行的浮点值。

def readInt(): Int

从 stdin 读取整行 Int 值。

def readLine(text: String, args: Any*): String

将格式化文本打印到标准输出并从标准输入读取整行。

def readLine(): String

从标准输入读取整行。

def readLong(): Long

从 stdin 读取整行的 Long 值。

def readShort(): Short

从 stdin 读取整行的 Short 值。

def readf(format: String): List[Any]

按照格式说明符的指定从 stdin 读取结构化输入。

def readf1(format: String): Any

按照格式说明符的指定从 stdin 读取结构化输入,返回
根据格式规范,仅提取第一个值。

def readf2(format: String): (Any, Any)

按照格式说明符的指定从 stdin 读取结构化输入,返回
根据格式规范,仅提取前两个值。

def readf3(format: String): (Any, Any, Any)

按照格式说明符的指定从 stdin 读取结构化输入,返回
根据格式规范,仅提取前三个值。

同样,如果您想从同一行读取多个用户输入,例如:姓名、年龄、体重,您可以使用

import java.util.Scanner

// simulated input
val input = "Joe 33 200.0"
val line = new Scanner(input)
val name = line.next
val age = line.nextInt
val weight = line.nextDouble

摘自 Scala Cookbook:Alvin Alexander 的面向对象和函数式编程的食谱的Scanner 对象

Here is a standard way to read Integer values

val a = scala.io.StdIn.readInt()
println("The value of a is " + a)

similarly

def readBoolean(): Boolean

Reads a Boolean value from an entire line from stdin.

def readByte(): Byte

Reads a Byte value from an entire line from stdin.

def readChar(): Char

Reads a Char value from an entire line from stdin.

def readDouble(): Double

Reads a Double value from an entire line from stdin.

def readFloat(): Float

Reads a Float value from an entire line from stdin.

def readInt(): Int

Reads an Int value from an entire line from stdin.

def readLine(text: String, args: Any*): String

Prints formatted text to stdout and reads a full line from stdin.

def readLine(): String

Reads a full line from stdin.

def readLong(): Long

Reads a Long value from an entire line from stdin.

def readShort(): Short

Reads a Short value from an entire line from stdin.

def readf(format: String): List[Any]

Reads in structured input from stdin as specified by the format specifier.

def readf1(format: String): Any

Reads in structured input from stdin as specified by the format specifier, returning
only the first value extracted, according to the format specification.

def readf2(format: String): (Any, Any)

Reads in structured input from stdin as specified by the format specifier, returning
only the first two values extracted, according to the format specification.

def readf3(format: String): (Any, Any, Any)

Reads in structured input from stdin as specified by the format specifier, returning
only the first three values extracted, according to the format specification.

Similarly if you want to read multiple user inputs from the same line ex: name, age, weight you can use the Scanner object

import java.util.Scanner

// simulated input
val input = "Joe 33 200.0"
val line = new Scanner(input)
val name = line.next
val age = line.nextInt
val weight = line.nextDouble

abridged from Scala Cookbook: Recipes for Object-Oriented and Functional Programming by Alvin Alexander

握住我的手 2024-10-25 09:02:49

来自 Scala maling 列表 (格式和链接已更新):

简短回答:

readInt

长答案:

如果您想从终端读取内容,请查看 Console.scala
您可以像这样使用这些函数:

Console.readInt

此外,为了您的方便,Predef.scala< /代码>
自动定义 Console 中功能的一些快捷方式。自从
Predef 中的内容始终随处自动导入,您
可以像这样使用它们:

readInt

From the Scala maling list (formatting and links were updated):

Short answer:

readInt

Long answer:

If you want to read from the terminal, check out Console.scala.
You can use these functions like so:

Console.readInt

Also, for your convenience, Predef.scala
automatically defines some shortcuts to functions in Console. Since
stuff in Predef is always and everywhere imported automatically, you
can use them like so:

readInt
温柔嚣张 2024-10-25 09:02:49
object InputTest extends App{

    println("Type something : ")
    val input = scala.io.StdIn.readLine()
    println("Did you type this ? " + input)

}

这样您就可以询问输入。

scala.io.StdIn.readLine()
object InputTest extends App{

    println("Type something : ")
    val input = scala.io.StdIn.readLine()
    println("Did you type this ? " + input)

}

This way you can ask input.

scala.io.StdIn.readLine()
雨落星ぅ辰 2024-10-25 09:02:49

您可以使用 readLine() 获取用户字符串输入。

import scala.io.StdIn._

object q1 {
  def main(args:Array[String]):Unit={  
    println("Enter your name : ")
    val a = readLine()
    println("My name is : "+a)
  }
}

或者您可以使用扫描仪类来获取用户输入。

import java.util.Scanner;

object q1 {
  def main(args:Array[String]):Unit={ 
      val scanner = new Scanner(System.in)
    println("Enter your name : ")
    val a = scanner.nextLine()
    println("My name is : "+a)
  }
}

You can take a user String input using readLine().

import scala.io.StdIn._

object q1 {
  def main(args:Array[String]):Unit={  
    println("Enter your name : ")
    val a = readLine()
    println("My name is : "+a)
  }
}

Or you can use the scanner class to take user input.

import java.util.Scanner;

object q1 {
  def main(args:Array[String]):Unit={ 
      val scanner = new Scanner(System.in)
    println("Enter your name : ")
    val a = scanner.nextLine()
    println("My name is : "+a)
  }
}
心清如水 2024-10-25 09:02:49

读取用户输入的简单示例

val scanner = new java.util.Scanner(System.in)

scala> println("What is your name") What is your name

scala> val name = scanner.nextLine()
name: String = VIRAJ

scala> println(s"My Name is $name")
My Name is VIRAJ

我们也可以使用 Read Line

val name = readLine("What is your name ")
What is your name name: String = Viraj

Simple Example for Reading Input from User

val scanner = new java.util.Scanner(System.in)

scala> println("What is your name") What is your name

scala> val name = scanner.nextLine()
name: String = VIRAJ

scala> println(s"My Name is $name")
My Name is VIRAJ

Also we can use Read Line

val name = readLine("What is your name ")
What is your name name: String = Viraj
落花随流水 2024-10-25 09:02:49

在 Scala 2 中:

import java.io._
object Test {
    // Read user input, output
    def main(args: Array[String]) {

        // create a file writer
        var writer = new PrintWriter(new File("output.txt"))

       // read an int from standard input
       print("Enter the number of lines to read in: ")
       val x: Int = scala.io.StdIn.readLine.toInt

       // read in x number of lines from standard input
       var i=0
       while (i < x) {
           var str: String = scala.io.StdIn.readLine
           writer.write(str + "\n")
           i = i + 1
       }

       // close the writer
       writer.close
     }
}

此代码从用户获取输入并输出:

[input] Enter the number of lines to read in: 2
one
two

[output] output.txt
one
two

In Scala 2:

import java.io._
object Test {
    // Read user input, output
    def main(args: Array[String]) {

        // create a file writer
        var writer = new PrintWriter(new File("output.txt"))

       // read an int from standard input
       print("Enter the number of lines to read in: ")
       val x: Int = scala.io.StdIn.readLine.toInt

       // read in x number of lines from standard input
       var i=0
       while (i < x) {
           var str: String = scala.io.StdIn.readLine
           writer.write(str + "\n")
           i = i + 1
       }

       // close the writer
       writer.close
     }
}

This code gets input from user and outputs it:

[input] Enter the number of lines to read in: 2
one
two

[output] output.txt
one
two
面如桃花 2024-10-25 09:02:49
Using a thread to poll the input-readLine:

// keystop1.sc

// In Scala- or SBT console/Quick-REPL: :load keystop1.sc
// As Script: scala -savecompiled keystop1.sc

@volatile var isRunning = true
@volatile var isPause = false

val tInput: Thread = new Thread {
  override def run: Unit = {
    var status = ""
        while (isRunning) {
            this.synchronized {
                status = scala.io.StdIn.readLine()
                status match {
                    case "s" => isRunning = false
                    case "p" => isPause = true
                    case "r" => isRunning = true;isPause = false
                    case _ => isRunning = false;isPause = false
                }
                println(s"New status is: $status")
            }
        }
    }
}

tInput.start

var count = 0
var pauseCount = 0

while (isRunning && count < 10){
  println(s"still running long lasting job! $count")
  if (count % 3 == 0) println("(Please press [each + ENTER]: s to stop, p to pause, r to run again!)")
  count += 1
  Thread sleep(2000) // simulating heavy computation
  while (isPause){
      println(s"Taking a break ... $pauseCount")
      Thread sleep(1000)
      pauseCount += 1
      if (pauseCount >= 10){
        isPause = false
        pauseCount = 0
        println(s"Taking a break ... timeout occurred!")
      }
  }
}
isRunning = false
println(s"Computation stopped, please press Enter!")
tInput.join()
println(s"Ok, thank you, good bye!")
Using a thread to poll the input-readLine:

// keystop1.sc

// In Scala- or SBT console/Quick-REPL: :load keystop1.sc
// As Script: scala -savecompiled keystop1.sc

@volatile var isRunning = true
@volatile var isPause = false

val tInput: Thread = new Thread {
  override def run: Unit = {
    var status = ""
        while (isRunning) {
            this.synchronized {
                status = scala.io.StdIn.readLine()
                status match {
                    case "s" => isRunning = false
                    case "p" => isPause = true
                    case "r" => isRunning = true;isPause = false
                    case _ => isRunning = false;isPause = false
                }
                println(s"New status is: $status")
            }
        }
    }
}

tInput.start

var count = 0
var pauseCount = 0

while (isRunning && count < 10){
  println(s"still running long lasting job! $count")
  if (count % 3 == 0) println("(Please press [each + ENTER]: s to stop, p to pause, r to run again!)")
  count += 1
  Thread sleep(2000) // simulating heavy computation
  while (isPause){
      println(s"Taking a break ... $pauseCount")
      Thread sleep(1000)
      pauseCount += 1
      if (pauseCount >= 10){
        isPause = false
        pauseCount = 0
        println(s"Taking a break ... timeout occurred!")
      }
  }
}
isRunning = false
println(s"Computation stopped, please press Enter!")
tInput.join()
println(s"Ok, thank you, good bye!")
好久不见√ 2024-10-25 09:02:49

readLine() 可让您提示用户并以字符串形式读取他们的输入

val name = readLine("What's your name? ")

readLine() lets you prompt the user and read their input as a String

val name = readLine("What's your name? ")
鹤仙姿 2024-10-25 09:02:49

请尝试

scala> readint

请尝试这个方法

please try

scala> readint

please try this method

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文