What import should I use for keyboard scanners and Math.? - java

I tried every import I know, and it still basically keeps giving me class, interface, or enum expected error on every line that uses Keyboard or Math.
If you're wondering what the program does, it's suppose to find the distance between 2 points that the user puts in.
// Sam
// 9.25.13
// import csl.Keyboard from the L: drive jdk
import java.io.*;
import java.util.*;
public class swagggg
public static void main ( String [] args)
{
// declare variables
int x1, y1 ,x2, y2;
double distance;
// get user input
Scanner Keyboard = new Scanner (System.in);
System.out.println("Enter the first set of coordinates: ");
x1 = Keyboard.nextInt();
y1 = Keyboard.nextInt();
System.out.println("Enter the second set of coordinates: ");
x2 = Keyboard.nextInt();
y2 = Keyboard.nextInt();
// calculate using the Math class static method
distance = Math.sqrt(Math.pow(x2-x1,2) + (Math.pow(y2-y1,2));
// out results
System.out.println ("The distance between (" +x1+","+y1+") and ("+ x2 +","+y2+") is " + distance);
}
}
/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now it compiles but when I type in the first coordinate, it looks like this
Enter the first set of coordinates:
(2,9)
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at C2p8.main(C2p8.java:17)
Process completed.

The Keyboard class doesn't exist in the JDK. Probably it's a custom class made by your teacher of some sort. You would need either the .jar of that class or the actual code. Are you supposed to do your work in your computer? If that's the case the teacher probably gave you that file. The only class I think that you might be needing here instead of Keyboard is Scanner but that one has nextInt() not readInt() method. Also that one has to be instantiated, it is not static and it appears your Keyboard one is.
For the Math class, you're not supposed to import it. It is imported automatically always.

Keyboard is not part of the standard library. Perhaps you meant java.util.Scanner, but that doesn't have readInt() method, it has nextInt(). There's a comment at the top of your code that tells you where it is, it looks like a custom class.
Math is java.lang.Math.
You're missing a ; at the end of
double distance; // <missing that ;
And you have a dangling quote here
y1 = Keyboard.readInt();' // < what is that?
Get rid of it.
Had you used a proper IDE like Eclipse, Netbeans, or IntelliJ you wouldn't have had any of these problems.

java.lang.Math.* for the math...
For getting input from the keyboard, you need a scanner.
Scanner scannerVariableNameWhichYouCouldCallKeyboard = new Scanner(System.in);
so if you simply added the line Scanner Keyboard = new Scanner(System.in);, all of your Keyboard lines would work. You may have to import java.util.Scanner;.
And for reference, if you're working in Eclipse, you can have Eclipse automatically handle your imports by either hovering over the thing that needs an import and waiting for the pop up, or I think Ctrl+O.

Related

Is there a way that I can scan comma values in Java? [duplicate]

This question already has answers here:
Scanner double value - InputMismatchException
(2 answers)
Closed 2 years ago.
I'm rather new to Java and I was making a simple calculator. Problem is when I my input number is for example "3.1" it gives an exception error, but when writing "3,1" it works just fine.
My friend, however, has a slightly more advanced calculator (with string parsing) and when I run his code the opposite happens: 3,1 gives exception error, 3.1 works perfectly.
I was looking forward to know what causes these different behaviors.
I made this simple sum just now and the same happens, I'll edit and put his calculator code in a few minutes
import java.util.Scanner;
public class Tutorial_7 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
double num1, num2;
System.out.println("Introduza os dois números");
System.out.println("1º: ");
num1 = scan.nextDouble();
System.out.println("2º: ");
num2 = scan.nextDouble();
System.out.println((num1 + num2));
scan.close();
}
}
Final edit: He does use Double.parseDouble(). Got it, the difference is indeed in where it is localized. Should have looked for it but never heard of this concept before.
Thank you
Because you are using difference Local for that one can scan it with a dot . and another with a comma , to fix it you should to fix one for your Scanner like this :
Scanner scan = new Scanner(System.in).useLocale(Locale.US);
For example:
If you are using Local.US you should to scan your double with a .
like 6.6
If you are using Locale.FRENCH you should to scan your double with
a , like 6,6

Cannot get a very basic program to produce any output whatsoever

I cannot get the Pearson MyProgrammingLab to produce any output from this code and several other programs like it. But the code works perfectly fine in other IDEs. Is there an error in the Scanner construction or anything else basic that I am overlooking?
I have exhausted so many solutions and still no luck. There is just simply no output when the program is checked, and cites it as a logic error.
Here is the code:
import java.util.Scanner;
class Area {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the side: ");
double s = input.nextDouble();
double area = (6 * Math.pow(s, 2)) / (4 * Math.tan(Math.PI/6));
System.out.println("The area of the hexagon is " + area);
}
}
Any ideas?
EDIT: This is what the ouput when checked would display:
Given the following was entered from the keyboard:
5.5⏎
you displayed:
instead of:
Enter◦the◦side:The◦area◦of◦the◦hexagon◦is◦78.59⏎

java.util.NoSuchElementException when using Scanner.nextInt() [duplicate]

I am very new to Java but am working through the book Java: How to program (9th ed.) and have reached an example where for the life of me I cannot figure out what the problem is.
Here is a (slightly) augmented version of the source code example in the textbook:
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
// creates a scanner to obtain input from a command window
Scanner input = new Scanner(System.in);
int number1; // first number to add
int number2; // second number to add
int sum; // sum of 1 & 2
System.out.print("Enter First Integer: "); // prompt
number1 = input.nextInt(); // reads first number inputted by user
System.out.print("Enter Second Integer: "); // prompt 2
number2 = input.nextInt(); // reads second number from user
sum = number1 + number2; // addition takes place, then stores the total of the two numbers in sum
System.out.printf( "Sum is %d\n", sum ); // displays the sum on screen
} // end method main
} // end class Addition
I am getting the 'NoSuchElementException' error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Addition.main(Addition.java:16)
Enter First Integer:
I understand that this is probably due to something in the source code that is incompatible with the Scanner class from java.util, but I really can't get any further than this in terms of deducing what the problem is.
NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html
How about this :
if(input.hasNextInt() )
number1 = input.nextInt(); // if there is another number
else
number1 = 0; // nothing added in the input
You should use hasNextInt() before assigning value to variable.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available.
I faced this Error with nextDouble(), when I input numbers such as 5.3, 23.8 ... I think that was from my PC depending on computer settings that use Arabic (23,33 instead 23.33), I fixed it with add:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
You must add input.close() at the end...
This error is mostly occur in case of 0nline IDE's on which you are testing your code. It is not configured properly, as if you run the same code on any other IDE/Notepad it works properly because the online IDE is not designed such a way that it will adjust the input code of your format, So you have to take input as the Online IDE supports.
If I may, I solved this issue today by realizing that I had multiple functions that used an instance of a Scanner, each. So basically, try refactoring so that you have only one instance opened and then closed in the end - this should work.
For anyone using gradle's application plugin, you must wire it to the standard console in build.gradle(.kts) otherwise it will keep throwing the NoSuchElementException error if you try to use scanner.
For groovy:
run {
standardInput = System.in}
For gradle kotlin dsl:
tasks.withType<JavaExec>() {
standardInput = System.`in`}
Integer#nextInt throws NoSuchElementException - if input is exhausted
You should check if there is a next line with Integer#hasNextLine
if(sc.hasNextLine()){
number1=sc.nextInt();
}
I added a single static scanner (sc) at the top of my class and closed it (sc.close()) when coming out of the whole class wherever I used return statements. Again that's one instance of scanner as suggested by another answer, which should be static.
package com.example.com;
import java.util.Scanner;
public class someClass {
static Scanner sc = new Scanner(System.in);
//Whole world of methods using same sc.
//sc.close()); return;
}
Other than that you can add #SuppressWarnings("resource") on the top of the troubling method to make the warning go away. But be careful about resource leaks.

Running a scanner program

I am trying to write a program that basically will read any integer from 1,000 to 999,999 and will then display it with a comma separating the thousands. So far I have this, and eclipse doesn't like it. Why?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// Scanner scan = new scanner(system.in);
double value, integer;
System.out.println("Enter your value without a comma");
integer = scan.nextdouble();
System.out.println(integer,);
scan.close();
you have a lot of errors in the code which is why eclipse doesnt like it ;)
To name a few:
new scanner -> Scanner with capital S
system.in -> same with system
check out this snippet below and it will run just fine :)
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
double value, intValue;
System.out.println("Enter your value without a comma");
intValue = scan.nextDouble();
System.out.println(intValue);
scan.close();
}
Your code looks pretty problematic, to say the least. First of all, is the line in which you declare the Scanner supposed to be commented? If not, that could be part of the problem. You should watch out that you pass the upper-case System.in to your Scanner. You also want to use the nextDouble() method. (Java is case sensitive!) You also want to be careful in your second print statement that you do something more like System.out.println(integer+",");
So, first, the solution:
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
public class Ideone {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
long number = scan.nextLong();
NumberFormat f = NumberFormat.getInstance(Locale.ENGLISH);
System.out.println(f.format(number));
scan.close();
}
}
And the problems with you code:
the package declaration is commented, why ?
you import java.lang.* but you don't use it.
your main method throws java.lang.Exception, but I don't see anything in your code throwing that.
you have commented out the scan declaration.
scanner should have the first letter uppercase (java is case-sensitive), same thing for system
you declare a double called value, but you don't use it.
you declare a double called integer (when what you really want is an integer).
you use scan.nextdouble() instead of scan.nextDouble() (but remember, you want an integer, so you should call scan.nextInt()).
I don't see any code trying to put a "," in your number.
you print integer,, this is not even close to what you want, you could have tried integer+"," to concatenate, but it's also not what you want.
you are missing the closing brackets.
the indentation of your code is really bad.
You should have a look at https://stackoverflow.com/tags/java/info in the section Beginners' resources, and try to understand a little bit more and to solve some of your problems by yourself.
Why have you commented the scanner instantiation, also I see the typo in there. The compiler will throw an exception on uninitialized 'scan' object.
Scanner scan = new Scanner(system.in);
In addition to Micah answer, I would suggest you do a check on the input from users to check the range 1000 - 999,999 and re-prompt the user to input the value, if not it will beat the purpose of the range.
System.out.println("Enter your value without a comma");
integer = scan.nextDouble();
while (integer > 999999 OR integer < 1000)
{
System.out.println("Please keep your range in between 1000 - 999,999");
integer = scan.nextDouble();
}

Need help jumping into Java and Java input from C++

This is my first program in java and I haven't found any good websites like this one for C++ and it's confusing for me because I just started writing java and I just came from C++. Anyways, concerning this code, could someone explain how to fix this code because of the line containing Scanner and/or how to simply receive inputs, because I haven't found any simple way to translate cin >> from C++
public class input {
public static void main(String[] args) {
double total = 0;
Scanner in = new Scanner(System.in);
System.out.println("As you enter numbers, they will be added.");
System.out.println("Entering a non-number will stop the program.");
while (in.hasNextDouble()) {
double n = in.nextDouble();
total = total + n;
System.out.println("The total is " + total);
}
}
}
Your code works. Just make sure you have import java.util.Scanner. On a related note, use Eclipse or Netbeans as they would have told you this. Also, you should capitalize class names and put your class in a package instead of in the "default package". I recommend "Head First Java".
package sand1;
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
double total = 0;
Scanner in = new Scanner(System.in);
System.out.println("As you enter numbers, they will be added.");
System.out.println("Entering a non-number will stop the program.");
while (in.hasNextDouble()) {
double n = in.nextDouble();
total = total + n;
System.out.println("The total is " + total);
}
}
}
Here is output when I ran it. I think I might consider it a bug that I was able to hit enter with a blank line without it ending.
run:
As you enter numbers, they will be added.
Entering a non-number will stop the program.
12.2
The total is 12.2
43
The total is 55.2
a
BUILD SUCCESSFUL (total time: 11 seconds)
I'm at work and don't have the jdk installed, so I can't compile and run this. Giving a quick look though, it seems like the only thing you might have problem breaking out of the scanner, though. After entering a few numbers, try pressing ctrl-d - this should signal end of input.
As Borealid said you need to add the following line at the top of the class to get it to compile:
import java.util.Scanner;
Also note that by convention in java classes are named with an uppercase character Input, not input.
Finally, you can obtain input directly through System.in.read() and the other overloaded permutations of the read() method, against System.in
Check out the Java Tutorials,they're quite good for a beginner

Categories

Resources