問題描述
我編寫了這個簡單的程序來求和用戶寫入的掃描 int,但是當(dāng)我編譯它,它說字符串不能轉(zhuǎn)換為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是什么數(shù)據(jù)類型:
Let's look at what data type num1 is:
int num1;
scan.nextLine()
將返回一個字符串.而且你不能有 int num1 = "1",因為它們是不同的數(shù)據(jù)類型.
scan.nextLine()
will return a String. And you can't have int num1 = "1", because they are different data types.
您應(yīng)該使用 scan.nextInt()
.它將返回一個數(shù)字.這會解決你的問題:)
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!
這篇關(guān)于字符串不能轉(zhuǎn)換為int!如何在java上對掃描的int求和?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!