Java: For loop not printing the last iteration - java

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

Related

repeat number sequence on java

So recently a had an exam to make this simple program on java:
You enter a number, then the program needs to repeat a sequence based on the amount you entered, like this: if it was number 3 it should show 01-0011-000111, as you can see the numbers repeat in the same row, if it would be number 5 it should show: 01-0011-000111-00001111-0000011111 without the "-" symbol, I'm just putting it for you to understand better.The only thing I could do was this:
Scanner lea = new Scanner(System.in);
int number;
int counter = 1;
System.out.println("Enter a number");
number = lea.nextInt();
while(counter<=number){
System.out.print("0");System.out.print("1");
counter = counter + 1;
}
thanks in advance!
I have a feeling this is inefficient, but this is my idea:
You'd need to use 1 loop with 2 additional loops inside it. The outside loop will iterate N times (the amount the user specified), and the 2 loops inside will iterate the number of current iterations the outside loop has. One of them is for printing 0s and the other for printing 1s.
In code, it would look like so:
for(int i = 0; i < N; i++){
for(int j = 0; j <= i; j++){
System.out.print(0);
}
for(int j = 0; j <= i; j++){
System.out.print(1);
}
if(i + 1 != N) System.out.print(" ");
}
I'd rather use 1 for loop for this case with a formatted string using String.repeat
for (int i =0; i <= N; i++)
System.out.print(String.format("%s%s ","0".repeat(i),"1".repeat(i)));

JAVA : Not printing the last iteration of the loop until I press enter

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.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.
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();
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;
}

While-loop Restriction

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++;
}

Palindromes using Stacks and Queues

My NEW sample text i was testing: My mom is a good cook. Although sometimes at around noon she will leave and forget to make me lunch and some pop. #Old homework become relevant again
my problem is just that i am not getting the correct output, as my method only prints *Mom a noon i
This is all GUI based.I am reading in a file and checking for palindromes and printing them out in my JTextArea afterwards using Stacks and Queue's.
Issue is, all of this is working and when i start the program and attach the text file, i only get the first palindrome. SO it will print "mom" which is my first testcase, but it won't go to any of the other palindromes following it?
I thought i might have got bogged down in my code blocking at some point but after tinkering with it for a day now i'm sort of stuck.
EDIT 1: I am now getting more results
my method is,
public void fileDecode() throws FileNotFoundException
{
if (fileChoice.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
file = fileChoice.getSelectedFile();
scanInput = new Scanner(file);
while(scanInput.hasNext())
{
int nextPalindrome = 0;
int counter = 0;
String token = scanInput.next();
Stack<Character> stk = new Stack<Character>();
Queue<Character> que = new LinkedList<Character>();
for (int i = 0; i < token.length(); ++i)
{
stk.push(token.charAt(i)); //pushing all char's onto the stack/queue
que.add(token.charAt(i));
}
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk == tempQue)
{
counter++;
}
}
if (counter == token.length())
{
build.append(token + " "); //if the counter # was the same as the token's length, than it is indeed a palindrome and we append it into our StringBuilder that we pass to the JTextArea
nextPalindrome = token.length();
}
}
}
}
You set counter to 0 outside your while loop, so the count of the second word is going to start at the count of the first word. Move counter = 0 inside the while loop and it should work.
Also, nextPalindrome doesn't appear to be used, and even if it is, if you set it at the bottom of the loop, it's immediately set to 0 at the top, so it will only remain non-zero if the last word is a palindrome.
Also, think about what's happening in the second for loop. You're looping over all the characters and comparing the one from the stack and the one from the queue. If ever those are different, you know you don't have a palindrome, so once you find a difference, it's pointless to continue with the loop. You also already have a loop counter, j, so you don't need another one. So I'd rewrite the second loop and following condition as follows:
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk != tempQue)
break;
}
if (j == token.length())
That works because the only way j can equal token.length() after the loop is done is if the loop completed, which can only happen if no pairs of characters aren't equal (in other words, all pairs of characters are equal, which is what you want).

Program Terminates Before Reaching Essential Code

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

Categories