I want to restrict the while Loop.
I don't want to use break;, instead I want to say that the loop must end after three times.
My while Loop:
while(!file.isFile()) { userInput = JOptionPane.showInputDialog("UserInput);
int i = 0;
while(!file.isFile() && i < 3) {
userInput = JOptionPane.showInputDialog("UserInput);
i++;
}
And I agree that for loop is better choice :)
Use a for loop instead :
for (int i = 0; i < 3 && !file.isFile(); i++) {
userInput = JOptionPane.showInputDialog("UserInput");
...
}
Consider refactoring to a for loop, introducing a counter variable in a tight scope:
for (int i = 0; i < 3 && !file.isFile(), ++i){
userInput = JOptionPane.showInputDialog("UserInput"/*ToDo - quotation inserted*/);
}
The for loop conditional check i < 3 && !file.isFile() is verified before the statement in the loop body is ran.
Then you need to make your while loop a for-loop like thing:
int counter = 0;
while (counter < 3 && !file.isFile()) { ...
counter++;
For the record: the code you are showing isn't really useful: you are "overriding" the input you get from the user; and: you are condition !file.isFile() ... will not change its value ... because there is no code that would do that. In other words: there is more to fix about your code than just the way you are looping. It simply seems weird to ask the user the same thing three times; to ignore what he says the first two times.
int i = 3;
while(!file.isFile() && i>0) {
userInput = JOptionPane.showInputDialog("UserInput");
i--;
}
int counter = 0;
while(!file.isFile() && counter < 3) {
userInput = JOptionPane.showInputDialog("UserInput);
counter++;
}
Replace 3 with the number of iterations you would like the loop to be limited to.
int count = 0;
while(!file.isFile() && count < 3 ) {
count++;
}
Related
I realize this has been asked before and I had a look at it but, for me, it only works to a point. After some struggle, I thought I'd ask.
I have an array of floats in an object's constructor.
That goes like this:
count = 3;
angles = new float[count];
The array length is really small though I'd like implement a modular and reusable approach.
I loop through the array assigning floats:
for (int i = 0; i < angles.length; i++) {
angles[i] = radians(random(360));
}
Then, with a new loop, I check if the singular elements have less than 30 degrees in between them, and if so, assign a new random value:
for (int i = 0; i < angles.length; i++) {
for (int k = i+1; k < angles.length; k++){
if(angles[i] != angles[k]){
if(abs(angles[i] - angles[k]) <= radians(30)){
angles[i] = radians(random(360));
}
}
}
}
This works nice and well but it doesn't guarantee that the new random number will keep the 30 degrees limit with the remaining elements. This, I assume, has to do with the length of the 'for' loop.
What would be the best way to overcome this and guarantee that newly fetched number will always conform to the 30 degree rule?
Instead of just checking once with an if statement, you could change it to a while statement, so that it attempts to find a new random number until the new one works.
while (abs(angles[i] - angles[k]) <= radians(30)){
angles[i] = radians(random(360));
}
However, if there are no numbers that follow your 30 degree rule, your program will get stuck in this loop, so you might want to check that there is a possible solution before entering the loop.
Edit: the above solution will ensure that the number follows the 30 degree rule with only one number in your array. Add a boolean to determine if the condition has been met, and loop until the boolean is true.
for (int i = 0; i < angles.length; i++) {
boolean meetsCondition = false;
while (!meetsCondition) {
for (int k = 0; k < angles.length; k++){
if(i != k){
if(abs(angles[i] - angles[k]) <= radians(30)){
angles[i] = radians(random(360));
meetsCondition = false;
break;
}
}
}
meetsCondition = true; //if the for loop completes, it has met the condition.
}
}
Why not use recursion earlier on:
for (int i = 0; i < angles.length; i++) {
angles[i] = findSuitable( i==0 ? 0 : angles[i-1] )
}
...
float findSuitable(float limit){
float sample = radians(random(360));
if(Math.abs(sample-limit) > 30)
return sample;
else
return findSuitable(limit);
}
In my opinion, you can try to change the the codes of random to this:
Random d = new Random();
int a = d.nextInt(360);
I am currently trying to make a simple program that will calculate the number of vowels in multiple sentences. The input looks like this:
6
Emily jumped high
Alex did not jump
Phillip hates jumping
The red dragon can fly
Sandwiches are nice
I like the sun
The number indicates how many lines there are. My problem is that when I print out the results, the last line gets ignored. So the program prints out 5 ints, rather than 6. I've been playing around with it for ages and I just can't seem to get my head around the issue.
Scanner in = new Scanner(System.in);
int cases = in.nextInt(); //how many lines there are
String a;
int vowels = 0;
int length; //length of a line
char temp;
in.nextLine(); //skips first line of the input, as this declares how many lines there are
for (int i = 0; i <= cases; i++)
{
a = in.nextLine();
length = a.length();
//System.out.println(a);
for (int b = 0; b < length; b++)
{
temp = a.charAt(b);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
{
vowels++;
}
}
System.out.println(vowels);
vowels=0;
}
For some reason when I posted the input, it would automatically show me the first 5 ints, I then just had to press enter to make the last one show up. So apparently hitting enter is now also one of the skills I've acquired ;)
You have extra step in loop:
for (int i = 0; i <= cases; i++)
The loop you need is:
for (int i = 0; i < cases; i++)
You are looping for cases+1 times ie 7 times. You should either use
for (int i = 0; i < cases; i++)
or
for (int i = 1; i <= cases; i++)
Otherwise your code will print the expected output.
Your code is work fine. Only one problem you need change i <= case to i < case. You can use this website for testing your code with std input.
https://ideone.com/Ud3MWt
How would I create a loop where it has a condition, but in addition you can decide how many times you want it to loop. I know that the for loop does this, but what if I want a specific integer to determine how many times it will loop?
Example
//for loop below
for(int x = 0; x < 10; x++)
{
}
Instead of doing the for loop (above), is there a way to choose a specific number of times you want it to loop, so that you can enter an integer variable in a properly which will tell it how many times you want it to loop?
There's a few choices. The simplest is to replace 10 with a variable,
int length = 10;
for(int x = 0; x < length; x++)
Alternatively, you could use a while loop,
int length = 10;
int x = 0;
while (x < length) {
// ...
x++;
}
Or a do {} while like
int length = 10;
int x = 0;
do {
// ...
} while (x++ < length);
Every loop can be made to satisfy your constraints. A while loop might be most apt one in this case.
int count;
while (count-- != 0) {
//statements
}
Will execute the loop body count number of times.
int amount = 50;
for(int x = 0; x < amount; x++) {
// This will loop 50 times.
}
The integer after x < is the amount of times that it will loop.
If you want to avoid using a loop, you can use Java 8 features :
IntStream.range(0,n).forEach(i -> {
//someCode
});
This will run a block of code n times.
just do this
System.out.println("enter amount of time you want the loop to run");
Scanner scanner=new Scanner(System.in);
int amount=scanner.nextInt();
for(int i=1;i<=amount;i++){
System.out.println("Hii");
}
This program will ask you how may times you want to execute the loop.
A little background, I saw a question on here a while back about creating a program that asks how many people are in the room, and then you 'interview' each person on their age, assign them to an age group, and then print their age group and the amount of people in that age group. I decided to take a shot at it off of needing an idea for a practice program, unfortunately the code terminates before getting the first for statement and i'm not exactly sure why. I assume it would be a syntax error but I honestly have no idea, so any help is greatly appreciated.
import java.util.Scanner;
public class UnkownProjects {
public static void main(String[] args){
Scanner stringInput = new Scanner(System.in);
Scanner numInput = new Scanner(System.in);
System.out.println("How many people are in the room?");
int amountOfPeople = numInput.nextInt();
int[] totalPeople = new int[amountOfPeople];
System.out.println("Test");
for(int index = 0; index == totalPeople.length; index++){
System.out.println("Please enter an age for each person in the room:");
int ageOfPerson = numInput.nextInt();
ageOfPerson = totalPeople[index];
System.out.println("Test");
}
for(int index = 0; index == totalPeople.length; index++){
if(totalPeople[index] < 20 && totalPeople[index] > 0){
int[] underTwenty = null;
underTwenty[index] = totalPeople[index];
System.out.println("Test");
}
}
}
}
I also know the spacing is a bit off but I just copy/pasted and tried to make it look pretty for you all, so don't worry. Oh and the 'println' statements were just there to check and see where the program terminates.
Output:
How many people are in the room?
(A number you would've entered here)
Test
Ninja Edit:
Decided that I should come back to this post and place the finished code here for anyone who comes across this question and would like to take a look at the finished product.
import java.util.InputMismatchException;
import java.util.Scanner;
public class InterviewClass {
public static void main(String[] args){
try{
Scanner numInput = new Scanner(System.in);
System.out.println("How many people are in the room? (Ex: 5, 10, 24)");
int totalPeopleInRoom = numInput.nextInt();
int[] agesOfPeopleInRoom = new int[totalPeopleInRoom];
int youngPeople = 0, middleAged = 0, oldPeople = 0, deadPeople = 0;
System.out.println("Please enter an age for " + totalPeopleInRoom + " people (Ex: 17, 21, 45):");
for(int index = 0; index < agesOfPeopleInRoom.length; index++){
int tempAgePlaceHolder = numInput.nextInt();
agesOfPeopleInRoom[index] = tempAgePlaceHolder;
if((index + 1) == (totalPeopleInRoom/2)){
System.out.println("Half way there!");
}
}
System.out.println("Age Group\tAmount In Group");
for(int index = 0; index < agesOfPeopleInRoom.length; index++){
if(agesOfPeopleInRoom[index] < 30 && agesOfPeopleInRoom[index] > 0){
youngPeople = youngPeople + 1;
}
if(agesOfPeopleInRoom[index] < 60 && agesOfPeopleInRoom[index] > 30){
middleAged = middleAged + 1;
}
if(agesOfPeopleInRoom[index] < 115 && agesOfPeopleInRoom[index] > 60){
oldPeople = oldPeople + 1;
}
else if(agesOfPeopleInRoom[index] < 0 || agesOfPeopleInRoom[index] > 115){
deadPeople = deadPeople + 1;
}
}
System.out.println("Young People:\t" + youngPeople);
System.out.println("Middle Aged:\t" + middleAged);
System.out.println("Old People:\t" + oldPeople);
System.out.println("Dead People:\t" + deadPeople);
System.out.print("Total People:\t");
System.err.println(totalPeopleInRoom);
}catch(InputMismatchException inputException){
System.err.println("[ERROR] Wrong type of input used: " + inputException);
}
}
}
This is a bad for loop: for(int index = 0; index == totalPeople.length; index++)
Instead do: for(int index = 0; index < totalPeople.length; index++)
Let's break the for loop down:
The first part of the loop, int index = 0 is the initial condition. It tells the loop what the index should be set to when the loop starts.
The 2nd item in the for loop, in your loop you have index == totalPeople.length, is the condition statement that tells the for loop whether to keep looping if true or to stop looping if false. Your statement will be false when the loop tries to begin, and so the loop will never begin. So this is where your problem is. Instead you want to tell it to continue looping as long as the index is less than the length of the array, or in Java, index < totalPeople.length.
The 3rd item in the loop, here index++, tells the loop what to do with the index at the completion of each loop. Here you're telling it to increase by one, which is good.
The for loop condition must be true for it to iterate; it breaks out when it's false. In your case, it's false right away, so it never executes.
Instead of
for(int index = 0; index == totalPeople.length; index++){
try
for(int index = 0; index < totalPeople.length; index++){
And similarly for the other for loop.
In the Java tutorial on for loops, it states this:
When the termination expression evaluates to false, the loop terminates.
for(int index = 0; index == totalPeople.length; index++){
The second part in the parentheses is not a stopping condition, it is a check to continue. Use:
for(int index = 0; index < totalPeople.length; index++){
for(int index = 0; index == totalPeople.length; index++) should be
for(int index = 0; index < totalPeople.length; index++)
otherwise the boolean condition is evaluated to false and hence the loop doesn't execute
You should read this.
The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s) }
When using this version of the for statement, keep in mind that:
1. The initialization expression initializes the loop; it's executed once, as the loop begins.
2. When the termination expression evaluates to false, the loop terminates.
3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment
or decrement a value.
Your for loops are saying
Continue doing this code while index is equal to the arrays length
What you mean to say is continue doing this code while index is less than the arrays length
I have this piece of code here:
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
if (input.nextInt() == 999){
break;
} else {
array[i] = input.nextInt();
}
}
I want to break out of the loop if the user enters 999 inside the array but so far no luck. I tried using break or return false but nothing works. Does anyone have a solution? Much thanks!
You are using input.nextInt(); twice.That is reading from console in if and else.
for (int i = 0 ; i < array.length; i++ ) {
int enteredNumber = input.nextInt();
if (enteredNumber == 999){
break;
} else {
array[i] = enteredNumber ;
}
}
You are reading twice inside your loop. So, if your if condition is falsy (user does not enter 999), then it will go into else block where you are reading a new input from user, which can possibly be 999.
Change your loop to:
for (int i = 0 ; i < array.length; i++ ) {
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Apart from that, you should also consider the case where user doesn't actually passes an integer, in which case, your code will blow. You can use Scanner#hasNextInt() method for that.
for (int i = 0 ; i < array.length; i++ ) {
while (!input.hasNextInt()) {
System.out.println("You must pass an integer");
input.next(); // Advance the scanner past the current line.
}
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Of course, that loop might run forever if user keeps on entering non-integer values. To overcome that, you can give user a maximum number of attemps. That I'll leave up to you to handle. (HINT: You will need a counter that goes from 0 to max. On each loop iteration, reset it).
The way you currently have it is that you're calling nextInt() multiple times within each iteration.
That means you'll lose data. Let's say you first enter 7. That's picked up in the if statement as "not 999" so it moves onto the else clause where you ask the user for yet another number (you've lost the 7).
In addition, you'll only break out of that loop if you enter 999 when it's executing the first call to nextInt(). If you enter 999 when it's executing the second call, it will just store it and keep going.
Try this instead:
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
if (next == 999)
break;
array[i] = next;
}
Try this thing in your for loop.
for (int i = 0 ; i < array.length; i++ ) {
int number = input.nextInt();
if (number == 999){
break;
}
System.out.println("aghsdgha" + number);
}
This is the simpler and cleaner way to check the input number.