本文整理汇总了Scala中java.util.Scanner类的典型用法代码示例。如果您正苦于以下问题:Scala Scanner类的具体用法?Scala Scanner怎么用?Scala Scanner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Scanner类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
示例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)
}
}
}
示例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)
}
}
}
示例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)
}
}
}
示例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
}
}
示例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)
}
}
示例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)
}
}
}
示例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 _ =>
}
}
示例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)
}
示例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)
}
示例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)
}
示例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("?")
}
}
示例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)
}
}
示例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
}
}
示例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
}
}