while (boolean expression)
{execute this code;}
First the logical condition is evaluated - when it is true
, the code inside the while loop will be executed. This repeats until the condition evaluates to false
.
Question: Is it possible for a while loop to execute 0 times?
An infinite loop is a loop where the condition always evaluates to true
.
Example of an infinite loop:
while (true)
{do this stuff;}
The condition will always evaluate to true
because true
is always true
.
A return
statement can stop the execution of a loop and exit the method or constructor.
My tasks:
import java.util.Scanner;
public class Main
{
public static void Main()
{
System.out.println("Type the month number:");
Scanner keyboard= new Scanner (System.in);
System.out.println(returnMonthName(keyboard.nextInt()));
}
public static String returnMonthName(int month)
{
String Months="January February March April May June July August September October November December ";
int monthIndex=1;
int stringIndex=0;
int endOfMonthIndex=0;
while (monthIndex<month)
{
if (Months.substring(stringIndex,stringIndex+1).equals(" "))
monthIndex++;
stringIndex++;
}
endOfMonthIndex=stringIndex;
while (!Months.substring(endOfMonthIndex,endOfMonthIndex+1).equals(" "))
{
endOfMonthIndex++;
}
return Months.substring(stringIndex,endOfMonthIndex);
}
}
Solutions:
public class Divisibility
{
public Divisibility()
{
}
public boolean evenlyDivisible(int number1,int number2)
{
if (number1%number2==0)
return true;
else
return false;
}
}
public class Main
{
public static void Main()
{
int number1=6;
int number2=4;
Divisibility d1=new Divisibility();
String result="";
if (d1.evenlyDivisible(number1,number2))
result="is";
else
result="isn't";
System.out.println("Number "+number1+" "+result+" evenly divisible by "+number2+".");
}
}
2.
public class Main
{
public static void Main()
{
int number=256; //declaring and initializing a primitive variable
Integer Number=new Integer(number); // creating a wrapper class so that you can convert the integer to a string
String numberAsText=Number.toString(); // converting an integer to a string
int index=0;// this will be the index used for traversing the string
while (index<numberAsText.length())
{
System.out.println(numberAsText.substring(index,index+1));
index++;//increasing the index value by one for each iteration
}
}
}
import java.util.Scanner;
public class Main
{
public static boolean isPalindrome(String word)
{
int index=0;
while (index<word.length())
{
if (!word.substring(index,index+1).equals(word.substring(word.length()-index-1,word.length()-index)))
{
System.out.println("Not a palindrome");
return false;
}
index++;
}
System.out.println("This is a palindrome");
return true;
}
public static void Main()
{Scanner keyboard=new Scanner(System.in);
String input="";
int noOfPalindromes=0;
while (!input.equals("exit"))
{
System.out.println("Input a word");
input=keyboard.next();
if (isPalindrome(input))
{
noOfPalindromes++;
}
}
System.out.println("You typed "+noOfPalindromes+ " palindromes.");
}
}
Parts of a for-loop header:
for (initialization, Boolean expression, increment)
int i=0
i<10
i++
A sample for-loop:
for (int i=1;i<=10;i++)
{System.out.println(i));
i
variable in the for-loop above is called a loop control variable. It is commonly named "i" as it stands for "iteration", however, it can use any valid name here, such as "counter
".This involves the following standard traversal (traversing through a string) algorithms to be familiar with:
A one-loop solution:
import java.util.Scanner;
public class Main
{
public static void Main()
{ int vowelsCounter=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("Type the word to count the vowels for:");
String input=keyboard.next();
String vowels="aeiouy";
for (int i=0;i<input.length();i++)
{
if (vowels.indexOf(input.substring(i,i+1))>=0)
vowelsCounter++;
}
System.out.println("The word "+input+" includes "+vowelsCounter+" vowel/s.");
}
}
A two-loop solution:
import java.util.Scanner;
public class Main
{
public static void Main()
{ int vowelsCounter=0; // this is where we store the vowels count
Scanner keyboard=new Scanner(System.in);
System.out.println("Type the word to count the vowels for:");
String input=keyboard.next();
String vowels="aeiouy"; //this stores all the vowels to look for
String currentVowel=""; // this stores the current vowel from the list that we are checking
String currentInputLetter=""; // this stores the current letter from the input text
for (int i=0; i<vowels.length();i++)
{
currentVowel=vowels.substring(i,i+1);// I change the vowel to look for here
for (int j=0;j<input.length();j++)
{
currentInputLetter=input.substring(j,j+1);// I change the current letter of the input
if (currentInputLetter.indexOf(currentVowel)>=0)
vowelsCounter++;
}
}
System.out.println("The word "+input+" includes "+vowelsCounter+" vowel/s.");
}
}
A nested loop example:
// prints the multiplication facts up to 10*10
for (int i=1;i<=10;i++)
{
for (int j=1;j<=10;j++)
{
System.out.println(i+"*"+j-"="+i*j);
}
}
You should be able to tell how many times a certain statement got executed during the running of a loop.
You should also be able to trace how a certain variable contents change during the running of a loop. For this it is useful to use a tracing table.
You can find the student notes to this lab here.
textToString()
method with your review saved as a text file as input.getPunctuation()
method or you can devise your own way of doing this, such as by traversing the whole string and copying it to a new string, character by character, provided the character is not on the "black list", which would be the list of all the punctuation that there is.split()
method, use your spaces as a sentinel) and fetch the sentiment value for each word by using the sentimentVal()
method which you need to add the running total. Also, keep track of the number of words you have evaluatedtotalSentiment()
to find the sentiment value of the reviewif-else-if
statements for this. public static double totalSentiment(String fileName)
{
int WordCount=0;
String Word="";
double totalSentimentValue=0.0;
String ReviewText=textToString(fileName);
String TextWithoutPunctuation="";
//removing punctuation:
for (int i=0; i<ReviewText.length();i++)
{
if (getPunctuation(ReviewText.substring(i,i+1))=="")
TextWithoutPunctuation+=ReviewText.substring(i,i+1);
else
TextWithoutPunctuation+=" ";
}
//fetching the sentiment value for each word and adding it to the total
for (int j=0; j<TextWithoutPunctuation.length();j++)
{
if (!TextWithoutPunctuation.substring(j,j+1).equals(SPACE))
Word+=TextWithoutPunctuation.substring(j,j+1);
else
{
System.out.println(sentimentVal(Word));
totalSentimentValue+=sentimentVal(Word);
WordCount++;
Word="";
}
}
//calculating the average sentiment value and returning it:
return totalSentimentValue/WordCount;
}
public static int starRating(String fileName)
{
double totalSentimentValue=totalSentiment(fileName);
if (totalSentimentValue>2)
return 4;
else if (totalSentimentValue>1)
return 2;
else if (totalSentimentValue>0)
return 1;
else
return 0;
}
fakeReview() method:
textToString()
method to generate a string from the review text file.randomAdjective()
method and store the outcome in a variable public static String fakeReview(String fileName)
{
String Word="";
String ReviewText=textToString(fileName);
String FakeReview="";
String EndingPunctuation="";
String RandomAdjective="";
//traverse through the review string, keep building the word until you hit a space:
for (int i=0;i<ReviewText.length();i++)
{ if (!ReviewText.substring(i,i+1).equals(SPACE))
Word+=ReviewText.substring(i,i+1);
//when the whole word has been read:
else
{
//look only for words that start with a star (i.e. adjectives):
if (Word.substring(0,1).equals("*"))
{
EndingPunctuation=getPunctuation(Word);
RandomAdjective=randomAdjective();
//add a random adjective to the review with the original punctuation (if any) plus a space:
FakeReview+=RandomAdjective+EndingPunctuation+" ";1
}
else
FakeReview+=Word+" ";
Word="";
}
}
return FakeReview;
}
sentimentVal()
method for it and save the corresponding sentiment value in a variable.randomPositiveAdj()
method, for a more negative review call the randomNegativeAdj()
method. Find the sentiment value of the random adjective and see if it is higher or lower than the original adjective's sentiment value. If you are trying to create a more positive review, keep calling the randomPositiveAdj()
method until it has returned an adjective that has a higher sentiment value than the original adjective. If you are trying to create a more negative review, keep calling the randomNegativeAdj()
method until its sentiment value is lower than that of the original adjective.public static String fakeNegativeReview(String fileName)
{
String Word="";
String ReviewText=textToString(fileName);
String FakeNegativeReview="";
String EndingPunctuation="";
String RandomAdjective="";
double SentimentValue=0;
for (int i=0;i<ReviewText.length();i++)
{ if ((ReviewText.substring(i,i+1).equals(SPACE)) || (i==ReviewText.length()-1))
{
if (i==ReviewText.length()-1)
Word+=ReviewText.substring(i,i+1);
if (Word.substring(0,1).equals("*"))
{
EndingPunctuation=getPunctuation(Word);
RandomAdjective=randomNegativeAdj();
while (sentimentVal(Word)<sentimentVal(RandomAdjective))
RandomAdjective=randomNegativeAdj();
FakeNegativeReview+=RandomAdjective+EndingPunctuation+" ";
}
else
FakeNegativeReview+=Word+" ";
Word="";
}
else
Word+=ReviewText.substring(i,i+1);
}
System.out.println(FakeNegativeReview);
return FakeNegativeReview;
}