How to use variable outside of try-catch block - java

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 ... :-)

Related

Finding hashtags in a input string from a user [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.

How to resolve InputMismatchException in Java

I'm trying to read a .adi file that has a line format of String, Int and Double.
For example:
Ford,Fusion,2010,85254,12855.58
For the code, I'm required to use a try-catch statement and the method header has to throw the exception. Furthermore, I have a while statement inside the try block to process the data, however I keep getting the InputMismatchException thrown.
So it looks like:
try{
Scanner scan = new Scanner(inventoryFile)
scan.useDelimiter(FIELD_SEPARATOR);
while(scan.hasNext()) {
String make = scan.next();
String model = scan.next();
int year = scan.nextInt();
int mileage = scan.nextInt();
double price = scan.nextDouble();
Automobile auto = new Automobile(make, model, year, mileage, price);
fileInventory.add(auto);
}
May I know how to resolve this issue? Thanks in advance.
You didn't specify, but I presume FIELD_SEPARATOR is set to ",". So rather than the default (whitespace) it is expecting ONLY single commas to delimit fields.
The first line ends with a newline character, which does not terminate the last field, so it's waiting until it reads the next line and attempts to scan the value from the first line concatenated with \n and the name from the second line.
So, for instance, for this input
-Ford,Fusion,2010,85254,12855.58
-Chevy,Silverado,2015,66454,17333.00
what your code actually sees is
-Ford,Fusion,2010,85254,12855.58\n-Chevy,Silverado,2015,66454,17333.00
and it's splitting on commas only, so the price field contains 12855.58\n-Chevy, which is clearly not a valid number.
I personally hate that Scanner was included in Java, it is the cause of an incredible amount of grief for beginners and is responsible for many, many questions here.
The simple fix in your case is to add one line
double price = scan.nextDouble();
scan.nextLine(); // ADD THIS LINE
to skip to the start of the next line.

My file isn't opening in cmd

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

Why am i getting a runtime error while submitting this code online?(jdk 1.7)

This is the code (used IntelliJ idea jdk 1.8)
It worked well for me but shows a runtime error whenever I submit it in an online portal (jdk 1.7). What changes should I make?
I have no idea what is causing the error.
import java.lang.String;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException{
int n,k;
int i=0;
int sum=0;
do {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
n = Integer.parseInt(s);
String s1 = reader.readLine();
k = Integer.parseInt(s1);
reader.close();
}while ( n<0 || k>java.lang.Math.pow(10,9) || n<k );
for (i=0 ; i<=k ; i=i+2){
sum+= fact(n)/(fact(i)*fact(n-i));
}
System.out.print(sum);
}
public static int fact(int n) {
int j=1;
while(n!=0){
j=j*n;
n--;
}
return j;
}
}
I prefer not to use Scanner
Error :
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Main.main(Main.java:18)
The stack trace is pretty clear that the problem arises from Main.main() passing null to Integer.parseInt(). It reports the parseInt() invocation appearing on line 18 of Main.java; that doesn't line up perfectly with your source as you presented it, but it's about right for this line:
n = Integer.parseInt(s);
The string s at that point was just obtained via your BufferedReader's readLine() method -- this indicates that there are no more data available from the underlying stream (ultimately, System.in).
That might be a bit surprising if it happened on the first iteration of your loop, but you close the BufferedReader yourself at the end of that iteration, and that closes all the wrapped Readers and InputStreams as well. On the second iteration, System.in is closed, and you are unable to read anything from it. You should instead initialize your BufferedReader outside the loop, and wait to close it until after you exit the loop:
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
do {
// do something with 'reader'
} while ( /* some condition */ );
reader.close();
Even if you were not closing the underlying stream, you certainly are buffering input from it, and then potentially tossing some of that buffered input along with the BufferedReader. That in itself could cause your program to observe end-of-file earlier than it expected. That might happen, for example, if you moved the close() outside the loop, but still created and read from a new BufferedReader on each iteration of the loop.
Moreover, it is wise to check upon each read whether a line was read successfully, and to handle the case where none was (indicated by null being returned). For a submission to an online solution checker, however, it might be reasonable to assume that the input will conform to your expectations.
Often when using Online IDEs / compilers, you need to type the input before you run your program. The online tools may not prompt you for input, which can lead to your variables being set to null. A null variable will cause the error you are seeing.
How exactly to fix this depends on which online tool you are using. For example, if you are using Ideone, type your input into the "enter input (stdin)" or the "input" textboxes before running your program. For your program, since you are using readLine(), put the input on separate lines, as seen in this picture.
I copy and pasted your code into Ideone. If I didn't enter anything into the input textbox, I got the same error you saw. But if I entered the input before running the program, your code ran without errors.
You have to make sure the string returned from readline() is number and not null.

Using substrings while reading file data

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

Categories