本文整理汇总了Scala中java.util.Scanner类的典型用法代码示例。如果您正苦于以下问题:Scala Scanner类的具体用法?Scala Scanner怎么用?Scala Scanner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Scanner类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: InsertionSort
//设置package包名称以及导入依赖的类
package com.example
import java.util.Scanner
import scala.annotation.tailrec
object InsertionSort {
def main(args: List[String]) {
val s = new Scanner(System.in)
val a = s.nextInt()
val numbers: Array[Int] = Array.fill(a){0}
for(i <- 0 until a) {
numbers(i) = s.nextInt()
}
println(sort(numbers.toList).mkString(","))
}
def insert(element: Int, acc: List[Int]): List[Int] = {
def insertHelper(elements: List[Int]): List[Int] = elements match {
case Nil => List(element)
case head :: tail if element < head => element :: head :: tail
case head :: tail => head :: insert(element, tail)
}
insertHelper(acc)
}
def sort(numbers: List[Int]): List[Int] = {
def sortHelper(unsorted: List[Int], acc: List[Int]): List[Int] = unsorted match {
case Nil => acc
case head :: tail => sortHelper(tail, insert(head, acc))
}
sortHelper(numbers, Nil)
}
}
开发者ID:deil87,项目名称:code-challenges,代码行数:41,代码来源:InsertionSort.scala
示例2: GCDEuclidian
//设置package包名称以及导入依赖的类
package com.example.gcd
import java.util.Scanner
import com.example.util.BenchmarkHelper._
import scala.math.BigInt
object GCDEuclidian extends App{
def calculateGCDfor(a: BigInt, b: BigInt): BigInt = {
if (b == BigInt(0)) a
else {
if(a > b) calculateGCDfor(b, a - b * (a / b))
else calculateGCDfor(a, b - a * (b / a))
}
}
val s = new Scanner(System.in)
val a = s.nextBigInteger()
val b = s.nextBigInteger()
//Test for example for a = 74356764380* 13 & b = 74356764380 * 5
time {
println{
s"GCD for numbers $a and $b is: \t" + calculateGCDfor(a, b)
}
}
}
开发者ID:deil87,项目名称:code-challenges,代码行数:31,代码来源:GCDEuclidian.scala
示例3: GCD
//设置package包名称以及导入依赖的类
package com.example.gcd
import java.util.Scanner
import com.example.util.BenchmarkHelper._
object GCD extends App{
def calculateGCDfor(a: BigInt, b: BigInt): BigInt = {
var biggestGCD: BigInt = 1
for( i <- BigInt(1) to a + b) {
if(a % i == 0 && b % i == 0) biggestGCD = i
}
biggestGCD
}
val s = new Scanner(System.in)
val a = s.nextBigInteger()
val b = s.nextBigInteger()
time {
println{
s"GCD for numbers $a and $b is: \t" + calculateGCDfor(a, b)
}
}
}
开发者ID:deil87,项目名称:code-challenges,代码行数:28,代码来源:GCD.scala
示例4: FibbonaciNumbers
//设置package包名称以及导入依赖的类
package com.example.fibbonaci
import java.util.Scanner
import com.example.util.BenchmarkHelper._
object FibbonaciNumbers extends App{
def calculateFibbFor(n: Int): Int = n match {
case number if number <= 1 => number
case number if number > 1 => calculateFibbFor(number -1) + calculateFibbFor(number -2)
}
val s = new Scanner(System.in)
val a = s.nextInt()
time {
println{
s"Fibbonaci for number $a:" + calculateFibbFor(a)
}
}
}
开发者ID:deil87,项目名称:code-challenges,代码行数:23,代码来源:FibbonaciNumbers.scala
示例5: SelectionSort
//设置package包名称以及导入依赖的类
package com.example
import java.util.Scanner
object SelectionSort {
def main(args: Array[String]) { // what if we have linked list
val s = new Scanner(System.in)
val a = s.nextInt()
val numbers: Array[Int] = Array.fill(a){0}
for(i <- 0 until a) {
numbers(i) = s.nextInt()
}
println(sort(numbers).mkString(","))
}
def sort(numbers: Array[Int]): Array[Int] = {
val n = numbers.size
for {i <- 0 until n} yield {
var minOfLeft = i
for {j <- i + 1 until n} yield {
if (numbers(j) < numbers(i)) minOfLeft = j
}
val temp = numbers(i)
numbers(i) = numbers(minOfLeft)
numbers(minOfLeft) = temp
}
numbers
}
}
开发者ID:deil87,项目名称:code-challenges,代码行数:37,代码来源:SelectionSort.scala
示例6: MaxPairwiseProduct
//设置package包名称以及导入依赖的类
import java.util.Scanner
object MaxPairwiseProduct {
def main(args: Array[String]) {
val s = new Scanner(System.in)
val a = s.nextInt()
val numbers: Array[Int] = Array.fill(a){0}
for(i <- 0 until a) {
numbers(i) = s.nextInt()
}
println(findMaxPairwise(numbers))
}
def findMaxPairwise(numbers: Seq[Int]): Long = {
val n = numbers.size
var maxIndex1 = -1
var maxIndex2 = -1
for{ i <- 0 until n } yield {
if( maxIndex1 == -1 || numbers(i) > numbers(maxIndex1)) maxIndex1 = i
}
for{ j <- 0 until n if j != maxIndex1} yield {
if(maxIndex2 == -1 || numbers(j) > numbers(maxIndex2)) maxIndex2 = j
}
numbers(maxIndex1).asInstanceOf[Long] * numbers(maxIndex2)
}
}
开发者ID:deil87,项目名称:code-challenges,代码行数:32,代码来源:MaxPairwiseProduct.scala
示例7: FileUtils
//设置package包名称以及导入依赖的类
package com.bob.scalatour.utils
import java.io._
import java.util.Scanner
import com.google.common.io.CharStreams
object FileUtils {
def usingScanner(inputStream: InputStream): String = {
using(new Scanner(inputStream)) {
scanner => {
val fileContent = scanner.useDelimiter("\\A").next()
fileContent
}
}
}
def using[A <: {def close() : Unit}, B](param: A)(f: A => B): B =
try {
f(param)
} finally {
param.close()
}
def writeToFile(fileName: String, data: String) =
using(new FileWriter(fileName, true)) {
fileWriter => {
fileWriter.append(data)
}
}
}
开发者ID:bobxwang,项目名称:scalatour,代码行数:34,代码来源:FileUtils.scala
示例8: Console
//设置package包名称以及导入依赖的类
package nl.dykam.hangman.client.actors
import java.util.Scanner
import akka.actor.Actor
import nl.dykam.hangman.client.actors.Console.Line
object Console {
case class Line(line: String)
}
class Console extends Actor {
var thread: Thread = null
override def preStart(): Unit = {
thread = new Thread(new Runnable {
def run() {
while (true) {
val line: String = new Scanner(System.in).nextLine()
context.system.eventStream.publish(Line(line))
}
}
})
thread.start()
}
override def postStop(): Unit = {
thread.interrupt()
}
override def receive: Receive = {
case _ =>
}
}
开发者ID:Dykam,项目名称:scala-akka-cluster-hangman,代码行数:37,代码来源:Console.scala
示例9: ScannerPrint
//设置package包名称以及导入依赖的类
package chehao.myscala
import java.util.Scanner
import scala.reflect.io.File
import scala.reflect.io.Path.string2path
object ScannerPrint {
def main(args: Array[String]): Unit = {
//object is like singleton object of a class defined implicitly.
ScannerPrint.withScan(File("src/main/resources/scanfile.properties"),
scanner => println("pid is " + scanner.next()))
//throw exception
ScannerPrint.withScan(File("src/main/resources/scanfile.properties"),
scanner => log("pid is " + scanner.next() + 1/0))
//call By Name don't throw exception, , evaluate until execute
ScannerPrint.withScan(File("src/main/resources/scanfile.properties"),
scanner => logByName("pid is " + scanner.next() + 1/0))
}
def withScan(f: File, op: Scanner => Unit) {
val scanner = new Scanner(f.bufferedReader())
try {
op(scanner)
} finally {
scanner.close()
}
}
val logEnable = false
def log(msg:String) = if(logEnable) println(msg)
//call by name
def logByName(msg: =>String) = if(logEnable) println(msg)
}
开发者ID:Chehao,项目名称:Akkala,代码行数:38,代码来源:ScannerPrint.scala
示例10: FileExtract
//设置package包名称以及导入依赖的类
package com.nekopiano.scala.scalasandbox.os
import java.io.File
import scalax.io.Resource
import scalax.io.Output
import java.util.Scanner
import java.nio.charset.Charset
import java.io.InputStreamReader
object FileExtract {
val TARGET_PATHS = Seq(
raw"bin\custom\samplecore\resources\samplecore-items.xml",
raw"bin\custom\samplecore\src\jp\sample\y\core\jalo\AcmecoreManager.java",
raw"bin\custom\sampleproductcockpit\resources\sampleproductcockpit\sampleproductcockpit-spring-services.xml",
raw"bin\custom\sampleproductcockpit\resources\sampleproductcockpit\sampleproductcockpit-web-spring.xml",
raw"bin\custom\sampleproductcockpit\src\jp\sample\y\productcockpit\services\meta\impl\ProductReferenceSpecNotePropertyValueHandler.java",
raw"bin\custom\sampleproductcockpit\src\jp\sample\y\productcockpit\services\meta\impl\SpecNotePropertyValueHandler.java",
raw"bin\custom\sampleproductcockpit\src\jp\sample\y\productcockpit\session\editor\AttributeSpecNoteUIEditor.java",
raw"bin\custom\sampleproductcockpit\src\jp\sample\y\productcockpit\session\editor\RichTextSpecNoteUIEditor.java",
raw"bin\custom\sampleproductcockpit\src\jp\sample\y\productcockpit\session\editor\SectionSpecNoteUIEditor.java",
raw"bin\custom\sampleproductcockpit\src\jp\sample\y\productcockpit\session\editor\SpecNoteUIEditor.java",
raw"bin\custom\sampleproductcockpit\src\jp\sample\y\productcockpit\session\impl\AcmeNewItemSection.java")
def main(args: Array[String]): Unit = {
System.out.println("Enter a String and press enter.");
val scan = new Scanner(System.in, "MS932")
System.out.println("Please enter the absolute path to copy files from.")
val dirPath = scan.nextLine
println("dirPath=" + dirPath)
val files = getFileTree(new File(dirPath)).filter(_.isFile)
println("files.size=" + files.size)
val targetFiles = files.map(file =>
{
val absoluthPath = file.getAbsolutePath
TARGET_PATHS.collectFirst { case targetPath if (absoluthPath.contains(targetPath)) => file }
}).collect { case Some(file) => file }
println("targetFiles.size=" + targetFiles.size)
targetFiles foreach (file =>
{
val absoluthPath = file.getAbsolutePath
println("file=" + file)
Resource.fromFile(file) copyDataTo Resource.fromFile("extracted/" + file.getName)
})
println("Finished.")
}
def getFileTree(f: File): Stream[File] =
f #:: (if (f.isDirectory) f.listFiles().toStream.flatMap(getFileTree)
else Stream.empty)
}
开发者ID:lamusique,项目名称:ScalaSandbox,代码行数:60,代码来源:FileExtract.scala
示例11: FileSearch
//设置package包名称以及导入依赖的类
package com.nekopiano.scala.scalasandbox.os
import java.io.File
import scalax.io.Resource
import scalax.io.Output
import java.util.Scanner
import java.nio.charset.Charset
import java.io.InputStreamReader
object FileSearch {
val FOLDER_PATH = "C:\\Repos\\AcmeDocsRepo\\git\\datamig\\registeringbinarydata_130807"
def main(args: Array[String]): Unit = {
System.out.println("Enter a String and press enter.");
val scan = new Scanner(System.in, "MS932")
System.out.println("Please enter the absolute path to search files from.")
val dirPath = scan.nextLine
println("dirPath=" + dirPath)
//http://stackoverflow.com/questions/2637643/how-do-i-list-all-files-in-a-subdirectory-in-scala
val files = getFileTree(new File(dirPath)).filter(_.isFile)
println("files.size=" + files.size)
files foreach { file =>
{
println(file)
Resource.fromFile(file) copyDataTo Resource.fromFile("medias/" + file.getName)
// val storingFile = new File("medias/" + file.getName)
// val output: Output = Resource.fromFile("medias/" + file.getName)
// output.write(file)
}
}
println("Finished.")
}
def getFileTree(f: File): Stream[File] =
f #:: (if (f.isDirectory) f.listFiles().toStream.flatMap(getFileTree)
else Stream.empty)
}
开发者ID:lamusique,项目名称:ScalaSandbox,代码行数:46,代码来源:FileSearch.scala
示例12: InputEncodingTest
//设置package包名称以及导入依赖的类
package com.nekopiano.scala.sandbox.os
import java.util.Scanner
object InputEncodingTest {
def main(args: Array[String]): Unit = {
// val scan = new Scanner(System.in, "UTF8")
val scan = new Scanner(System.in)
System.out.println("Please enter a string.")
val input = scan.nextLine
print(input)
def print(input: String) {
println("input=" + input)
println("%04X".format(input.charAt(0).toInt))
println("UTF8=" + input.getBytes("UTF8").mkString)
println("MS932=" + input.getBytes("MS932").mkString)
println("UTF16=" + input.getBytes("UTF16").mkString)
}
//print("?")
}
}
开发者ID:lamusique,项目名称:ScalaSandbox,代码行数:26,代码来源:InputEncodingTest.scala
示例13: LineProcessor
//设置package包名称以及导入依赖的类
package edu.knowitall.common.main
import java.util.Scanner
import edu.knowitall.common.Timing.time
abstract class LineProcessor {
def init(args: Array[String]) {}
def exit(ns: Long) {}
def process(line: String): String
def main(args: Array[String]) {
init(args)
val scanner = new Scanner(System.in, "UTF-8")
val condition =
if (args.length > 0 && args.contains("-i")) () => true
else () => scanner.hasNextLine
val ns = time {
while (condition()) {
println(process(scanner.nextLine))
}
}
exit(ns)
}
}
开发者ID:schmmd,项目名称:openie-standalone,代码行数:29,代码来源:LineProcessor.scala
示例14: ReadRegression
//设置package包名称以及导入依赖的类
package se.lth.immun.diana
import java.util.Scanner
import java.io.File
import scala.collection.mutable.ArrayBuffer
class ReadRegression {
val regressions = new ArrayBuffer[RegressionParams]
def readRegFile(name: String) {
val fileReader = new Scanner(new File(name))
while (fileReader.hasNext()) {
val line = fileReader.nextLine()
val splitData = line.split("\\)")
val min = splitData(0).charAt(splitData(0).length - 1)-'0'
val max = splitData(1).charAt(splitData(1).length - 1)-'0'
val detect = splitData(2).charAt(splitData(2).length - 1)-'0'
val filter = splitData(3).charAt(splitData(3).length - 1)-'0'
val rep = splitData(4).charAt(splitData(4).length - 1)-'0'
val ifTemplate = splitData(5).charAt(splitData(5).length - 1)-'0'
val corrLim = (splitData(6).split("\\(")(1)).toDouble
val regParams = splitData(7).drop(2).split(" ").map { x => x.toDouble }
regressions += new RegressionParams(min, max, detect, filter, rep, ifTemplate, corrLim, 1, regParams)
}
}
def estimatePeaks(features: PeptideFeatures, regParams: RegressionParams): Int = {
return (features.average * regParams.regressionParams(0) + features.lowpassaverage * regParams.regressionParams(1) + features.fakelowpassaverage * regParams.regressionParams(2) + features.max * regParams.regressionParams(3) + features.median * regParams.regressionParams(4) + features.numberOfChanges * regParams.regressionParams(5) + features.variance * regParams.regressionParams(6)).toInt
}
}
开发者ID:ViktorSt,项目名称:diana2,代码行数:34,代码来源:ReadRegression.scala
示例15: AuthIt
//设置package包名称以及导入依赖的类
package com.husaft.photofriend.cmd
import java.util.Scanner
import com.flickr4java.flickr._
import com.flickr4java.flickr.auth._
import org.scribe.model._
import java.awt.Desktop
import java.net.URI
import com.typesafe.config.ConfigFactory
object AuthIt {
def doAuth(api: Flickr): Auth = {
val authIntf = api.getAuthInterface
val prefix = "Auth.";
val conf = ConfigFactory.load();
val token = conf.getString(prefix + "token")
val secret = conf.getString(prefix + "secret");
var requestToken: Token = null
if (token.isEmpty()) {
val scanner = new Scanner(System.in)
val token = authIntf.getRequestToken()
val url = authIntf.getAuthorizationUrl(token, Permission.DELETE)
Desktop.getDesktop.browse(URI.create(url))
println("Paste in the token it gives you:")
print(">>")
val tokenKey = scanner.nextLine()
scanner.close()
requestToken = authIntf.getAccessToken(token, new Verifier(tokenKey))
println("Authentication success")
} else {
requestToken = new Token(token, secret)
}
val auth = authIntf.checkToken(requestToken)
println(" Token: " + requestToken.getToken());
println(" Secret: " + requestToken.getSecret());
println(" Id: " + auth.getUser().getId())
println(" Realname: " + auth.getUser().getRealName())
println(" Username: " + auth.getUser().getUsername())
println(" Permission: " + auth.getPermission().getType())
auth
}
}
开发者ID:husaft,项目名称:PhotoFriend,代码行数:49,代码来源:AuthIt.scala
示例16: HttpHelper
//设置package包名称以及导入依赖的类
package util
import java.io.InputStream
import java.util.Scanner
import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
class HttpHelper {
def downloadPageByGet(url: String): Option[String] = {
val httpClient = HttpClients.createDefault()
val httpGetter = new HttpGet(url)
val response = httpClient.execute(httpGetter)
if (response.getStatusLine.getStatusCode == HttpStatus.SC_OK) {
var is: InputStream = null
var sc: Scanner = null
try {
val entity = response.getEntity
val buffer = new StringBuilder()
is = entity.getContent
sc = new Scanner(is)
while (sc.hasNext) {
buffer.append(sc.nextLine())
}
Some(buffer.toString())
} catch {
case ex: Exception =>
if (is != null) is.close()
if (sc != null) sc.close()
if (response != null) response.close()
None
}
} else None
}
}
开发者ID:TopSpoofer,项目名称:CodingCrawler,代码行数:39,代码来源:HttpHelper.scala
示例17: main
//设置package包名称以及导入依赖的类
package kpi.twitter.analysis.tools.kafka
import java.io.File
import java.util.{Properties, Scanner, UUID}
import scala.util.Random
import org.apache.commons.io.FileUtils
import org.apache.curator.test.TestingServer
import org.apache.log4j.Logger
import kafka.admin.AdminUtils
import kafka.server.{KafkaConfig, KafkaServerStartable}
import kafka.utils.ZkUtils
import kpi.twitter.analysis.tools._
import kpi.twitter.analysis.utils._
def main(args: Array[String]) {
val config = getOptions("integration.conf")
val kafkaPort = config.getInt(kafkaBrokerPort)
val zookeeperPort = config.getInt(kafkaZookeeperPort)
val allTweetsTopic = config.getString(kafkaTweetsAllTopic)
val analyzedTweetsTopic = config.getString(kafkaTweetsPredictedSentimentTopic)
val kafkaZookeeper = KafkaZookeeper(kafkaPort, zookeeperPort)
kafkaZookeeper.start()
kafkaZookeeper.createTopic(allTweetsTopic, 3, 1)
kafkaZookeeper.createTopic(analyzedTweetsTopic, 3, 1)
val sc = new Scanner(System.in)
val stopCmd = "bye"
while (!stopCmd.equals(sc.nextLine())) {
println(s"use $stopCmd to stop Kafka server")
}
}
}
开发者ID:GRpro,项目名称:TwitterAnalytics,代码行数:37,代码来源:KafkaZookeeper.scala
示例18: App
//设置package包名称以及导入依赖的类
import java.io.IOException
import java.util.Scanner
object App {
private val EXIT: String = "exit"
private val POLL: String = "poll"
@throws[IOException]
def main(args: Array[String]) {
lazy val sensors = List(new FireSensor, new SmokeSensor)
lazy val controlUnit: ControlUnit = new ControlUnit(sensors)
val scanner: Scanner = new Scanner(System.in)
var input: String = ""
while (input != EXIT) {
println("Type \"poll\" to poll all sensors once or \"exit\" to exit")
input = scanner.nextLine
if (input == POLL) {
controlUnit.pollSensors()
}
}
}
}
开发者ID:BBK-PiJ-2015-67,项目名称:sdp-portfolio,代码行数:26,代码来源:App.scala
示例19: Entry
//设置package包名称以及导入依赖的类
package glog
import java.io.StringReader
import java.text.SimpleDateFormat
import java.util.{Date, Scanner}
case class Entry(
entryNumber: Int,
machineNumber: Int,
employeeNumber: Int,
name: String,
mode: Int,
ioMd: Int,
date: Date)
object Entry {
def apply(logLine: String): Entry = {
val dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
val scanner = new Scanner(new StringReader(logLine))
Entry(
entryNumber = scanner.nextInt(),
machineNumber = scanner.nextInt(),
employeeNumber = scanner.nextInt(),
name = scanner.next(),
mode = scanner.nextInt(),
ioMd = scanner.nextInt(),
date = dateFormat.parse(scanner.nextLine().trim)
)
}
}
开发者ID:stefanlourens,项目名称:glog-parser,代码行数:34,代码来源:Entry.scala
示例20: TestProcessIO
//设置package包名称以及导入依赖的类
package sygusgp
import scala.sys.process.ProcessIO
import java.io.InputStream
import java.io.OutputStream
import java.util.Scanner
import scala.sys.process.Process
object TestProcessIO extends App {
def feedInput(in: OutputStream): Unit = {
for (ln <- io.Source.stdin.getLines) {
print("> ")
in.write((ln + "\n").toCharArray().map(_.toByte))
in.flush // very important
}
}
def processOutput(pref: String)(os: InputStream): Unit = {
val sc = new Scanner(os)
while (true) {
println(pref + sc.nextLine)
}
}
val pb = Process("""/bin/bash""")
val pio = new ProcessIO(feedInput,
processOutput("OUT:"), processOutput("ERR:"))
pb.run(pio) // don't wait
}
开发者ID:kkrawiec,项目名称:CDGP,代码行数:28,代码来源:Sandbox.scala
注:本文中的java.util.Scanner类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论