Java从一行读取多个变量,但是如何使用一个变量终止?

时间:2019-01-24 08:02:42

标签: java java.util.scanner

import org.apache.http.HttpHost;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.*;
import java.util.concurrent.TimeUnit;
public class Main {
private static final int TCP_CONNECTION_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(30);
private static final int CONNECTION_REQUEST_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(30);
private static final int TCP_SOCKET_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(20);

private static final String USER_AGENT = "User-Agent";
private static final String ACCEPT_LANGUAGE = "Accept-Language";
private static final String ACCEPT_ENCODING = "Accept-Encoding";
private static final int MAX_RESPONSE_BYTE_COUNT = 25 * 1024 *1024;

public static void main(String[] args) throws Exception {
    Settings settings = new Settings("177.124.57.214", 8080);
    Document doc = getDoc(settings, "https://www.google.com/");
    System.out.println("Got Document");
}

private static byte[] readDataFrom(CloseableHttpResponse response) {
    System.out.println("Opening connect... ByteStream creating...");
    try (BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
         ByteArrayOutputStream bous = new ByteArrayOutputStream()) {
        int byteCount = 0;
        int byteValue;
        while ((byteValue = bis.read()) != -1) {
            byteCount += 1;
            if (byteCount > MAX_RESPONSE_BYTE_COUNT) {
                throw new RuntimeException("Response size exceeds max value " + MAX_RESPONSE_BYTE_COUNT + " bytes");
            }
            bous.write(byteValue);
        }
        return bous.toByteArray();
    } catch (Exception e) {
        System.out.println("During data read something went wrong null. "+ e.getMessage());
        return null;
    }
}

static class Settings {
    private CloseableHttpClient httpClient = null;
    private HttpClientContext context = HttpClientContext.create();
    RequestConfig.Builder globalConfigBuilder = RequestConfig.custom();

    public Settings(String host, int port) {


        CredentialsProvider credentialsProvider = null;

        HttpHost proxy = new HttpHost(host, port);
        globalConfigBuilder.setProxy(proxy);

        RequestConfig globalConfig = globalConfigBuilder
                .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                .setRedirectsEnabled(true)
                .setConnectTimeout(TCP_CONNECTION_TIMEOUT)
                .setSocketTimeout(TCP_SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                .build();


        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(globalConfig)
                .setKeepAliveStrategy(keepAliveStrategy)
                .setRetryHandler(new StandardHttpRequestRetryHandler(0, false))
                .setDefaultCredentialsProvider(credentialsProvider)
                .build();

    }
}

static ConnectionKeepAliveStrategy keepAliveStrategy = (response, context) -> 0;


private static Document getDoc(Settings settings, String requestUrl) throws IOException {
    CloseableHttpClient httpClient = settings.httpClient;
    HttpClientContext context = settings.context;
    HttpRequestBase httpRequest = new HttpGet(requestUrl);
    httpRequest.setHeader(ACCEPT_ENCODING, "gzip, deflate");
    httpRequest.setHeader(ACCEPT_LANGUAGE, "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2");
    httpRequest.setHeader(USER_AGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0");
    System.out.println("Getting document...");
    CloseableHttpResponse response = null;
    try {
        System.out.println("Starting...");
        response = httpClient.execute(httpRequest, context);
        System.out.println("Strart reading data from source...");
        byte[] data = readDataFrom(response);
        if (data == null)
            System.out.println("Data = null");
        else
            System.out.println("Data successfully read!");
        if (data != null) {
            System.out.println("Parsing started");
            return Jsoup.parse(new String(data));
        } else {
            return null;
        }
    } catch (Exception e) {
        System.out.println("Error while getting doc" + e.getMessage());
        return null;
    } finally {
        if (response != null) {
            response.close();
        }
    }
  }
}

如果我只想输入一个值(例如“ 0”)以终止程序,该怎么办?因为上面的代码必须输入3个值,对吗?

2 个答案:

答案 0 :(得分:2)

尝试使用while循环和一个列表来存储数据。

boolean mustContinue = true;
List<Integer> result = new ArrayList<Integer>();
while(mustContinue) {
    Integer a = br.nextInt();
    if(a == 0) {
        mustContinue = false;
    } else {
        result.add(a);
    }
}

这不是完整的正在运行的代码,仅是为您提供可能的解决方案的想法。为了使它成为完整的运行代码,需要注意一些事情(例如,检查br.hasNextInt()以防止异常等)。

答案 1 :(得分:0)

您可以使用while循环来完成此操作,当您键入0时它将结束:

    Scanner sc = new Scanner(System.in);

    int num;
    while (sc.hasNextInt() && ((num = sc.nextInt()) != 0))
    {
        // do something
    }