My file isn't opening in cmd - java

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);

Related

java.util.IllegalFormatConversionException: f != java.lang.Integer [duplicate]

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.

java: Scanner asks for an extra value when using useDelimiter

So I wanna create this program that stores 4 values. the first one being string and the remaining 3 being integers. However, when i enter 4 values and press enter, i get an error java.util.InputMismatchException but when I enter 5 values, i get the result for my for values. for example lets say i input the following values:
Japan,1,2,3
I will get the java.util.InputMismatchException error. And if I enter the following values:-
Japan,1,2,3,4
I get the output as I want:-
Japan,1,2,3
Why is this happening? Here is my code
public class satisfaction {
public static void main(String args[])
{
Scanner src= new Scanner(System.in);
src.useDelimiter("\\,|\\n");
String name=src.next();
int a=src.nextInt();
int b=src.nextInt();
int c=src.nextInt();
System.out.println(name+","+a+","+b+","+c);
}
}
I've tested this a bit myself, and I think the \n in the pattern is not matching the line ending used by your console.
For me, I had to use \r\n instead, but you could also use System.lineSeparator() e.g. like this:
src.useDelimiter(",|" + System.lineSeparator());
The way it's written, it needs another comma at the end of the input. I would recommend checking the string to make sure it ends in a comma, and if not, append one.
I believe that if you enter Japan,1,2,3, it will give you the output you want.

Why isn't eclipse letting me type for Scanner?

I had made a program which takes info from the user about a class (Its name, data members, methods, etc.) and prints the code with indentation.
However when I run it in Eclipse (Version: Luna Service Release 1a (4.4.1)
Build id: 20150109-0600), It does not allow me to type the number of Data Members and throws a NoSuchElementException.
This is my code snippet:-
static void initDataMembers(DataMembers[] var, Classes belongTo) {// for
// constructor
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of Data Members in class "
+ belongTo.name + " :-");//It doesn't even let me input
int num = sc.nextInt();
var = new DataMembers[num];
if (var.length > 0) {// i.e. if there are variables, init. them with
// constructor
for (int i = 0; i < var.length; i++) {
System.out.println(belongTo.name + ": Data member " + (i + 1));
var[i] = new DataMembers(belongTo);
}
}
sc.close();
}
My output comes thus:-
Enter name of the class:-
Xyz
Enter no. of Data Members in class Xyz :-
Exception in thread "main" java.util.NoSuchElementException
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 udc.JavaBody.initDataMembers(JavaBody.java:19)
at udc.Classes.<init>(Classes.java:40)
at udc.UserDefinedClass.<init>(UserDefinedClass.java:8)
at udc.UserDefinedClass.main(UserDefinedClass.java:12)
After further checking, I found out that the exception is only thrown when there is nothing typed. Problem is, the Eclipse console is not even letting me input it. Is it a problem with the software or is it my code's fault?
While doing Run As go into the run configurations.
On the Arguments tab of your Java run configuration, pass your argument(type the input numbers separated by spaces or newline.)

How to use variable outside of try-catch block

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:27‌​2)
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 ... :-)

Not getting user input as required in Java

I am new to java but not to programming as I know C++.
I am simply trying to get input from user either of integer or string form but when i execute my program, it just stands still and does nothing until I press enter.
My program and result after pressing "Enter" is given.
My question is "why I am not getting user input?"
import java.util.Scanner;
class roomarea
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println("Enterd value is " + input);
}
}
the result is
Start Running math >Command: "C:\Program Files\Java\jdk1.6.0\bin\java.exe"
-classpath "C:\Documents and Settings\Ahmad Abdullah\My Documents\NaviCoder IDE for
Java\projects\math\output\classes";"C:\Program Files\Java\jdk1.6.0\jre\lib\rt.jar";
roomarea
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:840) 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
roomarea.main(Main.java:14) >Run
Process Completed
When you say "it just stands still and does nothing untill i press enter", it is doing exactly what you told it to - it is waiting for you to input an int. You just hitting enter meant that there was no input, which your scanner could not interpret as an int, hence the exception.
If you enter an integer number then press the enter key, your program should work.
Your program should work if you enter an int as input. (By pressing Enter while "waiting" for the program, you could arise the exception you're talking about).
If you enter a char for example, you'll get InputMismatchException exception:
Thrown by a Scanner to indicate that the token retrieved does not
match the pattern for the expected type, or that the token is out of
range for the expected type.

Categories