This is probably a simple question, but how do I display "not in array" 1 time if the value I declared before isn't in the array? I got it to display "in array" by using an enhanced for loop to loop through the array. I noticed that if I added an else after the if, it would display "not in array" 4 times.
I'm still new to programming and have read the chapter, but I get so confused when it comes to arrays and for loops. Any help would be appreciated.
public static void main(String[] args) {
int[] test = {1, 2, 3, 4, 5}; // Creating an array
int number = 5; // My test number
// Enhanced for loop
for (int val: test) {
if (number == val) {
System.out.println(number + " in array");
}
}
}
The fundamental issue is that you can't know if an item is not in any position in an unsorted array until you have looped through all the items. If you check each item individually, you can't know if the next item might match.
Use a boolean variable to keep track of whether you've seen the item, and only print the result after the loop, once you've gone through all of them. Also check out break, you can use it to exit the loop if you don't need it to go all the way through.
After you've figured that out, a good next exercise is to extract the loop into a separate method and use return instead of break. Then you won't even need the boolean variable anymore.
use the flags,
boolean found = false;
for (int val: test) {
if (number == val) {
//System.out.println(number + " in array");
//set the flag if found
found=true;
//stop once you found what you looking for
break;
}
}
//check if the flag is set
if(!found)
System.out.println(number + " is not in array")
Related
Started learning about loops and the different types today. My question is in this situation which type would i try to use? And what would be the advantage over the others? After looking over my lecture notes it seems that do-while should always be used but I'm certain that it is not the case.
Also how would I start that first one about returning a sum of the "given array." what is the given array? Is it just whatever I'm supposed to be plugging into the run arguments line?
public class SumMinMaxArgs {
// TODO - write your code below this comment.
// You will need to write three methods:
//
// 1.) A method named sumArray, which will return the sum
// of the given array. If the given array is empty,
// it should return a sum of 0.
//
// 2.) A method named minArray, which will return the
// smallest element in the given array. You may
// assume that the array contains at least one element.
// You may use your min method defined in lab 6, or
// Java's Math.min method.
//
// 3.) A method named maxArray, which will return the
// largest element in the given array. You may
// assume that the array contains at least one element.
// You may use your max method defined in lab 6, or
// Java's Math.max method.
//
// DO NOT MODIFY parseStrings!
public static int[] parseStrings(String[] strings) {
int[] retval = new int[strings.length];
for (int x = 0; x < strings.length; x++) {
retval[x] = Integer.parseInt(strings[x]);
}
return retval;
}
// DO NOT MODIFY main!
public static void main(String[] args) {
int[] ints = parseStrings(args);
System.out.println("Sum: " + sumArray(ints));
System.out.println("Min: " + minArray(ints));
System.out.println("Max: " + maxArray(ints));
}
}
All three forms have exactly the same expressive power. What you use in a certain situation depends on style, convention, and convenience. This is much like you can express the same meaning with different english sentences.
That said, do - while is mostly used when the loop should run at least once (i.e. the condition is checked only after the first iteration).
for is mostly used when you are iterating over some collection or index range.
The four kinds of loops supported in Java:
C-style for loop: for (int i = 0 ; i < list.size() ; ++i) { ... } when you want to access the index of some kind of list or array directly, or to do an operation multiple times.
foreach loop, when you want to iterate over a collection, but don't care about the index: for (Customer c : customers) { ... }
while loop: while (some_condition) { ... } when some code must executed as long as the condition is true. If the condition is false to start with, the code inside the block (i.e. inside the brackets) will never be executed.
do while loop: do { statement1; } while (condition); will execute statement1 even if the condition is false to begin with, but it will do so only once.
Is there a way to increase the for-loop range in java? I have the following code:
for (DataRoot bri : Ri)
{
for (DataRoot brcom : complemento)
{
if (bri.getMesa().equals(brcom.getMesa()))
{
if (found) {found = false; break;}
postrecom = brcom.getOrden().getPostres();
Calendar dateri = Calendar.getInstance();
Calendar datecom = Calendar.getInstance();
dateri.setTime(bri.getFechaorden());
for (Postres proc : postrecom)
{
// if (found) {found = false; break;}
datecom.setTime(proc.getHora_plato());
long diff = datecom.getTimeInMillis() - dateri.getTimeInMillis();
if ( diff > (3*60*1000))
{
found = true;
Ri.add(brcom);
break;
}
else
{
bri.getOrden().getPostres().add(proc);
setBase();
}
}
}
}
}
As you can notice, if some conditions are met, the Array "Ri" which is the main array will increase its content, lets say from 3 items to 4, at the start, the loop was going to be from 0 to 2 but as it got a new element I need it to keep running from 0 to 3 but the range will not dynamically increase as new items are added.
I could count how many items I added to "Ri" So that I can call that many times this method but if I do so, the compiler witll give me the "java.util.ConcurrentModificationException" error at this point I dont know what to do any help would be appreciated.
I might be wrong, but from the explanation you have given and code you have written, you are trying to get complement Items and then add them to Ri list if not present.
Assuming data structure of Ri is ArrayList, the way I would approach is that, first I would get all the complement items. Then loop through complement items, and for each complement item, loop through the entire Ri value and set a boolean if the associated value is suitable to add like below :
for(dataBri brCom : complemento) {
boolean shouldAdd = false;
for (DataBri bri : Ri) {
if(someConditionMet) {
shouldAdd = true;
}
if (shouldAdd) {
Ri.add(brCom);
}
}
I hope it makes sense.
Well im relatively new developing in Java and seems like if you do loop type For-each like
for (Arraylist arraylist : size)
{
....
}
assuming your initial size was 2, meaning that the array contains 2 elements, IF in the process you add elements to the array, the size wont dynamically change BUT if you go for the old
for (int i = 0; i < Arraylist.size(); i++)
{
....
}
and in the process you add elements to the Array, the size of the loop gets re-calculated dynamically as you add new elements to the array and in my case, solving my problem.
Need little help. Working on my homework and I have to sort list using ArrayDeque. I can check first and last element.
I have a list, for example
int[] list = {6, 8, 7};
First element - 6 - will go into empty array, no problem with that.
Second element - 8 - will go at behind the 6, so we will have[6,8], but then comes 7. Since I can't put it in front of the 6, and I cant put it behind 8. So I have to store 7 into some other list that I can later return. How do I do that? Any hint is welcome.
Thanks.
(And sorry if this is something that has been asked before, but couldn't find the solution)
Let me clarify your constraints first. You can only:
get the value of the first element
remove the first element
prepend before the first element
get the value of the last element
remove the last element
append after the last element
An algorithm to add values from an array into a structure described above, using a stack:
for each value in the array
if the value is smaller than the first in the deck -> prepend
else if the value is greater than the last in the deck -> append
else if the value is closer to the first:
remove the first element and push on the stack repeatedly, as long as the first element is smaller
prepend the value to the deck
while the stack is not empty, pop from it and prepend to the deck
else:
remove the last element and push on the stack repeatedly, as long as the last element is greater
append the value to the deck
while the stack is not empty, pop from it and append to the deck
If you are not allowed to use a stack, but you are allowed to use recursion, then you can use the call stack to the same end
Something you could do is to store the int value at index x into a local variable and then traverse through the array seeing if there is a value lower than the currently stored value and if so that becomes the new lower value. When it finishes going through the array you can input that into the new array.
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
ArrayDeque<Integer> container = new ArrayDeque<>();
ArrayDeque<Integer> container2 = new ArrayDeque<>();
System.out.println("Please enter 10 number with space");
for(int i=0;i<10;i++){
container.add(sc.nextInt());
}
while (!isSorted(container.isEmpty()?container2:container)) {
while (!container.isEmpty()) {
int a = container.poll();
if(container.peek()!=null && a<container.peek()){
if(container2.peek()!=null && container2.peek()>container.peek()){
container2.addFirst(a);
}else{
container2.addLast(a);
}
}else if(container.peek()!=null){
if(container2.peek()!=null && container2.peek()>container.peek()){
container2.addFirst(container.poll());
}else{
container2.addLast(container.poll());
}
container.addFirst(a);
}else{
container2.addLast(a);
}
}
while (!container2.isEmpty()) {
int a = container2.poll();
if(container2.peek()!=null && a<container2.peek()){
if(container.peek()!=null && container.peek()>container2.peek()){
container.addFirst(a);
}else{
container.addLast(a);
}
}else if(container2.peek()!=null){
if(container.peek()!=null && container.peek()>container2.peek()){
container.addFirst(container2.poll());
}else{
container.addLast(container2.poll());
}
container2.addFirst(a);
}else{
container.addLast(a);
}
}
}
while (!container.isEmpty()) {
System.out.println(container.poll());
}
System.out.println("---------------------------");
while (!container2.isEmpty()) {
System.out.println(container2.poll());
}
}
static boolean isSorted(ArrayDeque<Integer> con){
boolean answer = true;
for(int i=0;i<con.size()-1;i++){
int a = con.poll();
con.addLast(a);
if(con.peek()!=null && a>con.peek()) answer= false;
}
con.addLast(con.poll());
return answer;
}
So here is the code I have right now.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
int set[] = new int[5];
set[0] = (int)(Math.random()*6)+1;
set[1] = (int)(Math.random()*6)+1;
set[2] = (int)(Math.random()*6)+1;
set[3] = (int)(Math.random()*6)+1;
set[4] = (int)(Math.random()*6)+1;
System.out.println("Your current dice: " + set[0] + " " + set[1] + " " + set[2] + " " + set[3] + " " +set[4] );
System.out.println("Select a die to re-roll (-1 to keep remaining dice):");
int ask = keyboard.nextInt();
After this if the user types in let's say 1 then set[1] should change to the number zero and so it becomes x0xxx and if the user also wants the 3rd number to change then it should be x0x0x.
The x's are just the generated random numbers by the way.
How do I keep doing this? It has to be a total of utmost 5 times.
Here are the basic steps you should follow to accomplish what you want/need.
Read user input (using Scanner or something else).
Validate if the user input is a valid index for the array (this is, the input is a number with a value between 0 and 5). You can store this in a variable int x.
Change the value of the element of the array inside the index user entered to 0 (or the value you want/need). This would traduce into something like set[x] = ... (change the ... by the proper value).
The way you do one thing many times is in a loop. The key is in learning which kind of loop to use.
For things that get applied to every element, use a for-each loop. For things that need done until some condition use a while loop. For things that need done until some condition becomes false, use a do-until loop.
The thing you do is the same, that goes into the block of the loop. The thing you are "working on" changes, that is a variable which the loop will set each time it "goes through" the loop's block.
In your case
for (Die die : dice) {
die.roll();
}
where class Die looks like
public class Die {
private int value;
public Die() {
roll();
}
public void roll() {
value = (int)(Math.random()*6)+1;
}
public int getValue() {
return value;
}
}
Then, since you need "order" (first, second, third, etc...) use a data structure that can contain Objects (like your Die)
List<Die> dice = new ArrayList<>();
Arrays are nice, and you do need to know how to use them; however, there are far better ways of solving most problems by not using them.
When you really can't get around using them, use a for loop to walk each array index.
I hope I'm also allowed to ask questions instead of really having errors and need to fix them.
I got the following code:
public boolean equals(NaturalNumberTuple givenTuple) {
int count = 0;
if(tuple.length == givenTuple.getLength()){
for(int i = 0; i < tuple.length; i++){
if(this.tuple[i] == givenTuple.tuple[i]){
count++;
}
}
if(count == tuple.length){
return true;
}
}
return false;
}
So as you can see I'm using a normal for loop but I learned that I can use a so called foreach loop
for(int i : tuple){...}
but if i try to use it I'm getting an error "ArrayIndexOutOfBoundsException" if I try to check two Arrays for equality.
Can someone explain me why I can't use a foreach loop here?
My only bet is that you wrote:
for(int i : tuple){
if(this.tuple[i] == givenTuple.tuple[i]){
count++;
}
}
In the for-each loop, i takes the value of the element in the array. It's not the index. Let's say you have:
int[] arr = {1, 4, -2};
i will take the value 1, 4 and -2, not 0, 1, 2.
As you need the index to access givenTuple.tuple[i], I think you can stick with the traditionnal for loop, or use Arrays.equals (that would be a one-liner).
Oh also note that public boolean equals(NaturalNumberTuple givenTuple) is not an override of the equals method (which can give you unexpected surprises)