Question:

JCreator LE Scanner error?

by  |  earlier

0 LIKES UnLike

When I try to build the program, the compiler has a problem with the statements:

1.) import java.util.Scanner;

and

2.) Scanner num = new Scanner(System.in);

This is my full code (The program asks the user for two numbers and performs a certain action depending on the input:

import java.util.Scanner;

public class BasicMath

{

public static void main(String[] args)

{

//Initialize variables

int num1;

int num2;

String command;

//Create the Scanner

Scanner num = new Scanner(System.in);

//Ask for the function

System.out.println("Please enter a function from the list: Add, Sub, Mult, Div, Exp");

command.equals(num.nextString());

//Ask for the numbers

System.out.println("Please enter the first number: ");

num1 = num.nextInt();

System.out.println("Please enter the second number: ");

num2 = num.nextInt();

//Perform the command

if (command.equals("Add"))

{

System.out.println("Add" + " " + num1 + " " + num2);

System.out.print(num1 + num2);

}

else if (command.equals("Sub"))

{

System.out.println("Sub" + " " + num1 + " " + num2);

System.out.print(num1 - num2);

}

else if (command.equals("Mult"))

{

System.out.println("Mult" + " " + num1 + " " + num2);

System.out.print(num1 * num2);

}

else if (command.equals("Div"))

{

System.out.println("Div" + " " + num1 + " " + num2);

System.out.print(num1 / num2);

}

else if (command.equals("Exp"))

{

System.out.println("Exp" + " " + num1 + " " + num2);

System.out.print(Math.pow(num1, num2));

}

}

}

 Tags:

   Report

1 ANSWERS


  1. You code for getting the command string is faulty.

    Replace it with:

    command = new String(num.nextLine());

    That's all I changed and it worked for the Add function.  I didn't bother checking anything else.

    [ the String method equals compares strings and returns true or false.  That's not what you want to do.  You want to set the value of command. I don't even know if there is a string method nextString()]

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.