问题描述
我编写了这个简单的程序,对用户编写的扫描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()
.
我希望能有所帮助.祝你好运!
I hope that helps. Good luck!
这篇关于字符串不能转换为int!如何在java上总结一个扫描的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!