I am getting a "unidentified label" error, here is my code:
if (this.prevTime > 0L)
{
int i = (int)(1.0E-06D * (System.nanoTime() - this.prevTime));
if (i >= 2000)
break label76;//unidentified label
j = 3;
if (j > 0)
break label56;//unidentified label
this.taps[0] = i;
}
I also tried:
if (this.prevTime > 0L)
{
int i = (int)(1.0E-06D * (System.nanoTime() - this.prevTime));
label76:
if (i >= 2000)
break label76;//'break' statement unnecessary
j = 3;
label56:
if (j > 0)
break label56;//'break' statement unnecessary
this.taps[0] = i;
}
but then I get ('break' statement unnecessary).
1st case: you don't declare labels.
2nd case: the label is in the break scope so it's unnecessary
Labels must be placed in a line that makes sense and when the break statement is not enough.
Of course, you can refer to documentation for further info:
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.
Look at this example: The following program, BreakWithLabelDemo, uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"):
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search: // <-----------------------------------------------------------*
for (i = 0; i < arrayOfInts.length; i++) { // *
for (j = 0; j < arrayOfInts[i].length; j++) { // *
if (arrayOfInts[i][j] == searchfor) { // *
foundIt = true; // *
break search; // -------------------------------------*
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
Related
Hi guys. How are you? =)
I'm new to Java and currently
I have a task to create a method, it takes one parameter sum - the amount of money to be given out, and returns the minimum number of banknotes that can be given out this amount.
Only While loop can be used.
I made it with for loop, but I can't find where I made mistake in while loop.
Could you please give me hint or advice?
Thank you!
public class ATM {
public static int countBanknotes(int sum) {
int[] notes = new int[] { 500, 200, 100, 50, 20, 10, 5, 2, 1 };
int[] noteCounter = new int[9];
int amount = 0;
for (int i = 0; i < 9; i++) {
if (sum >= notes[i]) {
noteCounter[i] = sum / notes[i];
sum -= noteCounter[i] * notes[i];
}
}
for (int i = 0; i < 9; i++) {
if (noteCounter[i] != 0) {
amount += noteCounter[i];
}
}
return amount;
}
public static void main(String[] args) {
// 6 (500 + 50 + 20 + 5 + 2 + 1
int sum = 578;
System.out.print(ATM.countBanknotes(sum));
}
}
And while loop
public class JustATest {
public static int countBanknotes(int sum) {
int[] notes = new int[] { 500, 200, 100, 50, 20, 10, 5, 2, 1 };
int[] noteCounter = new int[9];
int amount = 0;
int i = 0;
while ( i < 9 ) {
if (sum >= notes[i]) {
i++;
noteCounter[i] = sum / notes[i];
sum -= noteCounter[i] * notes[i];
}
}
while ( i < 9 ) {
if (noteCounter[i] != 0) {
i++;
amount += noteCounter[i];
}
}
return amount;
}
public static void main(String[] args) {
// Should be 6 (500 + 50 + 20 + 5 + 2 + 1)
int sum = 578;
System.out.print(JustATest.countBanknotes(sum));
}
}
You need to reinitialize your i variable between the loops, or use another variable, like j.
Furthermore, you should not have your i++ inside the if statements in your while loops. Otherwise, there are scenarios where the counter is never incremented and you will have an endless loop. That is bad!
Put your i++ in the bottom of the while loop outside the if statement like this:
while ( i < 9 ) {
if (sum >= notes[i]) {
noteCounter[i] = sum / notes[i];
sum -= noteCounter[i] * notes[i];
}
i++;
}
int j = 0;
while ( j < 9 ) {
if (noteCounter[j] != 0) {
amount += noteCounter[j];
}
j++;
}
This way, the counters are always incremented no matter what, and you will not have endless loops.
I included a fix for your problem in the code above as well.
You need to reinitialize your i value to 0 for the second while loop
You must execute i++ in your while loop everytime. Otherwise you will get into endless loop.
You must reset i before going to next loop. So one iterator i for two loops is not recommended.
public static int countBanknotes(int sum) {
int[] notes = new int[]{500, 200, 100, 50, 20, 10, 5, 2, 1};
int[] noteCounter = new int[9];
int amount = 0;
int i = 0;
while (i < 9) {
if (sum >= notes[i]) {
noteCounter[i] = sum / notes[i];
sum -= noteCounter[i] * notes[i];
}
i++;
}
i = 0;
while (i < 9) {
if (noteCounter[i] != 0) {
amount += noteCounter[i];
}
i++;
}
return amount;
}
I was wondering if there is a way or a library I can use to do the following:
I have an arraylist of objects where each obj has a name.
The list needs to always be unique with a maximum of 5 elements like [E1,E2,E3]
If for example the list has initial form [E3,E5] and I add an object, its name should be E1 and the list will be [E1,E3,E5] or [E3,E5,E1] it doesn't matter, as long as the name is unique and the item is added to the list starting from 1 to 5.
If add another item, it should be [E3,E5,E1,E2], always a unique name and between 1 and 5
These are my failed attempts,
StartNode node = new StartNode();
node.setName("E1");
for (int i = 0; i < circuit.getNbStartNodes(); i++) {
for (int j = 1; j <= circuit.getNbStartNodes(); j++) {
String test = ((StartNode) circuit.getStartNode(j)).getName();
if (("E"+j).equalsIgnoreCase(test) && ("E"+j).equalsIgnoreCase(node.getName()) ) {
break;
}
else
node.setName("E" + j);
}
}
/*while (t <= circuit.getNbStartNodes()) {
for (int j = 0; j < circuit.getNbStartNodes(); j++) {
String test = ((StartNode) circuit.getStartNode(j)).getName();
if (("E" + t).equalsIgnoreCase(test) || ("E" + t).equalsIgnoreCase(node.getName()))
break;
else {
node.setName("E" + t);
}
}
t++;
}
*/
/* for (int i = 1; i <= circuit.getNbStartNodes(); i++) {
for (int j = 0; j < circuit.getNbStartNodes(); j++) {
String test = ((StartNode) circuit.getStartNode(j)).getName();
if (!("E" + i).equalsIgnoreCase(test)) {
node.setName("E" + i);
t=0;
break;
}
}
if (t==0)
break;
else
continue;
*/
//String test = ((StartNode) circuit.getStartNode(i)).getName();
//for (int j = 1; j <= circuit.getNbStartNodes(); j++) {
// if (!("E" + j).equalsIgnoreCase(test))
// node.setName("E" + j);
//}
What did I do wrong in my code?
Create a small boolean array to track which names are already used and populate it with accordingly
Find the first unused element and use it as id.
boolean[] used = new boolean[circuit.getNbStartNodes()];
for (int i = 0; i < used.length; i++) {
int index = Integer.parseInt(((StartNode) circuit.getStartNode(j)).getName().substring(1)) - 1; // should be in range 0..4
used[index] = true;
}
String name = "E";
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
name += String.valueOf(i + 1); // starting from 1
break;
}
}
System.out.println("free name: " + name);
StartNode node = new StartNode();
node.setName(name);
// add new node to circuit, etc.
With small values, Alex' solution works fine.
However, if you ever come across a use case where the number of elements become potentially large, then you could use a TreeSet to keep track of the unused numbers. Further, the nextCeilValue is the next number to pick when there are no removed numbers.
In the below code, I have created a UniqueNumber class, which is able to get the next number, or remove a given number. Note that this code provides integers starting from 0. Of course, you could easily convert this to your E-numbers using the function i -> "E" + (i + 1).
public class UniqueNumber {
private int nextCeilValue;
private final TreeSet<Integer> removedNumbers = new TreeSet<>(Integer::compare);
public int get() {
if (removedNumbers.isEmpty()) {
return nextCeilValue++;
}
else {
int number = removedNumbers.first();
removedNumbers.remove(number);
return number;
}
}
public boolean remove(int number) {
if (number < 0 || number > nextCeilValue) {
return false;
}
if (number == nextCeilValue) {
nextCeilValue--;
}
else {
removedNumbers.add(number);
}
return true;
}
public int size() {
return nextCeilValue - removedNumbers.size();
}
}
In order to test this, we first need to simulate your initial situation. In our integer-starting-from-zero-world, we need the numbers 2 and 4 (representing E3 and E5). In below code, we need to call get five times, and then remove element 0, 1 and 3. Of course, we could have created a UniqueNumber(int... initialValues) constructor which does this under the hood.
UniqueNumber un = new UniqueNumber();
for (int i = 0; i < 5; i++) {
un.get();
}
un.remove(0); // Remove E1
un.remove(1); // Remove E2
un.remove(3); // Remove E4
In order to get the next value, simply use this:
StartNode node = new StartNode();
node.setName("E" + (un.get() + 1));
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have a question when executing following codes:
if(column!=n-1){
if(returnValue[row][column+1] == 0) column++;
else {
row++;
direction = "down";
}
}
else {
row++;
direction = "down";
}
If you see the codes, I need to check whether the column is exceeding the boundary first and then do another checking, which have duplicated codes in the else section. Is there a better way to write this logic?
I will give you an example cause sounds similar to a matrix issue , please focus on for loops cause the main key is there:
// JAVA Code for Boundary elements of a Matrix
class GFG {
public static void printBoundary(int a[][], int m,
int n)
{
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0)
System.out.print(a[i][j] + " ");
else if (i == m - 1)
System.out.print(a[i][j] + " ");
else if (j == 0)
System.out.print(a[i][j] + " ");
else if (j == n - 1)
System.out.print(a[i][j] + " ");
else
System.out.print(" ");
}
System.out.println("");
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
printBoundary(a, 4, 4);
}
}
in order to avoid getting out of bounds, you'd have to check if row & column are within the boundaries of the array. I do not expect either value to go below 0 as there is no decrement if your code, so I only checked the length, but not negative indices.
if (row < returnValue.length && column < returnValue[row].length - 1 && returnValue[row][column+1] == 0) column++;
else {
row++;
direction = "down";
}
I am writing an answer to a CCC question in java, but every time I input something it just takes infinite inputs. Can anyone help me stop this?
Your task is to write a program that verifies the validity of a well plan by verifying that the borehole will not intersect itself. A two-dimensional well plan is used to represent a vertical cross-section of the borehole, and this well plan includes some drilling that has occurred starting at (0, −1) and moving to (−1, −5). You will encode in your program the current well plan shown in the figure below:
Input Format:
The input consists of a sequence of drilling command pairs. A drilling command pair begins with one of four direction indicators (d for down, u for up, l for left, and r for right) followed by a positive length. There is an additional drilling command indicated by q (quit) followed by an integer, which indicates the program should stop the execution. You can assume that the input is such that the drill point will not:
rise above the ground, nor
be more than 200 units below ground, nor
be more than 200 units to the left of the original starting point, nor
be more than 200 units to the right of the original starting point.
Output Format:
The program should continue to monitor drilling assuming that the well shown in the figure has already been made. As we can see (−1, −5) is the starting position for your program. After each command, the program must output one line with the coordinates of the new position of the drill, and one of the two comments safe, if there has been no intersection with a previous position or DANGER if there has been an intersection with a previous borehole location. After detecting and reporting a self-intersection, your program must stop.
My code is:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> holeX = new ArrayList<>();
ArrayList<Integer> holeY = new ArrayList<>();
String direction;
boolean danger = false;
holeX.add(0);
holeX.add(0);
for (int i = 0; i < 4; i++) {
holeX.add(i);
}
holeX.add(3);
holeX.add(3);
holeX.add(4);
holeX.add(5);
holeX.add(5);
holeX.add(5);
holeX.add(6);
for (int i = -3; i > -8; i--) {
holeX.add(7);
}
for (int i = 6; i > -2; i--) {
holeX.add(i);
}
holeX.add(-1);
holeX.add(-1);
holeY.add(-1);
holeY.add(-2);
for (int i = 0; i < 4; i++) {
holeY.add(-3);
}
holeY.add(-4);
holeY.add(-5);
holeY.add(-5);
holeY.add(-5);
holeY.add(-4);
holeY.add(-3);
holeY.add(-3);
for (int i = -3; i > -8; i--) {
holeY.add(i);
}
for (int i = 6; i > -2; i--) {
holeY.add(-7);
}
holeY.add(-6);
holeY.add(-5);
do {
direction = sc.next();
int steps = sc.nextInt();
switch (direction) {
case "d":
for (int i = holeY.get(holeY.size() - 1); i > holeY.get(holeY.size() - 1) - steps; i--) {
holeY.add(i);
for (int j = 0; j < holeY.size() - 2; j++) {
if (Objects.equals(holeY.get(holeY.size() - 1), holeY.get(j)) && Objects.equals(holeX.get(holeX.size() - 1), holeX.get(j))) {
danger = true;
}
}
}
case "u":
for (int i = holeY.get(holeY.size() - 1); i < holeY.get(holeY.size() - 1) + steps; i++) {
holeY.add(i);
for (int j = 0; j < holeY.size() - 2; j++) {
if (Objects.equals(holeY.get(holeY.size() - 1), holeY.get(j)) && Objects.equals(holeX.get(holeX.size() - 1), holeX.get(j))) {
danger = true;
}
}
}
break;
case "l":
for (int i = holeX.get(holeX.size() - 1); i > holeX.get(holeX.size() - 1) - steps; i--) {
holeX.add(i);
for (int j = 0; j < holeX.size() - 2; j++) {
if (Objects.equals(holeX.get(holeX.size() - 1), holeX.get(j)) && i == holeY.get(j)) {
danger = true;
}
}
}
break;
case "r":
for (int i = holeX.get(holeX.size() - 1); i < holeX.get(holeX.size() - 1) + steps; i++) {
holeX.add(i);
for (int j = 0; j < holeX.size() - 2; j++) {
if (Objects.equals(holeX.get(holeX.size() - 1), holeX.get(j)) && i == holeY.get(j)) {
danger = true;
}
}
}
break;
default:
break;
}
if (danger == false && !"q".equals(direction)) {
System.out.println(holeX.get(holeX.size() - 1) + " " + holeY.get(holeY.size() - 1) + "safe");
System.out.print(" safe");
} else {
System.out.println(holeX.get(holeX.size() - 1) + " " + holeY.get(holeY.size() - 1) + " DANGER");
}
} while (!"q".equals(direction) && danger == false);
}
holeX and holeY are the coordinates of the drilled area.
Input:
l 2
d 2
r 1
q 0
Output:
-3 -5 safe
-3 -7 safe
-2 -7 safe
Well yes, you have an infinite loop. Let's take case "l" for example.
I used l and then 2.
for (int i = holeX.get(holeX.size() - 1); i > holeX.get(holeX.size() - 1) - steps; i--) {
holeX.add(i)...
You add something to the list and the condition gets re-evaluated, which leads to an infinite loop.
I don't know if it is what you want to do, but what helps is to extract the condition first into a variable, then the infinite loop stops.
I have a construct where I have a for loop nested inside of a while loop in Java. Is there a way to call a break statement such that it exits both the for loop and the while loop?
You can use a 'labeled' break for this.
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
Taken from: http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
You can do it in 3 ways:
You can have while and for loops inside method, and then just call return
You can break for-loop and set some flag which will cause exit in while-loop
Use label (example below)
This is example for 3rd way (with label):
public void someMethod() {
// ...
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
}
example from this site
In my opinion 1st and 2nd solution is elegant. Some programmers don't like labels.
Labelled Breaks
For example:
out:
while(someCondition) {
for(int i = 0; i < someInteger; i++) {
if (someOtherCondition)
break out;
}
}
Make the loop be inside a function call and return from the function?
You should able to use a label for the outer loop (while in this case)
So something like
label:
While()
{
for()
{
break label;
}
}