您好,为什么我的代码会出现此错误?
线程“主”中的异常java.lang.Error:未解决的编译问题: 类型不匹配:无法从String转换为int 这是我的代码:
import java.util.*;
public class matchScore{
public static void main(String[] args){
String opt;
String home_team_name;
String away_team_name;
int home_team_score;
int away_team_score;
String[] name = new String[10];
int[] score = new int[10];
System.out.println("Retype an option:\n");
System.out.println("Home teams");
System.out.println("Away teams");
System.out.println("Outputs");
Scanner scan = new Scanner(System.in);
opt = scan.nextLine();
if(opt == "Home teams"){
System.out.println("Entre first home team name: ");
name[0] = scan.nextLine();
System.out.println("Entre first home team score: ");
score[0] = scan.nextLine();
System.out.println("Entre second home team name: ");
name[1] = scan.nextLine();
System.out.println("Entre second home team score: ");
score[1] = scan.nextLine();
System.out.println("Entre third home team name: ");
name[2] = scan.nextLine();
System.out.println("Entre third home team score: ");
score[2] = scan.nextLine();
System.out.println("Entre forth home team name: ");
name[3] = scan.nextLine();
System.out.println("Entre forth home team score: ");
score[3] = scan.nextLine();
System.out.println("Entre fifth home team name: ");
name[4] = scan.nextLine();
System.out.println("Entre fifth home team score: ");
score[4] = scan.nextLine();
System.out.println("Entre sixth home team name: ");
name[5] = scan.nextLine();
System.out.println("Entre sixth home team score: ");
score[5] = scan.nextLine();
System.out.println("Entre seventh home team name: ");
name[6] = scan.nextLine();
System.out.println("Entre seventh home team score: ");
score[6] = scan.nextLine();
}
}
}
我不明白为什么要这么做。我可以想象这很简单,只是看不到fs。
答案 0 :(得分:2)
使用
score[0] = scan.nextInt();
代替
score[0] = scan.nextLine();
as score []是int []的数组。
还可以使用.equals
比较字符串。更改
opt == "Home teams"
至opt.equals("Home teams")
答案 1 :(得分:0)
您期望输入中包含字符串,并尝试将其转换为整数。您可以通过执行scan.nextInt()
来解决此问题,或者在每次调用需要整数的值时进行Integer.valueOf(scan.nextLine())
来解决此问题
答案 2 :(得分:0)
无论何时使用扫描仪,它都会自动认为它是字符串。因此改为: name [0] = Integer.valueOf(scan.next()); 这会自动将其转换为数字。