java.lang.String无法转换为int ...不确定我做错了什么

时间:2017-02-16 02:30:51

标签: java debugging compiler-errors syntax-error

这是我在Java课程中的第二周,所以请耐心等待。我正在尝试制作一个允许用户输入“摇滚”,“纸张”或“剪刀”的程序。我相信有比我所做的更有效的方式,我认为我实际上正在取得进展,但现在我卡住了。

我对该程序的适用知识仅限于if和if-else语句以及switch语句。我尝试获取摇滚,纸张或剪刀的用户输入,将其转换为数字,并将其与随机生成的数字进行比较,0表示摇滚,1表示纸张,2表示剪刀。

import java.util.*;

public class RockPaperScissors
{
    public static void main(String[] args) {

        int computer;

       computer = (int)(Math.random() * 2 + 1);

       Scanner input = new Scanner(System.in);

       String player;
       System.out.println("Enter the word rock, paper, or scissors.");
       player = input.next();

    if (computer == 0) {       
           System.out.println("The computer chose rock.");
    }
    else if (computer == 1) {
           System.out.println("The compuer chose paper.");
    }
    else if (computer == 2) {
           System.out.println("The computer chose scissors.");
    }


    // personally starting from here is where I feel like I started to make mistakes.
    int rock = 0;
    int paper = 1;
    int scissors = 2;
    player = (int)player;

       switch (player) {
           case "r" : rock = 0;
           player = 0;
           break;
           case 'p' : paper = 1;
           player = 1;
           break;
           case 's' : scissors = 2;
           player = 2;
           break;
           default : System.out.println("Invalid input");
    }

    if (player == computer) {
          System.out.println("You tied") ;     
        }
    else if (player = 1 && computer = 0 ^ player = 2 && computer = 0) {
        System.out.println("You won");
        }
    else {
        System.out.println("You lost");
    }
}
}

1 个答案:

答案 0 :(得分:1)

在Java中,您可以使用totalInfo将String转换为int。

  1. Integer.parseInt()示例 将字符串“10”转换为基本int的示例。

    Integer.parseInt()
  2. 输出

    String number = "10";
    
    int result = Integer.parseInt(number);
    
    System.out.println(result);
    

    2

    10 例子 或者,您可以使用Integer.valueOf(),它将返回一个Integer对象。

    Integer.valueOf()

    输出

    String number = "10";
    Integer result = Integer.valueOf(number);
    System.out.println(result);
    

    请注意

    总之,10 返回一个原始int,而parseInt(String)返回一个valueOf(String)对象。