Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- //Scope
- //Nested for loops
- //For loops to while loops
- //Strings
- public class L9ForLoopsDay2{
- public static void main(String[] args){
- //Declaring a variable inside of an if-statement, loop, or any block of code { }
- //limits that variable to existing inside of that block of code ONLY
- //The examples below are illegal. Try uncommenting them and running them to see
- // //Ex1
- // int a = 4;
- // if( a >= 3 ){
- // int b = 5;
- // }
- // System.out.println( b );
- // //Ex2
- // for(int i = 0; i < 3; i++){
- // System.out.println("hi");
- // }
- // System.out.println( i );
- // //Nested For Loop example
- System.out.println( "i\tj" );
- for( int i = 1; i <= 2; i++ ){
- for( int j = 1; j <= 3; j++ ){//this loop is inside and happens more often
- System.out.println( i + "\t" + j );//see that j changes more often and when j goes past 3, i gets incremented and inner loop starts again
- }
- }
- //Print a 10 x 10 box of *
- //or any of the other options in #18 on http://www.beginwithjava.com/java/loops/questions.html
- for(int b = 1; b <= 10; b++){
- for(int a = 1; a <= 10; a++){
- System.out.print("* ");
- }
- System.out.println();
- }
- // //For loop to While loop
- // for( int k = 0; k < 9; k++ ){
- // System.out.println( k );
- // }
- //
- // int k = 0;//initialization expression goes before
- // while( k < 9 ){//control expression goes inside
- // System.out.println( k );
- // k++;//step expression goes at bottom of loop
- // }
- // //Loop over the characters in a String
- Scanner kb = new Scanner(System.in);
- System.out.print("Enter a word: ");
- String word = kb.next();
- for(int i = 0; i < word.length(); i++){//start loop @ index 0, go up until but not including the length, count by 1
- String letter = word.substring(i, i+1);//substring(i,i+1) gets one letter at a time (first thing you want, first thing you don't want)
- System.out.println( letter );
- }
- //Write code to find how many vowels the user's name contains. The user inputs their name from the keyboard
- System.out.print("Enter your name: ");
- String name = kb.next();
- int vowels = 0;
- for(int i = 0; i < name.length(); i++ ){
- String letter = name.substring(i, i+1).toLowerCase();
- if( letter.equals("a") || letter.equals("e") || letter.equals("i")
- || letter.equals("o") || letter.equals("u") ){
- vowels++;
- }
- }
- System.out.println( "Your name has " + vowels + " vowels" );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement