I am using a for loop to print the backwards alphabet in uppercase but I would like to know how to do the same thing with a while loop, which I am not very good with.
String alphabet = "abcdefghijklmnopqstuvwxyz";
int x = 0;
for(x = alphabet.length() - 1; x > -1; x--) {
System.out.print(alphabet.charAt(x));
System.out.print(alphabet.toUpperCase());
}
I also need to terminate it when it reaches A. think it's something like this, but I don't know how to make it loop backwards. I'd really appreciate your help!
while(alphabet.length() < 26) {
System.out.print(alphabet.charAt(x));
System.out.print(alphabet.toUpperCase());
if(x == A) {
break;
}
}
for (initialization; condition; increment) {
}
is same as:
{
initialization;
while(condition) {
// body
increment;
}
}
The outer block creates a block scope for the initialized parameter, that we get in a for loop also. But, if you are declaring your for-loop variable outside the loop, then you can omit that outer block.
Now you can map your for loop to the while loop.
There is a much simpler way to reverse a string in Java.
public class StringReversalExample {
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqstuvwxyz";
String reversedString = new StringBuilder(alphabet).reverse().toString();
System.out.println(reversedString);
}
}
Try this:
public static void main(String[] args) {
char[] alphabet = "abcdefghijklmnopqstuvwxyz".toCharArray();
int index = alphabet.length - 1;
while (index >= 0) {
System.out.println(alphabet[index--]);
}
}
This is a most efficient solution with minimal memory overhead.
x = alphabet.length() - 1;
while( x > -1 )
{
System.out.print( alphabet.charAt( x ));
System.out.print( alphabet.toUpperCase() );
x--;
}
Related
public class Main {
public static int count = 0;
public static void main(String[] args) {
String str = "AAAA";
System.out.println(delete1(str));;
}
private static int delete1(String str) {
if (str.length() > 1) {
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i-1) == str.charAt(i)) {
count++;
str = str.substring(i, str.length());
delete1(str);
}
}
}
return count;
}
}
count should come as 3 in this case...but coming as 4
For loop inside recursive method does not have break statement. put break; statement after delete1(str); statement will work.
delete1(str);
break;
while using recursive you should know where to break the loop and how functional flow happens in java.
in your case for all sub strings of length more than 2 will call delete method more than once. that's why you got output as 4.
There are multiple things wrong with your code:
You have the count on class-level and also let your method return this count.
You continue your loop after your recursive call
Not really wrong, but your if(str.length() > 1) check is redundant since your loop is already looping in the range [1, length), so the loop wouldn't start anyway if the length is smaller than or equal to 1.
Keeping the things above in mind, you could change it to this:
class Main {
public static void main(String[] args){
String str = "AAAA"; // Expected output: 3
countChars(str);
System.out.println(count);
}
private static int count = 0;
private static void countChars(String str){
int length = str.length();
for(int i = 1; i < length; i++){
if(str.charAt(i-1) == str.charAt(i)){
count++;
String substr = str.substring(i, length);
countChars(substr);
break;
}
}
}
}
Which puts the count at 3 in the end as you expected.
Try it online.
I'm still not entirely sure what you are trying to accomplish however. For example, what would the expected output be for AAAABABBAB or ABAAAAABBABA? Also, it would be better if the count isn't a static class-level field so it can more easily be re-used.
I have no clue how I would research this otherwise, so here this is. I'm trying to create a program that will "flip bits", e.g. the string "00110011" would return "11001100". I tried to make a for loop to output the individual characters so see if getting the characters would work in this way, but it stops without outputting the characters.
public static void main(String[] args) {
String bitsList = "01010101";
char[] sepBits = bitsList.toCharArray();
System.out.println("Array'd");
int num = bitsList.length();
System.out.println("Got length");
for (int count = 0; count == num;) {
System.out.println(sepBits[count]);
System.out.println("Outputted " + sepBits[count]);
}
}
You never go in your for loop because count is 0 and num is 8 (length of "01010101"). Therefore count == num evaluates to false and the for loop is not entered.
Try to replace your for loop with:
for (int count = 0 ; count < num ; count++) {
// ...
}
The variable count is not equal to the variable num so the for loop never triggers. I think you are looking for <= not ==. Also you never change the count so the loop will just keep printing the same spot over and over even if you do change this.
this might work for you
public static void main(String []args){
String bitsList = "01010101";
char[] sepBits = bitsList.toCharArray();
int num = bitsList.length();
for ( int i = num - 1 ; i >= 0 ; i-- ) {
System.out.println("Outputted " + sepBits[i]);
}
}
Why is the variable eachLetter unknown when I reference it in the second loop?
import java.util.*;
public class Main {
public static void main(String [] args) {
String myName = ("Yourname");
int maxLength = myName.length() - 1;
for (int loops = 0; loops <= maxLength; loops++) {
char[] eachLetter = myName.toCharArray();
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
System.out.println("");
System.out.println("next loop");
for (int loops = maxLength; loops <= 0; loops--) {
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
}
}
Because it lives only in first loop scope. You have to declare it before you enter into first loop.
char[] eachLetter = new char[maxLength];
for (int loops=0; loops <= maxLength; loops++) {
eachLetter = myName.toCharArray();
}
for (int loops= maxLength; loops<=0; loops--) {
(..)
}
First, lets format your code so it's legible:
public static void main(String[] args) {
String myName = ("Yourname");
int maxLength = myName.length() - 1;
for (int loops = 0; loops <= maxLength; loops++) {
char[] eachLetter = myName.toCharArray();
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
System.out.println("");
System.out.println("next loop");
for (int loops = maxLength; loops <= 0; loops--) {
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
}
Now, in Java - like in VBA with Option Explicit - each variable must be declared in scope to be visible.
In Java scope is within curly brackets so:
{
char[] thing = ...
thing[i]...
}
//error
thing[i]
This is because the second thing[i] is outside of the curly brackets.
In your example you declare eachLetter within the for loop - each iteration has its own instance. You are trying to access it outside of the loop. The only way to do this is to declare it in a wider scope - i.e. in the next set of curly brackets up, the method:
public static void main(String[] args) {
String myName = ("Yourname");
int maxLength = myName.length() - 1;
char[] eachLetter = ...
for (int loops = 0; loops <= maxLength; loops++) {
eachLetter = myName.toCharArray();
But the real question is why you are doing this. Every time the for loop iterates you get a different char[]. You will only be able to access the last one from outside the loop.
I am trying to create a Mastermind game in which colors are numbers [] and one number can never repeat itself in the String. The string should be made of 4 characters. I cannot figure out why my code keeps on printing strings with repeated characters.
import java.util.Random;
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
String toGuess="";
while(!IsValidNumber(toGuess));
{
for(int i=0; i<4; i++)
{
Random rando= new Random();
int rd=rando.nextInt(9);
toGuess=toGuess+rd;
}
}
System.out.println(toGuess);
}
public static boolean IsValidNumber(String s) // boolean
{
boolean noRepetition = true;
for(int i = 0; i < s.length(); i++)
{
for(int j = 0; j < i; j++)
{
if(i == j)
{
continue;
}
else if(s.charAt(i) == s.charAt(j))
{
noRepetition = false;
return false;
}
}
}
return noRepetition;
}
}
The boolean IsValidNumber never operates, I tried to print simple check words at different levels of it, and nothing ever prints but the String.
Thanks in advance, cheers
You've got a stray semicolon after the while() declaration, which causes the loop to immediately end. Consequently, your for loop constructs a number, and whatever number it constructs is immediately printed.
Consider the following instead:
public static void main(String[] args)
{
String toGuess="";
do { // Always try to generate at least one number.
toGuess = ""; //Reset each time we loop.
for(int i=0; i<4; i++) {
Random rando= new Random();
int rd=rando.nextInt(9);
toGuess=toGuess+rd;
}
} while(!IsValidNumber(toGuess));
System.out.println(toGuess);
}
That might work better.
Basically, while (exp); is equivalent to while(exp) {} or an empty while loop. Only put a semicolon after your while(exp) when using the do...while construct I illustrate here.
I'm trying to write a method that returns the number of times char c first appears consecutively in s, even if it's a single occurrence of the character. Even spaces break the consecutive count. So the string "I'm bad at programming." should only return 1, if char c was 'a'.
The code below compiles but doesn't print the correct answers. Just something to show my general logic when it comes to approaching this problem.
public class WordCount
{
public int countRun( String s, char c )
{
int counter = 0;
for( int i = 0; i < s.length(); i++)
/*There should be other conditions here that checks for first
appearance consecutively. I've tried my fair share, but no
luck on getting correct results.*/
{
if( s.charAt(i) == c )
{
counter += 1;
}
}
return counter;
}
public static void main( String args[] )
{
WordCount x = new WordCount();
System.out.println( x.countRun( "Add dog", 'd' ) ); //should return 2
System.out.println( x.countRun( "Add dog", 'D' ) ); //should return 0
System.out.println( x.countRun( "Hope you're happy", 'p' )); //should return 1
System.out.println( x.countRun( "CCCCCcccC", 'C' )); //should return 5
}
}
I just need a few pointers (logic-wise or code). Maybe there's a method for Strings that I've never seen before that could make my program much simpler. I have very limited knowledge in programming and in Java.
EDIT: For anyone wondering if this is part of some homework assignment or whatnot, this was a question from a very old midterm. I got it wrong but for some reason but never bothered to ask for the correct answer at the time. I looked at it today and wanted to see if I knew the answer. Looks like I don't.
You could do it in one line:
int result = s.replaceFirst(".*?(" + c + "+).*", "$1").length();
This code uses regex to essentially extract the part of s that is the first contiguous occurrences of c, then gets the length of that.
This will also work for no occurrences, yielding zero.
See live demo.
Add a flag, and break out of the loop when you have found one matching character, then find "anything else". Maybe not the most compact or elegant, but true to the original code. Tested, and produces 2,0,1,5 as expected.
public int countRun( String s, char c )
{
int counter = 0;
boolean foundOne = false;
for( int i = 0; i < s.length(); i++)
{
if( s.charAt(i) == c )
{
counter += 1;
foundOne = true;
}
else {
if(foundOne) break;
}
}
return counter;
}
It occurs to me that counter>0 is an equivalent condition to foundOne==true; that would allow you to simplify the code to:
public int countRun( String s, char c )
{
int counter = 0;
for( int i = 0; i < s.length(); i++)
{
if( s.charAt(i) == c ) counter++;
else if(counter>0) break;
}
return counter;
}
The logic is a tiny bit harder to follow this way, as the variable name foundOne is self-documenting. But per other posts, "small is beautiful" too...
Using assci array counter
public static int countRun(String s, char c) {
int[] counts = new int[256];
int count = 0;
char currChar;
for (int i = 0; i < s.length(); i++) {
currChar = s.charAt(i);
if (currChar == c) {// match
counts[c]++;
} else if (Character.isSpaceChar(currChar)) {
counts[c] = 0;// reset counter for c
} else {// no match
if (counts[c] > 0) {// return accumulated counts if you have
count = counts[c];
return count;
}
}
}
return count;
}
public class A3B2C1 {
public static void main(String[] args) {
String s = "AAABBC";
s = s + '#';//dummy char to consider the last char 'C' in the string
//without using charAt()
int count = 1;
String n="";
int i=0;
StringBuffer bf = new StringBuffer();
char c[] = s.toCharArray();
for(i=0;i< c.length-1;i++)
{
if(c[i] == c[i+1])
{
count++;
}
else
{
n = c[i] +""+count;
bf.append(n);
count=1;
}
}
System.out.println("Output: "+bf);//prints-->> Output: A3B2C1
}
}