Java User Input and Difference between readInt and nextInt?

前端 未结 2 786
后悔当初
后悔当初 2021-01-29 15:19

What is wrong with this?

import java.io.*;

class TUI{

    public static void main(String[] args) {

        System.out.println(\"Enter the two numbers:\");
            


        
相关标签:
2条回答
  • 2021-01-29 15:49

    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.

    0 讨论(0)
  • 2021-01-29 15:56

    readInt is used with datainputstream class. nextInt with scanner class and you need to create a scanner object inorder to get input values. i.e

    java.util.Scanner obj=new java.util.Scanner(System.in);
          int x=obj.nextInt();
    

    Objective of both is the same to read integer values.

    0 讨论(0)
提交回复
热议问题