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.
Related
I have an assignment where I need to create a 3x5 array and ask the user for a boolean input. I then need to print the user input into every cell of the array. I'm stuck on how to use a for loop to enter the user input into the array. I also have to do this using methods. My code so far is:
import java.util.*;
public class TrueFalse
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [5][3];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
answ = console.nextBoolean();
for (int i=0; i<pArray.length; i++)
{
pArray[i] = answ;
}
}
}
You're not far off:
for (int i=0; i<pArray.length; i++) {
for (int j=0; i<pArray[i].length; j++) {
System.out.println("Enter true or false.");
pArray[i][j] = console.nextBoolean();
}
}
will do the trick. Note you defined a matrix with 5 rows and 3 columns, the opposite of what you write in the text. Also note I'm checking nothing here.
Your code is not far off. Try iterating over the bounds of the array in your popArray method:
public static void popArray(boolean pArray[][]) {
for (int r=0; r < pArray.length; ++r) {
for (int c=0; c < pArray[0].length; ++c) {
System.out.println("Enter true or false.");
boolean answ = console.nextBoolean();
pArray[r][c] = answ;
}
}
}
One convenient option for printing your 2D array is Arrays.deepToString(), e.g.
System.out.println(Arrays.deepToString(pArray));
To make 3*5 array of boolean you should do
boolean myA[][] = new boolean [3][5];
And make nested loop. and you can index the value to the array variable myA[ i ][ j ]
for(int i=0;i<3;i++){
for(int j=0;j<5;j++){
myA[i][j]=false;
}
}
In your code you have a two dimensional array but your not assessing it correctly. You can visualized your 2d array as a matrix with 5 rows and 3 columns. So to assess every location you need to specify the row and column numbers. Your code should look like this:
private static int ROWS= 5;
private static int COLUMNS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [ROWS][COLUMNS];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
for (int i=0; i<COLUMNS ; i++)
{
for (int j=0; j<ROWS; j++)
{
pArray[i][j] = console.nextBoolean();
}
}
}
So I was creating this random string generator:
public class Test {
public static void main(String[] args) {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random generator = new Random(System.currentTimeMillis());
int stringLength = strings.length()-1;
Character character;
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
String outputString = outputString.concat(character.toString());
}
System.out.println(outputString);
}
}
I went an compiled it using javac Test.java, and it gave me the error outputString might not have been initialised for lines 14 and 16. So I added the String keyword to line 14, and now it's telling me
cannot find symbol: variable outputString
Why is this so?
EDIT:
Okay so I took up the suggestions, and this is the code currently:
public class Test {
public static int randomInt(int min, int max, long seed) {
Random rand = new Random(seed);
int randomNum = rand.nextInt((max-min)+1) - min;
return randomNum;
}
public static void main(String[] args) {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int stringLength = strings.length()-1;
Character character;
for (int i = 0; i < stringLength; i++) {
Double test = new Double(randomInt(0, stringLength, System.currentTimeMillis()));
character = strings.charAt(test.intValue());
System.out.print(character);
}
}
}
The code runs without errors, but it doesn't print anything.
I'm currently using Command Prompt to compile it.
You are defining the outputString only inside of the for loop. It will not be available outside.
You could output the characters directly:
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
System.out.print(character);
}
System.out.println();
If you insist on concatenating a String in a loop, please use StringBuilder instead.
The next problem you will run into:
Double test = new Double(Math.random());
strings.charAt(test.intValue());
That will always get the the first character. The double will be between 0 (inclusive) and 1 (exclusive).
You need to create a random integer between 0 and the length of your alphabet.
The compiler is correctly telling that outputString is not declared correctly. The outputString is declared within the for loop, but you are trying to print the value outside.
A quick way to fix this would be to declare outputString outside the for loop by having outputString = "";
outputString is only defined within the block of the for loop, so once you exit it, it no longer exists. To make sure that your code works, define it outside the loop:
String outputString = "";
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
outputString += character.toString();
}
System.out.println(outputString);
It is because you are calling outputString.concat before you have intialized it
try
String outputString = "";
outputString = outputString.concat(character.toString());`
I managed to get it to work using the following code:
import java.util.Random;
public class Test{
public static void print(String str) {
System.out.print(str);
}
public static int randomInt(int min, int max) {
Random rand = new Random(System.currentTimeMillis());
int randomNum = rand.nextInt((max-min)+1) - min;
return randomNum;
}
public static void main(String[] args) throws InterruptedException {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int len = strings.length() - 1;
StringBuilder outputString = new StringBuilder(len);
for (int i = 0; i < len; i++) {
Double test = new Double(randomInt(0, len));
Integer value = test.intValue();
if (value <= len) {
//print(value.toString()); For testing purposes
outputString.append(strings.charAt(value));
Thread.sleep(1);
}
else {i--;}
}
print(outputString + "\n");
}
}
I have a java program where the following is what I wanted to achieve:
first input: ABC
second input: xyz
output: AxByCz
and my Java program is as follows:
import java.io.*;
class DisplayStringAlternately
{
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
displayStringAlternately(firstC, secondC);
}
public static void displayStringAlternately (String[] firstString, String[] secondString)
{
int combinedLengthOfStrings = firstString.length + secondString.length;
for(int counter = 1, i = 0; i < combinedLengthOfStrings; counter++, i++)
{
if(counter % 2 == 0)
{
System.out.print(secondString[i]);
}
else
{
System.out.print(firstString[i]);
}
}
}
}
however I encounter the following runtime error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
AyC at DisplayStringAlternately.displayStringAlternately(DisplayStringAlternately.java:23)
at DisplayStringAlternately.main(DisplayStringAlternately.java:12)
Java Result: 1
What mistake is in my Java program?
If both arrays have same length for loop should continue while i < anyArray.length.
Also you don't need any counter to determine from which array you should print first. Just hardcode that first element will be printed from firstString and next one from secondString.
So your displayStringAlternately method can look like
public static void displayStringAlternately(String[] firstString,
String[] secondString) {
for (int i = 0; i < firstString.length; i++) {
System.out.print(firstString[i]);
System.out.print(secondString[i]);
}
}
Anyway your code throws ArrayIndexOutOfBoundsException because each time you decide from which array print element you are incrementing i, so effectively you are jumping through arrays this way
i=0 i=2
{"A","B","C"};
{"x","y","z"};
i=1 i=3
^^^-here is the problem
so as you see your code tries to access element from second array which is not inside of it (it is out of its bounds).
As you commented, If both arrays length is same, you can simply do
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
Then
for(int i = 0; i < firstC.length; i++) {
System.out.print(firstC[i]);
System.out.print(secondC[i]);
}
Using the combined length of the Strings is wrong, since, for example, secondString[i] would cause an exception when i >= secondString.length.
Try the below working code with high performance
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < firstC.length; i++) {
builder.append(firstC[i]);
builder.append(secondC[i]);
}
System.out.println(builder.toString());
}
public class concad {
public void main(String[] args) {
String s1 = "RAMESH";
String s2 = "SURESH";
int i;
int j;
for (i = 0; i < s1.length(); i++) {
System.out.print(s1.charAt(i));
for (j = i; j <= i; j++) {
if (j == i) {
System.out.print(s2.charAt(j));
}
}
}
}
}
I have taken two strings as mentioned.Then pass one counter variable in inner for-loop with second string,Then for every even position pass with code "counter%2".Check this out if any concern then comment below.
public class AlternatePosition {
public static void main(String[] arguments) {
String abc = "abcd";
String def = "efgh";
displayStringAlternately(abc, def);
}
public static void displayStringAlternately(String firstString, String secondString) {
for (int i = 0; i < firstString.length(); i++) {
for (int counter = 1, j = 0; j < secondString.length(); counter++, j++) {
if (counter % 2 == 0) {
System.out.print(secondString.charAt(i));
break;
} else {
System.out.print(firstString.charAt(i));
}
}
}
}
}
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 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--;
}