Java User Input and Difference between readInt and nextInt?

前端 未结 2 837
后悔当初
后悔当初 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.

提交回复
热议问题