This question already has an answer here:
String.Format for rounding, can't locate illegal format conversion source error?
(1 answer)
Closed 1 year ago.
I'm trying to create a simple java program that reads a floating-point number, calculates it using an equation with Euler's number then converts the results from double to int. I can get it to compile without errors but after I input the floating-point numbers I get the error:
nB = Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at Ex4.main(Ex4.java:16)
Its only a few lines of coding and I just created a similar program that works fine, so I don't understand what's wrong here! I'm thinking it might have to do with the line on Euler's number since I don't fully understand all the math functions yet, but I've used π just fine before the exact same way. Or is it because the final conversion step is wrong? Sorry if it's something super obvious, i've tried my best to debug it so many times but any time I change a part I think could be the issue I end up with so many more errors. Here is the code:
import static java.lang.Math.*;
import java.util.Scanner;
class Ex4
{
public static void main( String [ ] args)
{
Scanner input = new Scanner(System.in); //import scanner and ask user to input number
System.out.print("Please enter a floating-point number: ");
double nA = input.nextDouble();
double nB = Math.pow(E, nA); //mathematical equation
int value = (int) nB; //convert nB to an int
System.out.printf("nB = %f", value);
}
}
Pitifully small and simple, I know ;_; I also tried looking up similar questions on here but all the errors any commenters found I triple checked were right in mine. Also if anyone could help me understand the error message better as well, i'd really appreciate it. Thank you!!
Try using %d instead of %f:
System.out.printf("nB = %d", value);
For more details on formatting consult this page.
Related
Hi I am totally new in Java and don't know much about it .I Have just made a program and not sure if it's correct.I want a input from user so that it will calculate the answer.Here's the code:
import java.util.Scanner;
class Vedant
{
public static void main(String[] args)
{
Scanner inputa=new Scanner(System.in);
int b=inputa.nextInt();
if(b<20);
int a=5;
{
System.out.println("Answer ="+a);
}
}
}
When I run this file in cmd it does nothing.It doesn't even ask for input.If I type random things and press enter it gives me this
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Vedant.main(Vedant.java:8)
Please help.And yeah I am just a beginner
When I run this file in cmd it does nothing.
That's incorrect
It doesn't even ask for input
You didn't tell it to, the command you gave is inputa.nextInt() which only reads input, but doesn't output anything.
If I type random things and press enter it gives me this
inputa.nextInt() means "read the next input as a number". If you're typing random things it can't convert it to a number.
There are some more issues with your code:
if(b<20);
The semicolon at the end means that nothing is done if b actually is less than 20
int a=5;
{
System.out.println("Answer ="+a);
}
The parentheses are not needed here, and because you explicitly set the variable a to 5 your application, if it gets this far, will always say Answer =5
If you are wanting it to ask for a number. You have to tell it to ask for a number like so.
System.out.println("Enter a number.");
By what you typed in your code it seems like you are trying to add 'b' and 'a' for "Answer". If so, it will be easier for you to make a new variable that is adding 'a' and 'b'.
int answer = a + b;
System.out.printf("Answer = %d", answer);
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
I am making a decryption program and I'm not quite sure how to use the variable "cip" out side of my try catch block. I tried moving the 3 lines of where is asks user to input pattern but i ran into other problems.
my code is:
import java.util.*;
public class unscrambler //This class will encrpyt the program
{
public static void main (String [] args){
int cip= 0;
String user ="";
System.out.println("Please enter the code to unscramble");
Scanner inputScanner = new Scanner(System.in); //imports scanner reader
String userinput = inputScanner.next();
char[] charArray = userinput.toCharArray(); //sends userinput to charArray
int j=charArray.length;
Character [] array = new Character[j];
for(int w=0; w<j; w++){
array[w] = charArray[w];
}
int a=1;
System.out.println("Please enter the number cipher pattern (an integer)");
do{
try{
user = inputScanner.next();
cip = Integer.parseInt(user);
a=2;
System.out.println("your code is ");
for(int w =0; w<j;){
System.out.println(charArray[j]);
w+=cip;
}
if(cip<=0){
System.out.println("please enter number greater than zero");
a=1;
}
}catch(NumberFormatException f){
System.out.println("please enter a proper number");
}
}while(a==1);
}
}
You're only making the declarations in that block.
String user = inputScanner.next();
int cip = Integer.parseInt(user);
Add these to the start of the file, just after the main() line:
int cip = 0;
String user = "";
The errors after just moving (without the = stuff) indicate that you're using cip after the try block, so we need to initialise it with empty data in case the try fails.
Now just change the lines that you've currently got in the try block to:
// Remove the 'String' part.
user = inputScanner.next();
// Remove the 'int' part.
cip = Integer.parseInt(user);
And then you can move on to the next unrelated bug.
The solution is to either move the variable declaration outside of the loop, or move the place you want to use it inside the loop.
Java doesn't allow you to use a local variable outside of the scope in which it was declared. Period.
I tried moving the 3 lines of where is asks user to input pattern but i ran into other problems.
Well ... you need to solve those other problems!
Programming is like this. You need to work within the constraints of the programming language that you are using.
I can see what is causing your latest error, but I'm not going to tell you what it is. Instead, I'm going to tell you how to find it for yourself.
The "line upon line of output" is a Java Stacktrace. It contains A LOT of useful information, and you need to learn how to interpret it.
java.lang.ArrayIndexOutOfBoundsException: 5
at unscrambler.main(unscrambler.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Stacktraces typically report an exception that has been thrown somewhere in your running program.
Step 0: Find the stacktrace.
The first line gives the name of the exception, and the message. In this case, the name of the exception is ArrayIndexOutOfBounds and the message is (just) "5".
Step 1: If you don't recognize the name of the exception, look it up in the javadocs.
Here it is: link. Read it now.
Step 2: Try to understand the message. In this case, you just need to know that the message is the value of the index that was out of range. But you should be able to guess that ... based on the javadoc for the exception. (Usually the messages are a bit more informative, but this one is being thrown from compiled code, and for technical reasons a more informative error would be difficult to produce.)
The second line of the stacktrace tells you where the exception was thrown. In this case, line 35 of "unscrambler.java" ... in the main method.
Step 3: Open the source file in an editor or your IDE, and see what the code at that line says.
In this case it is (I think) this line:
System.out.println(charArray[j]);
Step 4: Now you have to start thinking. (Thinking is a very important part debugging!) How can that line have possibly thrown that exception? What could have caused that?
In this case, the first think to observe is that there is only one place on that line where you are doing array indexing, and it is the expression charArray[j]. So that means that ... (you fill in the details). But were did ... (you fill in the details) come from? Take a look at what happened before this statement. See it yet? (If no, then look again. It should be really obvious if you look carefully!)
The rest is for you to sort out ... :-)
import java.util.Scanner;
class Calculator
{
public static void main(String args[]){
Scanner mortgage = new Scanner(System.in);
System.out.println(mortgage.nextLine());
double iRate;
double lAmount;
double answer;
System.out.println("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println(answer);
}
}
My question is I don't think I am declaring the double correctly and am getting an error. How do I declare the double correctly so the program runs without error
That code compiles fine although:
System.out.println(mortgage.nextLine());
seems a bit strange since you wait for a line then print it out. Not sure why you would want to do that.
The following code with that line removed and some cosmetic changes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner mortgage = new Scanner (System.in);
double iRate, lAmount, answer;
System.out.println ("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println ("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println ("Answer is " + answer);
}
}
outputs:
Enter interest rate
10
Enter loan amount
50000
Answer is 50010.0
You may also want to rethink the way in which you do interest rate calculations. Anyone who's ever done work for a bank would get a giggle out of that.
The general way to calculate the interest due on some capital for a given percentage rate would be something like:
answer = iRate / 100.0 * lAmount;
although I realise you may have intended to clean that up once you get past your immediate problem, so apologies for that friendly jab :-)
I'm having to guess since you didn't specify the error, but it's likely coming from your usage of mortgage.nextDouble();. nextDouble(); will read JUST the next double from the line you type in, meaning there will be a trailing newline character at the end, which will result in it behaving in ways you don't expect.
There's a few alternative ways to go about it, so I'll just show one here:
double iRate;
iRate = Double.parseDouble(mortgage.nextLine());
Mind you, this does as much sanity checking as your code (as in, none!). What this does is read in a line of input, and then have the Double class convert the resulting String into a Double, which is stored in the double iRate.
If you want your "Enter interest rate" line to appear first, remove System.out.println(mortgage.nextLine());; it's not doing anything. Your program is waiting for an input before it can proceed, which I think was your problem.
Don't use double's (or float's) for money or any other calculations, have a look at this article "don't use floats for money". basicly it IEEE 754 giving you all kind of rounding errors.
Last night I asked a question like this, I'm not sure what's happening and I have encountered another problem so here goes:
My instructor has given my class a project a program that reads a file, reads each letter and then prints out the amount of hits, outs, walks and sacrifice flies that each line has. I posted some more info in my original question about this topic.
I have rewritten the code in chance that I would better my chances of getting the program to work. I learned about what substrings are and a bit more about tokens and came together with this program:
import java.util.Scanner;
import java.io.*;
public class BaseballStats
{
public static void main(String[]args) throws IOException
{
Scanner fileScan, lineScan;
String fileName;
int oCount = 0, hCount = 0, sCount = 0, wCount = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
fileName = scan.nextLine();
fileScan = new Scanner(new File(fileName));
while (fileScan.hasNext())
{
lineScan = new Scanner (fileName);
lineScan.useDelimiter(",");
String input = lineScan.nextLine();
int point =(input.indexOf(","));
String name = input.substring(0,point);
String records = input.substring(point,input.length());
for (int i = 0; i < records.length(); i++)
{
if (records.charAt(i) == 's')
sCount++;
else if (records.charAt(i) == 'o')
oCount++;
else if (records.charAt(i) == 'h')
hCount++;
else if (records.charAt(i) == 'w')
wCount++;
}// end of for loop
System.out.printf("Name: %s. Hits: %d. Outs: %d. Walks: %d. Sacrifice flies: %d.", name, hCount, oCount, wCount, sCount);
System.out.println();
}//end of while loop
}//end of main
}// end
The program runs fine, but after I enter in stats.dat(The file that is supposed to be reading), I get the following exception error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at BaseballStats.main(BaseballStats.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
It points to line 25, which is the
String name = input.substring(0,point);
line. I have been stumped on this, am I missing something?
Note: I have read Adamski's suggestion on the original question. I tried to follow it but as I'm new to java I'm having a hard time understanding encapsulation, specifically the setter and getter methods. I figured it would be best to leave them alone for now until next chapter, where my class explains them.
What you're dealing with is called an "edge condition." It's a situation that isn't the most common situation for your algorithm. But you have to deal with the rare situations as well to avoid errors.
You've got the following code:
String input = lineScan.nextLine();
int point =(input.indexOf(","));
String name = input.substring(0,point);
This is a problem of bug diagnosis (which programmers do all day long.) You need to now ask yourself the following:
What does "StringIndexOutOfBoundsException" mean? Google will tell you that.
How could that possibly be? What would cause that error when calling substring? (Google java substring to see what causes substring could throw that exception.)
This will have you looking at the indexOf() method (again, google is your friend) and what kind of results would come back from that that could lead to that stack trace.
What kind of input could lead to THAT situation?
Hope that gets you moving forward again.
String#indexOf(String) returns -1 if the passed in parameter is not found in this String.
So, input is likely not finding a , in it:
int point =(input.indexOf(","));
And when you pass in a negative index into String.substring(int, int), an StringIndexOutOfBoundsException will be thrown.
String name = input.substring(0,point); // input.substring(0, -1); will throw the exception