java


For loop how to print to console without leaving on first iteration java


I have written a for loop which counts each value in an array and if that array does NOT contain a given number (numberIn) that the user has entered, then a relavent error will appear.
However I noticed that I get a dead code warning on i++ as it only iterates once. Is there a way for the loop to iterate fully?
for (int i = 0; i < array.length; i++) {
if (!(numberIn == array[i]))
System.out.println("WRONG!!!!!");
break;
}
EDIT: sorry everyone for the massive confusion!, what i meant to say was that i want an error to appear if the value is NOT in the array, sorry again! :(
As I understand it, you are trying to test for the case when numberIn is not in the array. In that case, the simplest approach is to loop through the array, keeping track of whether the value was found, and then check whether it was found after that:
boolean found = false;
for (int i = 0; i < array.length; i++) {
if (numberIn == array[i]) {
found = true;
break;
}
}
if (!found) {
System.out.println("WRONG!!!!!");
}
You can also do this a bit more cleanly if you use a method:
boolean contains(array, value) {
for (int i = 0; i < array.length; i++) {
if (value == array[i]) {
return true;
}
}
return false;
}
if (!contains(array, numberIn)) {
System.out.println("WRONG!!!!!");
}
You break from your loop regardless whether or not the if statement evaluates to true.
Fix:
for (int i = 0; i < array.length; i++) {
if (!(numberIn == array[i])){
System.out.println("WRONG!!!!!");
break;
}
}
You need to include the break in your if block. Right now, it's always executing.
See:
for (int i = 0; i < array.length; i++) {
if (!(numberIn == array[i])) {
System.out.println("WRONG!!!!!");
break;
}
}
In general, the use of break is considered bad practice. Perhaps consider converting this to a while loop if you would like to stop after the first error is detected.
You need more braces eg:
for (int i = 0; i < array.length; i++) {
if (!(numberIn == array[i])){
System.out.println("WRONG!!!!!");
break;
}
}
Your mistake is forgetting to put brackets in your "if" statement. Your code looks like this:
if (!(numberIn == array[i]))
System.out.println("WRONG!!!!!");
break;
Therefore no matter if the if statement is run, the break will be run.
Put the break inside the if statement and it will work.
Your break hits because it's not in the if statement, you should put the break inside the if statement it will work
for (int i = 0; i < array.length; i++) {
if (!(numberIn == array[i]))
{
System.out.println("WRONG!!!!!");
break;
}
}
I think is a problem with your braces:
Without the if-statement body having braces, it's actually parsed as the following, which probably isn't what you intended:
for (int i = 0; i < array.length; i++) {
if (!(numberIn == array[i])) {
System.out.println("WRONG!");
}
break;
}
Hopefully this makes it clearer to see why your loop will always break after one iteration. Adding the braces, and putting the break back where you want it should resolve your issue (I've also slightly re-written your if condition):
for (int i = 0; i < array.length; i++) {
if (numberIn != array[i]) {
System.out.println("CORRECT!");
break;
}
}
public static void main (String[] args) throws java.lang.Exception
{
int array[] = {1,2,3};
int numberIn = 3;
for (int i = 0; i < array.length; i++) {
if (!(numberIn == array[i])){
System.out.println("WRONG!!!!!");
break;
}
}
}
You need the brackets on if sentence :D
I agree with the other posts that the break should be withing brackets in the if statement, but according to what you are saying that you the loop is supposed to do, the logic does not appear correct either. You have said that you only want the error message to appear if the value is found in the loop so if I am understanding correctly what the loop intends to do, it should read:
for (int i = 0; i < array.length; i++) {
if ( numberIn == array[i] )
{
System.out.println("WRONG!!!!!");
break;
}
}
you need curly brackets {} around the if statement, otherwise it will always exit after one iteration. Without {} an if statement only applies to the statement immediately below it. In this case the System.out.println("WRONG!!!!!"); statement. the break statement is not part of the if statement by default. The curly brackets indicate that everything inside of them is only to be executed in the event the condition is true, rather than just the next single statement.
EDIT: also, you had it writing the output in the event that it didn't detect a match. It should println() ony in the event that there is a match. remove the ! from the if statement, and it should work.
Fixed version
for (int i = 0; i < array.length; i++) {
if (numberIn == array[i]){
System.out.println("WRONG!!!!!");
break;
}
}
When you call for a break, it will leave the loop you are currently in.
Simply take out the break; allowing it to run through all values.
EDIT: Put the break inside the brackets. I don't think he wants it to run forever, just until he finds the value.

Related Links

Converting Large
Preventing Pop-Up Menu of JComboBox from Closing in Java
mockito in gradle not working for java project
Java lottery game
Convert a 2d double array to 2d double arraylist
Why is windows displaying a question mark on system.out.print in java?
Where is the R.java file in Android Studio?
what is the difference between System.out.write and System.out.print in java
Developing a chess game in java, my board object is not getting modified properly
I'm having problems accessing the total price I initialized inside my if else statements
How to prevent two objects in collisions from crossing both
making a playable jslider in java
Adding PdfDiv to Paragraph
Spring MVC - No mapping found for HTTP request with URI [/webstore/] in DispatcherServlet with name 'DefaultServlet'
How do I dump messageQueue in a Handler?
exploded-aar breakpoints show no executable code found at line x

Categories

HOME
clips
vbscript
heroku
google-docs
analysis
amortized-analysis
enterprise-library-5
directx
session-variables
dacpac
correlation
n-gram
systemc
transformation
http-status-code-504
css-animations
wijmo
firebase-crash-reporting
tdd
bootstrap-material-design
filezilla
rst2pdf
jspm
unboundid
skia
xquery-3.0
calibre
hybridauth
normal-distribution
simplexml
libraries
webix-treetable
splice
streamreader
greenrobot-eventbus
mesos-chronos
gzipstream
janrain
android-mediaprojection
no-www
netcdf4
sas-jmp
apple-news
network-flow
carrot
forever
font-size
yt-project
parallel-data-warehouse
storekit
lttng
markojs
skype4py
hover-over
bgp
apachebench
asp.net5
pervasive-sql
e10s
kineticjs
python-green
formatjs
tt-news
google-style-guide
angularjs-ng-click
android-imagebutton
nsbutton
id3v2
mysql-error-1062
mbr
fmod
ruby-datamapper
jplaton
back-stack
django-nonrel
type-equivalence
delphi-6
e4x
path-separator
bitsharp
datawindow
multipage
qtkit
nsmanagedobject
asyncfileupload
disclosure
actionview
oncheckedchanged
floating
xfbml
w3wp.exe
infrastructure
iweb
libs
javap
adrotator
defensive-programming
paul-graham
3gp

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App