1. 程式人生 > >Java算法測試的輸入模板

Java算法測試的輸入模板

數據 ++ void any java算法 port width cin import

Java數據讀入

讀入一個整數:

Scanner sc = new Scanner (System.in);

int n = sc.nextInt();

讀入一個字符串

Scanner sc = new Scanner (System.in);

String s=sc.next();

讀入一個浮點數

Scanner sc = new Scanner (System.in);

double t = sc.nextDouble();

讀入一行

Scanner sc = new Scanner (System.in);

String s = sc.nextLine();

判斷是否有下一個輸入sc.hasNext()或sc.hasNextInt()或sc.hasNextDouble()或sc.hasNextLine()

Java讀入一行空格隔開的數據

Sample Input

1 2 3 4 5 6 7 8 9 10 11 12 13

import java.util.Scanner;

public class Demo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String s = sc.nextLine();

String ss[] = s.split(" ");

int len = ss.length;

int[] src = new int[len];

for(int i = 0; i < len; i++){

src[i] = Integer.parseInt(ss[i]);

}

}

}

讀入一個整數

public class Solution{

public static void main(String[] args){

Scanner in = new Scanner(System.in);

int a = in.nextInt();

}

}

連續數據多個數

public static void readManyNumber(){

Scanner in = new Scanner(System.in);

int len = in.nextInt();

int[] array = new int[len];

for(int i = 0; i < len; i++){

array[i] = in.nextInt();

}

}

讀入整數

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

while(sc.hasNext()){ //判斷是否結束

int score = sc.nextInt();

}//讀入整數

}

}

讀入實數

輸入數據有多組,每組占2行,第一行為一個整數N,指示第二行包含N個實數。

Sample Input

4

56.9 67.7 90.5 12.8

5

56.9 67.7 90.5 12.8

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

while(sc.hasNext()){

int n = sc.nextInt();

for(int i=0;i<n;i++){

double a = sc.nextDouble();

}

}

}

}

讀入字符串

輸入數據有多行,第一行是一個整數n,表示測試實例的個數,後面跟著n行,每行包括一個由字母和數字組成的字符串。

Sample Input

2

asdfasdf123123asdfasdf

asdf111111111asdfasdfasdf

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = Integer.parseInt(sc.nextLine());

for(int i=0;i<n;i++){

String str = sc.nextLine();

}

}

}

Java算法測試的輸入模板