字符串不能转换为int!如何在java上对扫描的int求和?

string cannot be converted to int! how to sum a scanned int on java?(字符串不能转换为int!如何在java上对扫描的int求和?)
本文介绍了字符串不能转换为int!如何在java上对扫描的int求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我编写了这个简单的程序来求和用户写入的扫描 int,但是当我编译它,它说字符串不能转换为int".这个程序有什么问题?

I wrote this simple program to sum a scanned int written by the user, but when i compile it, it says that "string cannot be converted to int." What is wrong in this program?

import java.util.*;
public class Pr6{
      public static void main(String[] args){
      Scanner scan = new Scanner (System.in);
      int num1;
      int num2;
      int num3;
      int sum;

                  System.out.print("Please write an integer: ");
       num1 = scan.nextLine();

                  System.out.print("Please write an integer: ");
       num2 = scan.nextLine();

                  System.out.print("Please write an integer: ");
       num3 = scan.nextLine();

       sum = num1 + num2 + num3;
                  System.out.print("Total = " + sum);



        }//main
}//Pr6

推荐答案

这是你的问题

num1 = scan.nextLine();

我们看看num1是什么数据类型:

Let's look at what data type num1 is:

int num1;

scan.nextLine() 将返回一个字符串.而且你不能有 int num1 = "1",因为它们是不同的数据类型.

scan.nextLine() will return a String. And you can't have int num1 = "1", because they are different data types.

您应该使用 scan.nextInt().它将返回一个数字.这会解决你的问题:)

You should use scan.nextInt(). It will return a number. That'll solve your problems :)

所以你会有 num1 = scan.nextInt()num2 = scan.nextInt()num3 = scan.nextInt().

So you'll have num1 = scan.nextInt(), num2 = scan.nextInt(), and num3 = scan.nextInt().

我希望这会有所帮助.祝你好运!

I hope that helps. Good luck!

这篇关于字符串不能转换为int!如何在java上对扫描的int求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

java8 stream sum multiple(java8流总和倍数)
How to output the decimal in average?(如何平均输出小数?)
Java sum 2 negative numbers(Java求和2个负数)
How to get sum of char values produced in a loop?(如何获得循环中产生的 char 值的总和?)
How can I sum the values associated with a reoccurring key in a hashmap(如何将与哈希图中重复出现的键关联的值相加)
subset sum find all subsets that add up to a number(子集和找到所有加起来为一个数字的子集)