trying to make program rotation of array, it was giving an Exception by user misinput so I use try block but now, under try block it is not initializing values....
Can some one tell the reason or solution for this....
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
System.out.println("Enter T : ");
int t = sc.nextInt();
sc.nextLine();
while(t!=0){
System.out.println("\nEnter N D : ");
String s = sc.nextLine();
s.trim();
String st[] = s.split(" ");
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
System.out.println("Enter Element : ");
s=sc.nextLine();
st = s.split(" ");
ar.rotateArray(st,n,d);
t--;
}
}
If you need valid input and you did not get valid input, the thing to do is to try again to get valid input, after telling the user the input was invalid. Don't just proceed with the invalid data. You therefore need an inner loop:
while (t!=0) {
boolean validInput = false;
while (!validInput) {
System.out.println("\nEnter N D : ");
String s = sc.nextLine().trim();
String[] st = s.split(" ");
int n,d;
try {
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
validInput = true;
}
catch (Exception e) {
System.out.println("Invalid input");
}
}
… process n and d as before …
}
For my taste the loop to get the valid input would be better off being a subroutine in its own right - for clarity.
Variable in local scope should be initialized , that is what error , so do initialize the variables n and d to some integer value say as below
int n = 0 ,d = 0;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}
When a method throws an exception, that method never returns.
This means that if n = Integer.parseInt(st[0]); throws an exception, it does not return a value, which means n will not be assigned a value (since there is no return value to assign to it).
You are ignoring the exception and trying to continue as if nothing went wrong. But something did go wrong—n was never assigned a value. So the compiler tells you that it is not safe to use n in any subsequent code.
To solve this, you first must decide what to do if the user provides invalid input. You can’t just ignore the exception. If the input doesn’t represent two integers, you don’t have any values to work with. You can’t continue in any meaningful way.
The best course of action is to remove your try and catch. This will cause the program to terminate if Integer.parseInt fails, which is almost certainly what you want (unless your assignment requires you to do something different). Remember that it is not possible to continue in any meaningful way without values assigned to n and d.
In other words, change this:
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
to this:
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
As a side note, this line does nothing:
s.trim();
…because Strings cannot be changed. s.trim() returns a new String which you must capture in a variable. You probably want to do this:
s = s.trim();
Your image is quite misleading and really doesn't point to the actual problem, it only points to what you perceive to be the problem. Your mistake was placing the initialization of variables n and d into a try block which takes your call to the rotateArray() method out of scope for that initialization of those variables.
The bigger problem is... What in the world are you rotating? Where is the Array to rotate? Is it actually a String Array or is it suppose to be an Integer Array? Please don't tell me it's the st[] String Array (which is what you're trying to do) because according to your code that array is used to establish the array size (n) portion to work with and the number of elements (d) the User wants to rotate by. No rocket science to rotate an Array with only two elements. Give the rotateArray() method an array to actually rotate.
Let's provide an Integer Array and a way to do this without a try/catch mechaism:
// The Array to carry out rotations on.
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String ls = System.lineSeparator();
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
int t = 0;
String value = "";
while (value.equals("")) {
System.out.print("Enter Number of times to Rotate Array: --> ");
value = sc.nextLine().trim();
/* Make sure a String representation of a Integer value is supplied.
The regular Expression "\\d+" in the String#matches() method
ensures the a numerical integer string is supplied. */
if (!value.matches("\\d+" || value.length() > 9) {
/* Will handle situations where nothing is supplied, alpha
characters might be supplied, or the supplied numerical
value is outrageously large. */
System.out.println("Invalid integer numerical value supplied!" + ls);
value = "";
}
}
t = Integer.parseInt(value);
while (t != 0) {
System.out.println();
System.out.print("Enter the Size (portion) of the Array to consider and the" + ls
+ "number of elements to rotate (separated with a space): --> ");
String s = sc.nextLine().trim();
// Quit if anything starting with the letter "Q"
// (like "q" or "quit") is supplied.
if (s.substring(0, 1).equalsIgnoreCase("q")) {
System.out.println("\"Quit\" Supplied!");
System.exit(0);
}
String st[] = s.split(" ");
/* Make sure two values were supplied and that
they are both numerical integer strings. */
if (st.length != 2 || !st[0].matches("\\d+") || !st[1].matches("\\d+")) {
System.out.println("Invalid Input! Try again and make sure 'both' "
+ "values are numerical Integers.");
continue;
}
// Declare and initialize the n and d variables.
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
/* If the number of elements to rotate is greater
than the portion of array to rotate in. */
if (d >= n) {
System.out.println("Invalid Input! The size of the Array portion to rotate" + ls
+ "must be greater than the number of elements to rotate.");
}
/* If the supplied Array size to deal with is
out of bounds of the Array itself. */
else if (n < 1 || n > array.length) {
System.out.println("You have supplied an invalid Array Size! (" + n
+ ") Size must be between 1 and " + array.length + "!"
+ ls);
}
/* If the supplied number of elements to rotate
is less than 1 or greater than the total number
of elements - 1. */
else if (d < 1 || d > (array.length - 1)) {
System.out.println("You have supplied an invalid number of elements to rotate! (" + d
+ ") Value must be between 1 and " + (array.length - 1) + "!" + ls);
}
// All is good - Do the rotation.
else {
ar.rotateArray(array, n, d); // Rotate the Array
// Display the current rotation...
System.out.println("Current Rotation: --> " + Arrays.toString(array));
t--;
}
}
// Done
The error you outline in your image is a general compilation error and is relatively generic for all data types. This error occurs when you are trying to use a local variable without first initializing it. You won't get this error if you use a uninitialized class or instance variable because they are initialized with their default value (for example: Reference types are initialized with null and integer types are initialized with zero), but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is going to use it, you will receive this error. You of course will not get this error if you just declare the local variable but don't use it but then, why declare it in the first place.
Everyone is stating to initialize the local variables n and d because in reality, in order to successfully compile your code that is exactly what needs to be done in order for the rotateArray() method (which uses these uninitialized variables) to function. Again in reality, you do initialize them however your code does it within a try{} block which alters scope and the compiler is smart enough to know that if the initialization fails within the try{} block then the catch{} block could let that failure be ignored. In fact, if you were to place the call to the rotateArray() method within that try{} block then you would not get this compile time error since the call is within the scope of of where the variables n and d are actually initialized. You know, a decent IDE (line Eclipse, NetBeans, InteliJ, etc) should catch this error for you long before you try to compile.
According to your code, the actual intent of the try/catch blocks would be to handle the case of invalid input whereas a non-numerical integer value was supplied by the User. In this case it would be up to your catch{} block to handle that particular situation which should be to inform the User of the invalid input and then continue to re-prompt for proper input. At compile time the compiler really doesn't care about this mechanism since this would be a Runtime Error unless of course it is syntax related.
Nothing wrong with try/catch, I just like to avoid them if I can.
Related
double pullPrice(String input){
if(input.length() < 3){
System.out.println("Error: 02; invalid item input, valid example: enter code here'milk 8.50'");
System.exit(0);
}
char[] inputArray = input.toCharArray();
char[] itemPriceArray;
double price;
boolean numVal = false;
int numCount = 0;
for(int i = 0; i <= inputArray.length-1; i ++){
//checking if i need to add char to char array of price
if(numVal == true){
//adding number to price array
itemPriceArray[numCount] = inputArray[i];
numCount++;
}
else{
if(inputArray[i] == ' '){
numVal = true;
//initializing price array
itemPriceArray = new char[inputArray.length - i];
}
else{
}
}
}
price = Double.parseDouble(String.valueOf(itemPriceArray));
return price;
}
Problem: attempting to pull the sequence of chars after white space between 'milk 8.50' as input. Initialization error occurs because I am initializing char array inside an if else statement that will initialize the array if it finds whitespace.
Question: since I don't know my char count number until I find a whitespace is there another way I can initialize? Does the compiler not trust me that I will initialize before calling array.
Also, if I am missing something or there are better ways to code any of this please let me know. I am in a java data structures class and learning fundamental data structures but would also like to focus on efficiency and modularity at the same time. I also have a pullPrice function that does the same thing but pulls the item name. I would like to combine these so i don't have to reuse the same code for both but can only return items with same datatype unless I create a class. Unfortunately this exercise is to use two arrays since we are practicing how to use ADT bags.
Any help is greatly appreciated?
Try something like this:
double pullPrice(String input)
{
try
{
// Instantiate a new scanner object, based on the input string
Scanner scanner = new Scanner(input);
// We skip the product (EG "milk")
String prod = scanner.next();
// and read the price(EG 8.5)
double price = scanner.nextDouble();
// We should close the scanner, to free resources...
scanner.close();
return price;
}
catch (NoSuchElementException ex)
{
System.out.println("Error: 02; invalid item input, valid example: enter code here 'milk 8.50'");
System.exit(0);
}
}
If you are sure that you program will get only proper input data then just initialize your array with null:
char[] itemPriceArray = null;
The main problem why the compiler is complaining - what happens if your program accesses uninitialized variable (for instance with wrong input data)? Java compiler prevents this kind of situations completely.
I will add to the other answers,
since you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
int oldItems[] = new int[10];
for (int i=0; i<10; i++) {
oldItems[i] = i+10;
}
int newItems[] = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;
char[] itemPriceArray = new char[inputArray.length];
I made this program in java, on the BlueJ IDE. It is meant to take a number in the decimal base and convert it into a base of the users choice, up till base 9. It does this by taking the modulus between two numbers and inserting it into a string. The code works till the input stage, after which there is no output. I am sure my maths is right, but the syntax may have a problem.
My code is as follows:
import java.util.*;
public class Octal
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int danum = 0;
int base = 0;
System.out.println("Please enter the base you want the number in (till decimal). Enter as a whole number");
base=in.nextInt(); //This is the base the user wants the number converted in//
System.out.println("Enter the number you want converted (enter in decimal)");
danum=in.nextInt(); //This is the number the user wants converted//
while ( danum/base >= base-1 && base < danum) {
int rem = danum/base; //The number by the base//
int modu = danum % base;//the modulus//
String summat = Integer.toString(modu);//this is to convert the integer to the string//
String strConverted = new String();//Making a new string??//
StringBuffer buff = new StringBuffer(strConverted);//StringBuffer command//
buff.insert(0, summat); //inserting the modulus into the first position (0 index)//
danum = rem;
if ( rem <= base-1 || base>danum) {//does the || work guys?//
System.out.println(rem + strConverted);
}
else {
System.out.println(strConverted);
}
}
}
}
I am very new to Java, so I am not fully aware of the syntax. I have done my best to research so that I don't waste your time. Please give me suggestions on how to improve my code and my skill as a programmer. Thanks.
Edit (previous answer what obviously a too quick response...)
String summat = Integer.toString(modu);
String strConverted = new String();
StringBuffer buff = new StringBuffer(strConverted);
buff.insert(0, summat);
...
System.out.println(strConverted);
Actually, strConverted is still an empty string, maybe you would rather than display buff.toString()
But I don't really understand why making all of this to just display the value of modu. You could just right System.out.println(modu).
I assume that you want to "save" your value and display your whole number in one time and not each digit a time by line.
So you need to store your number outside of while loop else your string would be init at each call of the loop. (and print outside)
So, init your StringBuffer outside of the loop. you don't need to convert your int to String since StringBuffer accept int
http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#insert-int-int-
(You could even use StringBuilder instead of StringBuffer. It work the same except StringBuffer work synchronized
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
Your if inside the loop is a specific case (number lower than base) is prevent before the loop since it's the opposite condition of your loop. (BTW : rem <= base-1 and base>danum are actually only one test since rem == danum at this place)
so :
StringBuffer buff = new StringBuffer();
if(base > danum) {
buff.append(danum);
} else {
while (danum / base >= base - 1 && base < danum) {
int rem = danum / base;
int modu = danum % base;
buff.insert(0, modu);
danum = rem;
}
if(danum > 0) {
buff.insert(0, danum);
}
}
System.out.println(buff.toString());
I would also strongly recommand to test your input before running your code. (No Zero for base, no letters etc...)
2 Things
do a lot more error checking after getting user input. It avoids weird 'errors' down the path
Your conversion from int to String inside the loop is wrong. Whats the whole deal summat and buff.... :: modifying the buffer doesnt affect the strConverted (so thats always empty which is what you see)
try to get rid of this. :)
error is logic related
error is java related
Your code has the following problems:
Firstly, you have declared and initialized your strConverted variable (in which you store your result) inside your while loop. Hence whenever the loop repeats, it creates a new string strConverted with a value "". Hence your answer will never be correct.
Secondly, the StringBuffer buff never changes the string strConverted. You have to change your string by actually calling it.
You print your result inside your while loop which prints your step-by-step result after every repetition. You must change the value of strConverted within the loop, nut the end result has to be printed outside it.
Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);
This question already has answers here:
Scope of variable declared inside a for loop
(5 answers)
Closed 8 years ago.
The solution to my problem is probably something really obvious, but I have yet to find it. If you're at all wondering what this code is suppose to do, it's suppose to take 10 user-inputted numbers, add them together, and output the average. My only error thus far is that where I have double average = sum / 10;
it doesn't read the variable sum and I'm at a total loss as to why.
import java.io.*;
class Average
{
public static void main (String args[]) throws IOException
{
// declare some variables
int count = 0;
String inInput;
// declare array constructer
double[] userInput = new double[9];
// declare a reader
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(inStream);
// print out the array
while (count >= 9)
{
if (count != 10)
{
System.out.println ("Please enter a value");
}
else
{
System.out.println ("Please enter another value");
}
inInput = reader.readLine();
double inInputDouble = Double.parseDouble(inInput);
userInput[count] = inInputDouble;
double sum = sum + userInput[count];
count++;
}
double average = sum / 10;
System.out.println ("The average of all the numbers you have entered is" + average);
}
}
A variable can only be used inside the scope of which it is declared. Your sum variable is declared inside the while body and can thus only be used inside that scope.
Move the declaration of sum outside of the while loop as follows:
double sum = 0;
// print out the array
while (count >= 9)
{
...
sum = sum + userInput[count];
...
}
...
You probably also want to change count >= 9 to count < 9 to avoid ArrayIndexOutOfBounds.
int count is always 0, so it never goes into while(count >= 9) and when sum is called it won't be defined at all, change it for while(count <= 9)
You are declaring you variable sum inside the while loop block. Once that block finishes the variable goes out of scope and is no longer defined.
Put your double sum declaration before the while and you should be fine.
The scope of sum is the block it's declared in which is the block of the while loop.
Declare sum outside the while loop.
It doesn't make too much sense to redeclare this variable over and over again, because you want to sum up all numbers.
Take a look at this question:
Scope of variable declared inside a for loop
As said above, the sum must be declared befor the for loop.
Scopes are like brackets in programs,
int a ..
{
int b ...
{
int c ...
}
}
if the instruction evaluated is on line with a, it cannot know about the state of b and c, since they are not declared yet.
if instuction pointer evaluates line with int c , it know about all the variables because it allready got into the 3rd level of scoping. but since c is declared on 3rd level, after the instuction pointer goes outer from the brackets, if you did not saved the value of c in an upper leveled variable, the value gets lost, since c gets cleaned, and it is not accessible(outer scope). It is the same like you would want to read a variable from another file... you cant, scopes are like sticky notes which start from outer and append new smaller stickynotes, which after iot has been worked with , they get removed
scope: class definitions > method definitions > block definitions(for, while, if)
visible everywhere - visible under the method > visible in the block only
after it exits method all (eg: for (int i;..)
is gone i is not visible outer the for / brackets
another bug:
new double[9]; ?
you said it is supposed to take 10 ints...
at initialistion you dont count 0... 0 is used at 0 based indexing (a[0],a[1],a[2] needs a new int[3])... set it to new double[10];
I am devoloping an application to find the minimum of all the numbers entered .It accepts the numbers from the dialog box and when the user enters 0 it displays the minimum of all the numbers.But i dont need the 0 but the minimum of the numbers that preceeded it.
My code is as Follows:
try {
int a, c = 0, d = 0;
do {
a = Integer.parseInt(jOptionPane1.showInputDialog(null, "please enter the number"));
c = Math.min(a, d);
if (a != 0) //since a=0 will be excecuted one time
{
d = c;
}
} while (a != 0);
lb2.setText("Minimum of the numbers is " + d);
} catch (Exception e) {
jOptionPane1.showMessageDialog(this, "Some thing went wrong");
}
I know that it gives me 0 because the minimim of the numbers entered is zero and if i enter a number less than 0 (ie a negative number)it gives me the correct answer .I think the problem is also due to the initialisation that c=0.
Now i need a method to find the minimum without using any arrays and it should be simple and easy.(most helpful if you use Math.min itself)
Any help Appreciated.
Just change your initialization to set d set to Integer.MAX_VALUE.
I have an advice for your code, that you should make every variable names make sense. Maybe your code is small, but it will affect your habit, and when you work in large project, your habit will affect you so much :)
You should change initialize part of d = 0 to d = Integer.MAX_VALUE. Here is a new code :
try {
int inputNumber = 0, min= Integer.MAX_VALUE;
// int c : you don't need this variable
do {
inputNumber = Integer.parseInt(jOptionPane1.showInputDialog(null, "please enter the number"));
if (inputNumber != 0) //since a=0 will be excecuted one time
{
min= inputNumber;
}
} while (inputNumber != 0);
lb2.setText("Minimum of the numbers is " + min);
} catch (Exception e) {
jOptionPane1.showMessageDialog(this, "Some thing went wrong");
}
This new code is make more sense ?
And, Why you Must change initialize to min= Integer.MAX_VALUE? For example, you initialize like this : min = 10;. And at first time when someone type 15, you program will see : Oh, 15>10, so this is not the min value. But in fact, 15 is the first value of input and it should be the min value. Your program will be wrong until someone type a number less than 10.
Compare to your code, because you initialize d=0. when you type d=1, ops, 1>0, this is not min value (like above example). And everything will true only when you type some numbers < 0.
Al the problem above happen, because although user types any number, the min is the initialize number. (the number that user doesn't type). And that why you set your min value to something REALLY REALLY big. So, the FIRST TIME you type some numbers, It's ALREADY the SMALLEST.
Because machine not like us, doesn't have "infinity", so we must set it the biggest value possible. And because d is an int, so the biggest value of int is Integer.MAX_VALUE. In fact, you can type number for d. I don't remember exactly, but the biggest value for integer in range 32000 (2^31).