Java User Input and Difference between readInt and nextInt?

会有一股神秘感。 提交于 2019-12-09 03:59:10

问题


What is wrong with this?

import java.io.*;

class TUI{

    public static void main(String[] args) {

        System.out.println("Enter the two numbers:");
        int n1=readInt("Enter n1:");
        int n2=readInt("Enter n2:");
        int total=n1+n2;
        System.out.println("Total is =" + total+".");
    }
}

Getting these errors

Day2.java:5: error: cannot find symbol
    int n1=readInt("Enter n1:");
           ^
  symbol:   method readInt(String)
  location: class TUI
Day2.java:6: error: cannot find symbol
    int n2=readInt("Enter n2:");
           ^
  symbol:   method readInt(String)
  location: class TUI

PS- Also What is the difference between readInt and nextInt ? Can I use nextInt here


回答1:


You need something like a scanner to read-in values from console. The code should look like that:

import java.util.Scanner;

class TUI {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the two numbers:");
        System.out.println("Enter n1:");
        int n1 = scanner.nextInt();
        System.out.println("Enter n2:");
        int n2 = scanner.nextInt();
        int total = n1 + n2;
        System.out.println("Total is =" + total + ".");
        scanner.close();
    }
}

I hope it helps.



来源:https://stackoverflow.com/questions/32494712/java-user-input-and-difference-between-readint-and-nextint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!