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

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of TestAcceptanceCriteria out of START_ARRAY token
Inputting a parameter for a for loop | Java
What is more effective, a huge condition, or a huge array?
JAVA 8 crashes with Fatal Error Log on startup - Solaris 10 (sparc)
How to handle large text in java variable
Trouble connecting to local database with JDBC - no error after executing the code
Jackson can't parse large json - LinkedHashMap cannot be cast to entity
How to use JFoenix RequiredFieldValidator to enable/disable form JFXButton?
Insert Multiple Rows realm android
Actions class in selenium 3.3.1 deprecated looking for solution with contextClick
Parsing array of objects into a function
Moverio bt-350 bluetooth
Run *.jar file on Android
How to make graphics move without showing tracing but keep it when I draw another one?
Calling a method with a return type
Saving a current open file using JFileChooser

Categories

HOME
compiler-construction
yii2
jdo
listview
openmp
netbeans
json.net
homebrew
include
lodash
read-eval-print-loop
youtube-dl
kalman-filter
google-docs
frameworks
c#-2.0
dxl
jxls
ip
contact
python-unittest
kibana-4
gnupg
vault
google-apps-marketplace
google-cloud-ml
jplayer
telephony
foselasticabundle
excel-vba-mac
visual-composer
predix
conemu
tokenize
language-agnostic
emgucv
selectedindexchanged
kendo-datasource
junit5
create-table
copying
code-contracts
sequential
simplexml
android-browser
lumberjack
broadcastreceiver
fedex
http-live-streaming
eigenvalue
python-c-api
dandelion
return-value
titanium-android
chord-diagram
time-and-attendance
firmata
google-web-starter-kit
merge-conflict-resolution
xml-attribute
contact-list
blackberry-10
thredds
qdialog
quicklisp
computer-algebra-systems
ionic
twirl
census
proj4js
codeigniter-url
gadt
cdt
android-nested-fragment
document-classification
openexr
article
system.net.webexception
mechanize-ruby
cloud-connect
xsockets.net
dataservice
ember-app-kit
eventlistener
html-editor
selected
pvrtc
google-email-migration
manchester-syntax
assembly-loading
work-stealing
php-parser
window-management
doh
genshi
joyent
html-input
infrastructure
xsdobjectgen
premature-optimization
commodore

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