简体   繁体   English

Java:使用 BufferReader 添加 2 个数字,不适用于 CS Academy

[英]Java: Adding 2 numbers with BufferReader, not working on CS Academy

I'm trying to add 2 integers together and print out the result, for a task on CS Academy .我正在尝试将 2 个整数相加并打印出结果,用于CS Academy上的任务。 I'm using a BufferReader to read the integer results and an enhanced-for loop to put the values into A & B;我正在使用 BufferReader 读取整数结果,并使用增强的 for 循环将值放入 A 和 B; however, it just provides a blank result.然而,它只提供一个空白结果。 How do I fix the enhanced-for loop and the reader?如何修复增强型 for 循环和读取器? https://csacademy.com/contest/archive/task/addition/ https://csacademy.com/contest/archive/task/addition/

-- ——

task: You are given two integer values A and B, compute and output their sum.任务:给定两个整数值 A 和 B,计算并输出它们的总和。

Standard input The first line contains the two integers A and B.标准输入 第一行包含两个整数 A 和 B。

Standard output Output a single number representing the sum of A and B.标准输出 输出一个代表 A 和 B 总和的数字。


  import java.util.*;
  import java.lang.*;
  import java.io.*;

  class Main {
        public static void main (String[] args) throws java.lang.Exception {
          int A, B;
          A =0; B =0;

       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter Integer:");
            int i = Integer.parseInt(br.readLine());

        int[] values = new int[i];
            for(int value: values ) {
            A=value[0];
            B=value[1];
            }
        System.out.println(A + B );

        }
    }

Your program doesn't work because first of all you are reading only one number instead of two.您的程序不起作用,因为首先您只读取一个数字而不是两个数字。 Secondly, you are adding two numbers which are initialized to 0 but which never get any other values.其次,您要添加两个初始化为 0 但从未获得任何其他值的数字。 You expect user to enter two numbers separated by a space.您希望用户输入由空格分隔的两个数字。 Therefore, you need to split the input string ("10 15") with a space and then treat each individual one string as a number and then sum it up.因此,您需要用空格分割输入字符串(“10 15”),然后将每个单独的字符串视为一个数字,然后将其相加。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Integer:");
String[] str = br.readLine().split(" ", 2);
System.out.println("Sum is " + (Integer.parseInt(str[0]) + Integer.parseInt(str[1])));
br.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM