I am using Java (VSC is my compiler).
I try to read through a document that is in the same folder. However, just scanning causes this error:
An error has occured.
java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Project1.results(Project1.java:66)
at Project1.main(Project1.java:87)
This is my whole code:
public class Project1() {
public void results(String fileName){
double x, y, xc, yc, rad, radius;
int number_of_circles = 0;
try {
Scanner scanner = new Scanner(new BufferedReader(new FileReader(fileName)));
while(scanner.hasNext()) {
x = scanner.nextDouble();
y = scanner.nextDouble();
rad = scanner.nextDouble();
if(rad > 0) {
number_of_circles++;
}
}
}
catch(Exception exception) {
System.err.println("An error has occured.");
exception.printStackTrace();
}
}
public static void main(String args[]){
Project1 P = new Project1();
P.results("Project1.data");
}
}
I tried different files with different values but it does not seem to help. Thanks. I looked at other threads, but they seem to not cover the exact same problem.
It looks like if I put only integer values inside Project1.data, then it works, but obviously I want to allow for other values
Project1.data values:
9.50 2.40 3.20
2.20 3.40 5.60
2.50 2.40 3.20
3.20 4.40 5.60
Is it possible that your locale expects , as separator, while your file contains . ?
Related question: Best way to parseDouble with comma as decimal separator?
Here is another related question with tips for Scanner: Java - Scanning comma delimited double and int values
Related
I am trying to make a program which averages two numbers.
public class Average
{
private double one, two, average;
public void setNums(double num1, double num2)
{
one=num1;
two=num2;
}
public void average( )
{
average = (one + two) / 2;
}
public void print()
{
System.out.print( one+" + "+two +"has an average of ");
System.out.printf("%.2d\n",average);
}
}
This is the error that comes out, I assume that its due to the formatting.
Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.base/java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:3138)
at java.base/java.util.Formatter$FormatSpecifier.(Formatter.java:2874)
at java.base/java.util.Formatter.parse(Formatter.java:2713)
at java.base/java.util.Formatter.format(Formatter.java:2655)
at java.base/java.io.PrintStream.format(PrintStream.java:1209)
at java.base/java.io.PrintStream.printf(PrintStream.java:1105)
at Average.print(Average.java:26)
at AverageRunner.main(AverageRunner.java:17)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Help pls.
Also, it compiles fine but inside the main method it will not run.
The issue is with this line:
System.out.printf("%.2d\n",average);
"%.2d\n" is a malformed format string for double. Replace it with "%.2f\n"
I'm struggling on this problem, given that I'm probably making a basic mistake or I haven't got a clue what I'm doing.
platform being a Zybook
the problem reads:
One lap around a standard high-school running track is exactly 0.25 miles. Write a program that takes a number of miles as input, and outputs the number of laps.Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
Your program must define and call a method:
public static double
milesToLaps(double userMiles)
It gives off a couple of example input 1.5 -> 6.00, 2.2 ->8.80 etc.
it gives you a start off of:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
}
}
Below I've edited to this point, still I don't think I know what I'm doing. However I've gotten it down to one error which states that> error: cannot find symbol numMiles.printMilesToLaps(userMiles);. I would like someone to tell me if I'm doing this someway maybe correctly and or if they can solve this error, cause I've completely redid the code multiple times, and I'm at the point of giving up and never submitting it.
also sometimes I start to remove code that's supposed to be there, but at the same time doesn't make sense to the computer ex. being (return;), but maybe you can explain it in greater detail then the zybook or its checking system.
The code itself looked a bit neater, but I was forced to change it after the multiple errors.
import java.util.Scanner;
public class LabProgram {
public static double MilesToLaps(double userMiles){
Scanner scnr = new Scanner(System.in);
userMiles = scnr.nextDouble();
System.out.printf("%.2f", (userMiles / 0.25));
}
public static void main(String[] args) {
LabProgram numMiles = new LabProgram();
numMiles.printMilesToLaps(userMiles);
}
}
I'm getting constant cannot find symbol errors, mostly on the secondary public method. I could think I could fix this, but it wouldn't line up with the question parameters.
I'm usually only using the example input values in the input terminal.
There are a few issues with your posted code. The method should be named milesToLaps (not MilesToLaps). The method takes the user's input, and does not prompt. The method should return the result, not output it itself. And, I would multiply by 4 instead of dividing by 0.25. Like,
public static double milesToLaps(double userMiles) {
return userMiles * 4;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double userMiles = scnr.nextDouble();
System.out.printf("%.2f%n", milesToLaps(userMiles));
}
Please go through some basic java tutorials(JavaTpoint, Toutrialspoint etc.) where you can get a basic understanding of class, object, methods how these things works.
public static double MilesToLaps(double userMiles)
{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a number");
userMiles = scnr.nextDouble();
double x = (userMiles / 0.25);
return x;
}
public static void main(String[] args)
{
//LabProgram numMiles = new LabProgram(); this object not require because your calling method MilesToLaps() is static.
double result = MilesToLaps(5); // here in this method you need to pass a double type value.
System.out.println("user miles :"+ result);
}
I'm having some problems with my file reader that uses scanner, and I'm at a bit of a loss at this point. Trying to read the file with scanner but atm I keep getting a java.util.InputMismatchException message which suggests that my scanner.next is putting the wrong files in the wrong arrays? I don't know why this is happening, if someone could point out in my code where I'm screwing up, I'd appreciate it.
Note: Unless it is relevant, ignore the useless variables and the excessively long arrays. I was getting ready to make this into a class and some variables are not used yet.
public static void main(String[] args) throws IOException
{
int playersTotal = 0;
int entries = 0;
int namesIndex = 0;
int attackIndex = 0;
int blockIndex = 0;
String[] playersName = new String[60];
double[] attackScores = new double[60];
double[] blockScores = new double[60];
String file = "roster1.txt";
Scanner scanner = new Scanner(new File(file));
scanner.useDelimiter(" ");
while(scanner.hasNextLine())
{
playersName[namesIndex] = scanner.next();
System.out.println(playersName[namesIndex]);
namesIndex ++;
playersName[namesIndex] = scanner.next();
System.out.println(playersName[namesIndex]);
namesIndex ++;
entries ++;
attackScores[attackIndex] = scanner.nextDouble();
System.out.println(attackScores[attackIndex]);
attackIndex ++;
entries ++;
//problem occurs here:
blockScores[blockIndex] = scanner.nextDouble();
System.out.println(blockScores[blockIndex]);
blockIndex ++;
entries ++;
playersTotal ++;
}
}
This should take every entry separated by a space from a list with both Strings and doubles on every line and save it to their proper arrays. However it only ever reaches the first double on the first line. Attempting to read the next double prompts an exception in thread.
Program output:
Rachael
Adams
3.36
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at VerdeVolleyball.main(VerdeVolleyball.java:37)
list I'm using:
1. Rachael Adams 3.36 1.93
2. Kim Hill 1.53 1.76
3. Tori Dixon 0.92 1.62
4. Alisha Glass 1.96 1.55
5. Cursty Jackson 0.69 1.44
6. Michelle Bartsch 0.28 1.42
7. Alexis Crimes 3.89 1.34
8. Foluke Akinradewo 4.81 1.14
9. Courtney Thompson 0.59 0.93
10. Krista Vansant 2.78 0.86
11. Nicole Fawcett 4.01 0.61
12. Kelly Murphy 1.15 0.58
13. Natalie Hagglund 2.49 0.52
14. Kayla Banwarth 2.98 0.5
15. Lauren Gibbemeyer 2.25 0.5
Try to comment out the line where you specify the delimiter for Scanner instance
scanner.useDelimiter(" ");
and be sure that your Scanner instance uses proper locale when resolving double (. separator instead of ,).
Scanner scanner = new Scanner(new File(file).useLocale(Locale.US);
I got to calculate the factorial of a number. As a fact factorial of 0 is 1. So I included that case in the function as well.
here's the code:
import java.util.*;
public class Factorial {
static int fact(int n) {
int result;
if (n == 0 || n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
public static void main(String args[]) {
int i, fact = 1;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
}
but if I'm giving input as 0, some exception was raised
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Factorial.main(Factorial.java:14)
How to resolve this situation?
Edits:
I have changed the exception.All apologies for the thing that yes the code wasn't even 26 lines. I had put some code above as comments before posting just the code here.
This ain't a duplicate. As of the fact I want to know why it doesn't accept 0 as an input. It works perfect for all other inputs.
I use an online Compiler https://www.tutorialspoint.com/compile_java_online.php
Works fine with Java Compiler of the PC JDK 1.7 ,but raises exception on online IDE.
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. Link.
Modified your code and added hasNextInt so that NoSuchElementException is not thrown and sc.close() to close the resource at the end of main method
public static void main(String args[]) {
int fact = 1;
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
sc.close();
}
The online IDE is probably doing some kind of pre-processing of the data that
don't plays very nice with zeros.
TutorialPoint has online compilers for multiple languages and is very likely
that these all share some common backend that does the magic of passing text
from your browser to their servers. I'm not sure what kind of processing is
happening behind but I can imagine that is something like trimming the
unnecessary zeros from the left of the numbers or something like that.
I have encountered the opposite problem in standard C with the function sscanf,
which expected to fail (return 0) when the input string is empty just like its
sister function scanf but it still returns sucess and stores zero in the integer
variables.
By the way, if you just add a leading space or \n to the zero, everything works
just fine.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My very simple program should sort out the maximum one among 3 numbers. I have used a static method for algorithm and called that into the main method. User should enter 3 floating numbers by using a space. afetr pressing enter the program should print out the biggest floating number. But it doen't. It just shows a bunch of errors. The attachment shows what error I have:
MaximumFinder.java:
package maximumfinder;
import java.util.Scanner;
public class MaximumFinder {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
System.out.println("Enter 3 floating-pont value separated by space:");
double num1 = inScanner.nextDouble();
double num2 = inScanner.nextDouble();
double num3 = inScanner.nextDouble();
double result = maximum(num1, num2, num3);
System.out.println("Maximum number is: "+result);
}
public static double maximum(double x, double y, double z) {
double maximumValue = x;
if (y > maximumValue)
maximumValue = y;
//statement
if (z > maximumValue)
//statement
maximumValue = z;
return maximumValue;
}
}
If I exclude the package declaration it is working perfectly fine for me
Just make sure that the class is in the right package.
Note : compile & run from command line.
Why dont you simply use the max() method from Java? It may solve your problem...
EDITED
I've tried your code and it runs perfectly, but I got the same error as you, if I type the double numbers using dots, like "3.5". If I type the numbers using commas("3,5") the program is executed till the end.
I hope this help you.
public static double maximum(double firstValue, double... otherValues) {
double maximumValue = firstValue;
for (double v : otherValues) {
maximumValue = Math.max(maximumValue, v);
}
return maximumValue;
}