How to Print Random number in a Math Table? - java

I am implementing a math table using two integers (a and tableSize). I have built a random operation named R. I am going to calculate a random number between the row and column range and print the random number. For those instances where the row value is larger than the column value, the output is a dash ("-").
Here is my code,
int a = 4;
int tableSize = 10;
System.out.print(" R ");
for(int i = a; i <= tableSize;i++ )
{
System.out.format("%4d",i);
}
System.out.println();
for(int i = a ;i <= tableSize;i++)
{
System.out.format("%4d ",i);
for(int j=a;j <= tableSize;j++)
{
int randomNum = rand.nextInt (j) + i;
if(!(i > j))
{
System.out.format("%4d", randomNum);
} else
{
System.out.format("%4s", "-");
}
}
System.out.println();
}
The output I need is like this,
R 4 5 6 7 8 9 10
4 4 4 5 5 4 9 8
5 - 5 5 6 5 9 8
6 - - 6 6 7 9 6
7 - - - 7 7 7 7
8 - - - - 8 9 9
9 - - - - - 9 10
10 - - - - - - 10
But the problem is I didn't get output like that. output I receive is,
R 4 5 6 7 8 9 10
4 5 7 6 8 8 10 13
5 - 5 9 8 8 10 12
6 - - 9 8 11 10 11
7 - - - 8 14 9 16
8 - - - - 14 12 11
9 - - - - - 13 18
10 - - - - - - 19
And the row value is larger than the column value, Please anyone can help me? Thanks in advance.

The problem is that you are computing the cell value as the sum of a random number between 1 and the column number plus the row number. The logic I think you want is that a given cell in the matrix can be no larger than the max of the row or column number. If so, then you need to change this line:
int randomNum = rand.nextInt(j) + i;
To this:
int randomNum = rand.nextInt((Math.max(i, j) - a) + 1) + a;
Demo

Change your random number like this.
int randomNum = rand.nextInt((tableSize - a) +1)+a;
Output:
R 4 5 6 7 8 9 10
4 4 6 7 6 6 7 7
5 - 6 5 4 6 8 8
6 - - 7 8 7 7 8
7 - - - 10 7 5 5
8 - - - - 9 5 8
9 - - - - - 8 8
10 - - - - - - 4

You want a number that can be up to the higher limit (inclusive), but Random.nextInt(int) excludes the higher limit, so you need to add 1 to the argument. To get a random number from zero to 10 (inclusive), you can use rand.nextInt(10+1).
But you also have a lower bound. It's correct that you need to add the lower bound to the result as you did, but you need to subtract it from the range first.
You need to change this line:
int randomNum = rand.nextInt (j) + i;
To this:
int randomNum = rand.nextInt(j + 1 - i) + i;
But you need to move this line within your check that i <= j, or else your range becomes negative:
if (i <= j) {
int randomNum = rand.nextInt(j + 1 - i) + i;
System.out.format("%4d", randomNum);
} else {
System.out.format("%4s", "-");
}
Output:
R 4 5 6 7 8 9 10
4 4 5 5 7 4 5 8
5 - 5 6 6 5 5 5
6 - - 6 6 8 8 9
7 - - - 7 7 9 9
8 - - - - 8 9 9
9 - - - - - 9 9
10 - - - - - - 10

First, you should know how to get random between two integers, and then code the rest (check code comments)
Here is an implementation using ternary operator ?:, which is good to know of
PrintR.java:
import java.util.Random;
public class PrintR {
public static void main(String[] args) {
int a = 4;
int end = 10;
printRTable(a, end);
}
public static void printRTable(int init, int end) {
Random rand = new Random();
// first print the top header row
System.out.format(" R ");
for(int i = init; i<=end;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------");
for(int i = init ;i<=end;i++) {
// print left most column first
System.out.format("%4d |",i);
for(int j=init;j<=end;j++) {
//Ternary operator
//r.nextInt(High-Low + 1) + Low; gives you a random number in between Low (inclusive) and High (inclusive)
System.out.format("%4s", i > j ? "-" : (rand.nextInt(j-i+1)) + i);
}
System.out.println();
}
}
}
Example output:
R 4 5 6 7 8 9 10
------------------------------------------
4 | 4 4 5 7 5 5 4
5 | - 5 6 6 5 8 10
6 | - - 6 7 7 6 8
7 | - - - 7 7 7 10
8 | - - - - 8 8 10
9 | - - - - - 9 10
10 | - - - - - - 10

Related

Bubble sort with output

So I have edited it some and am getting almost exactly what I want. The only problem I am having now is that I am getting a line of output that I don't want. I feel like the fix here is simple but my brain is fried right now.
static void bubbleSort(int[] myArray) {
int n = myArray.length;
int temp = 0;
int counter = 0;
for (int i = 0; i < n; i++) {
int k;
for (k = 0; k < n; k++) {
System.out.print(myArray[k] + "|");
}
System.out.println(" Num swaps: " + counter);
for (int j = 1; j < (n - i); j++) {
if (myArray[j - 1] > myArray[j]) {
//swap elements
temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
counter++;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter slot " + i + ": ");
myArray[i] = sc.nextInt();
}
bubbleSort(myArray);
}
Here is an example of what I get:
Enter slot 0: 10
Enter slot 1: 9
Enter slot 2: 8
Enter slot 3: 7
Enter slot 4: 6
Enter slot 5: 5
Enter slot 6: 4
Enter slot 7: 3
Enter slot 8: 2
Enter slot 9: 1
10|9|8|7|6|5|4|3|2|1| Num swaps: 0
9|8|7|6|5|4|3|2|1|10| Num swaps: 9
8|7|6|5|4|3|2|1|9|10| Num swaps: 17
7|6|5|4|3|2|1|8|9|10| Num swaps: 24
6|5|4|3|2|1|7|8|9|10| Num swaps: 30
5|4|3|2|1|6|7|8|9|10| Num swaps: 35
4|3|2|1|5|6|7|8|9|10| Num swaps: 39
3|2|1|4|5|6|7|8|9|10| Num swaps: 42
2|1|3|4|5|6|7|8|9|10| Num swaps: 44
1|2|3|4|5|6|7|8|9|10| Num swaps: 45
That first line of output where it just repeats what the user input and says 0 swaps. I don't want that.
Just changed the position of the for loops. Hope this is the output you actually want :).
static void bubbleSort(int[] myArray) {
int n = myArray.length;
int temp = 0;
int counter = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (myArray[j - 1] > myArray[j]) {
// swap elements
temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
counter++;
}
}
int k;
for (k = 0; k < n; k++) {
System.out.print(myArray[k] + "|");
}
System.out.println(" Num swaps: " + counter);
}
}
Algorithm with two nested streams: Bubble sort with step-by-step output Java 8
Bubble sort with step-by-step output
The outer do-while-loop repeats until the array is sorted, and the inner for-loop passes through the array, swapping the unordered adjacent elements. The output is the swapped elements in the inner loop, grouped by passes in the outer loop.
public static void main(String[] args) {
int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
bubbleSort(arr);
}
public static void bubbleSort(int[] arr) {
// counters
int passes = 0, swaps = 0;
// marker
boolean swapped;
// repeat the passes through the array until
// all the elements are in the correct order
do {
// output the beginning of the pass and increase the counter of passes
System.out.print((passes == 0 ? "<pre>" : "<br>") + "Pass: " + passes++);
swapped = false;
// pass through the array and
// compare adjacent elements
for (int i = 0; i < arr.length - 1; i++) {
// if this element is greater than
// the next one, then swap them
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
// output the array and increase the counter of swaps
System.out.print(outputSwapped(arr, i, i + 1, swaps++));
}
}
// if there are no swapped elements at the
// current pass, then this is the last pass
} while (swapped);
// output total
System.out.print("<br>Total: Passes=" + passes);
System.out.println(", swaps=" + swaps + "</pre>");
}
static String outputSwapped(int[] arr, int e1, int e2, int counter) {
StringBuilder sb = new StringBuilder("<br>");
for (int i = 0; i < arr.length; i++) {
if (i == e1 || i == e2) {
// swapped elements are in bold
sb.append("<b>").append(arr[i]).append("</b>");
} else {
// other elements
sb.append(arr[i]);
}
sb.append(" ");
}
return sb.append("| ").append(counter).toString();
}
Output:
Pass: 09 10 8 7 6 5 4 3 2 1 | 09 8 10 7 6 5 4 3 2 1 | 19 8 7 10 6 5 4 3 2 1 | 29 8 7 6 10 5 4 3 2 1 | 39 8 7 6 5 10 4 3 2 1 | 49 8 7 6 5 4 10 3 2 1 | 59 8 7 6 5 4 3 10 2 1 | 69 8 7 6 5 4 3 2 10 1 | 79 8 7 6 5 4 3 2 1 10 | 8Pass: 18 9 7 6 5 4 3 2 1 10 | 98 7 9 6 5 4 3 2 1 10 | 108 7 6 9 5 4 3 2 1 10 | 118 7 6 5 9 4 3 2 1 10 | 128 7 6 5 4 9 3 2 1 10 | 138 7 6 5 4 3 9 2 1 10 | 148 7 6 5 4 3 2 9 1 10 | 158 7 6 5 4 3 2 1 9 10 | 16Pass: 27 8 6 5 4 3 2 1 9 10 | 177 6 8 5 4 3 2 1 9 10 | 187 6 5 8 4 3 2 1 9 10 | 197 6 5 4 8 3 2 1 9 10 | 207 6 5 4 3 8 2 1 9 10 | 217 6 5 4 3 2 8 1 9 10 | 227 6 5 4 3 2 1 8 9 10 | 23Pass: 36 7 5 4 3 2 1 8 9 10 | 246 5 7 4 3 2 1 8 9 10 | 256 5 4 7 3 2 1 8 9 10 | 266 5 4 3 7 2 1 8 9 10 | 276 5 4 3 2 7 1 8 9 10 | 286 5 4 3 2 1 7 8 9 10 | 29Pass: 45 6 4 3 2 1 7 8 9 10 | 305 4 6 3 2 1 7 8 9 10 | 315 4 3 6 2 1 7 8 9 10 | 325 4 3 2 6 1 7 8 9 10 | 335 4 3 2 1 6 7 8 9 10 | 34Pass: 54 5 3 2 1 6 7 8 9 10 | 354 3 5 2 1 6 7 8 9 10 | 364 3 2 5 1 6 7 8 9 10 | 374 3 2 1 5 6 7 8 9 10 | 38Pass: 63 4 2 1 5 6 7 8 9 10 | 393 2 4 1 5 6 7 8 9 10 | 403 2 1 4 5 6 7 8 9 10 | 41Pass: 72 3 1 4 5 6 7 8 9 10 | 422 1 3 4 5 6 7 8 9 10 | 43Pass: 81 2 3 4 5 6 7 8 9 10 | 44Pass: 9Total: Passes=10, swaps=45
See also: Bubble sort output is incorrect

How can I create a java program which makes numbers align-right side?

My purpose is a java app that takes a number from a user. Start 1 and write it to console. Each new line series will increase 1 until the number token from the user. The important thing is to align each line to the right side.
Scanner in = new Scanner(System.in);
int numberOfLines = in.nextInt();
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
System.out.printf(" %d",col);
}
System.out.println();
}
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
when reaching double-digit numbers it is not right-aligned text. I tried to use the if condition in the loop but I could not do it.
Here's a different way to think about it using String concatenation.
You could generate the last row, first, to determine the maximum width that each row must be. Then for each row, you count backwards from the current row number down to 1 so you know the width of just the numbers part. Finally, you prepend the number of spaces needed to make the current row as wide as the last row. Note that is a horribly inefficient use of Strings, but really I'm demonstrating a different algorithm. Making this memory efficient would just make it harder to understand. Also note that the output being rendered correctly is dependent upon the environment in which you are running, and how it displays long strings. Some systems will add a scrollbar, while others may cause the strings to wrap.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Number of rows? ");
int numberOfLines = in.nextInt();
if (numberOfLines >= 1) {
int totalWidth = 0;
// add up the widths of the numbers themselves
for (int number = 1; number <= numberOfLines; number++) {
totalWidth = totalWidth + ("" + number).length();
}
// add in the spaces in-between the numbers
totalWidth = totalWidth + (numberOfLines - 1);
// now generate each row by counting backwards from the current row number
for (int rowNumber = 1; rowNumber<=numberOfLines; rowNumber++) {
String row = "";
for (int i=rowNumber; i>=2; i--) {
row = row + i + " ";
}
row = row + "1";
// prepend the spaces in front to make it as wide as the last row
int paddingLength = totalWidth - row.length();
for(int i=1; i<=paddingLength; i++) {
row = " " + row;
}
// output the row
System.out.println(row);
}
}
else {
System.out.println("Number of rows must be positive!");
}
}
Sample output with 25 rows:
Number of rows? 25
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Your code is doing the job just fine. The one problem you have, is that it stops working properly once you get to numbers that are more than 1 digit large: In your example, the 10 and the 11.
It's actually kind of tricky to fix that - what if I input '120392'?
You have a few options. Each option is more amazing, but also requires more code.
Restrict your input. For example, disallow inputs beyond 99, and assume all numbers have a # of digits equal to the largest allowing numbers (so, 2 digits).
Calculate the # of digits in the input, then assume all numbers have the calculated # of digits.
Just get it right, with the spacing being applied increasing as numbers grow digits.
If you choose the first or second option, you'd get something like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
Note how this has way more spaces than your example (2 spaces in between e.g. every 4 and 3 instead of 1.
So, how? For #1 and #2, you need System.out.printf("%2d"); - this means: print a number, but if it takes fewer than 2 characters to do so, left-pad with spaces.
For #1 you hardcode the '2' (and hardcode a 99 limit; alternatively, hardcode 3 spaces, and a 999 limit). For #2 you get your input and then figure out how many digits that is. Something like String.valueOf(limit).length(); will do that, then you construct the format string using this length.
For #3 you track which number you're not printing in your System.out.print(" "); loop, so that you can still figure out how long the blank space you need to make has to be: If you're not printing a 10, you need 3 spaces. If you're not printing a 500, you'd need 4. If you're not printing a 5, you need 2.
For #2 and #3: printf("%4s", ""); prints 4 spaces. This is what you'd use to ask java to print X number of spaces. You're going to need this for solutions #2 and #3.
This sounds like first-week homework. I think #1 is most appropriate.
In order to make the 2 digits right aligned ,one of the ways would be- after the for loop of 'col' convert each digit to String then reverse it then after that print it . If u don't convert it to String then numbers like 10,20,30,etc would be printed as 1,2,3,etc
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
if(col>9){
COL=Integer.toString(col);
for(int i=COL.length();i>=0;i--)
rev=rev+COL.charAt(i);
System.out.printf(" %d",rev);
}
else
System.out.printf("%d",col);
}
System.out.println();
}

For-loop output explanation needed?

I need an explanation of how the output prints 9(S), 7(S), 5(S) and 3(S).
10 > 3 is correct and goes to y 1 <= 2 which is correct so 2 x 10 - 2 = 18 but the output prints 9. I don't understand the logic here. Why does it print 9(s) instead of 18(s)?
public class Q2{
public static void main(String args[]) {
int x,y;
for(x= 10; x > 3; x = x - 2) {
for(y = 1; y <= 2 * x - 2; y = y + 2)
System.out.print("S");
System.out.print("\n");
}
}
}
Its correct Y <= 18 , but you are incrementing Y by 2, so it gets printed 9 times.
To understand, write down on a piece of paper what the values of your variables will be.
First, write down the values of x:
x: 10 8 6 4
Next, write down the calculated upper boundary value for y, i.e. the result of expression 2 * x - 2:
x : 10 8 6 4
yMax: 18 14 10 6
Last, write down the values of y:
x : 10 8 6 4
yMax: 18 14 10 6
y : 1 1 1 1
3 3 3 3
5 5 5 5
7 7 7
9 9 9
11 11
13 13
15
17
Finally, count the number of y values for each x value, i.e. the number of times S is printed:
x : 10 8 6 4
count: 9 7 5 3
Then realize that the code would have been much easier to understand if it had just been written like this:
for (int count = 9; count >= 3; count -= 2) {
for (int i = 0; i < count; i++) {
System.out.println("S");
}
}
Of course, that wouldn't have taught you what they were trying to teach you, which is:
Conclusion: If you don't understand what the code is doing, follow the logic step by step, and write down what it is doing.

How can I space my triangle correctly?

I am trying to print out a Right Triangle that looks like this:
1
2 1
3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
The size of the triangle increases if the number in the method gets larger, which in this case is 11.
My code seems to only work up to 10 as after 10, my spacing is messed up.
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
I am trying to make it so that up to 99, the spacing is correct. What kind of edits should I do to my if statements or for loops in order to space it properly?
Code:
public class Patterns
{
public static void main(String[] args)
{
displayPattern(13);
//displayPattern(11,",");
}
public static void displayPattern(int n)
{
//print out n-1 spaces and the first number
//print n-2 spaces and the 2nd then first number
int counter = n;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= counter; j++)
{
if (n > 10)
{
if (i == n)
{
System.out.print("");
}
else if (i <= 10)
{
System.out.print(" ");
}
else
{
System.out.print(" ");
}
}
else if (n <=10)
{
if (i>9)
{
System.out.print(" ");
}
else
{
System.out.print(" ");
}
}
}
System.out.print(i + " ");
int tempValue = i - 1;
while(tempValue>0)
{
System.out.print(tempValue);
if(tempValue>1)
{
System.out.print(" ");
}
tempValue--;
}
if(tempValue==0)
{
System.out.print("\n");
}
counter--;
}
}
}

Palindrome Program using Recursion

This is currently what I have for my Palindrome program for my computer science class. I have it pretty much working, except whenever a word is a palindrome, it is an infinite loop. I know I have to insert a number base case, but I do not how to do that...I'm really having trouble understanding recursion. Help is appreciated.
public class PalindromeTester
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String str, another = "y";
int left, right;
while (another.equalsIgnoreCase("y"))
{
System.out.println("Enter a potential palindrome:");
str = scan.next();
left = 0;
right = str.length() - 1;
tester(str, left, right);
System.out.println();
System.out.println("Test another palindrome (y/n)?");
another = scan.next();
}
}
public static void tester (String str, int left, int right)
{
Scanner scan = new Scanner (System.in);
while (str.charAt(left) == str.charAt(right) && left < right)
{
System.out.println(str);
tester( str, left + 1, right -1);
}
if (left < right)
{
System.out.println("That string is NOT a palindrome.");
}
else
{
System.out.println("That string IS a palindrome.");
}
}
}
You are using a while loop. With recursion, this is done implicitly.
You have to split the algorithm in small parts.
[] represents left, {} represents right.
[1] 2 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 2 {1} -->Level 0
1 [2] 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 {2} 1 -->Level 1
1 2 [3] 4 5 6 7 8 9 0 9 8 7 6 5 4 {3} 2 1 -->Level 2
1 2 3 [4] 5 6 7 8 9 0 9 8 7 6 5 {4} 3 2 1 -->Level 3
1 2 3 4 [5] 6 7 8 9 0 9 8 7 6 {5} 4 3 2 1 -->Level 4
1 2 3 4 5 [6] 7 8 9 0 9 8 7 {6} 5 4 3 2 1 -->Level 5
1 2 3 4 5 6 [7] 8 9 0 9 8 {7} 6 5 4 3 2 1 -->Level 6
1 2 3 4 5 6 7 [8] 9 0 9 {8} 7 6 5 4 3 2 1 -->Level 7
1 2 3 4 5 6 7 8 [9] 0 {9} 8 7 6 5 4 3 2 1 -->Level 8
1 2 3 4 5 6 7 8 9 {[0]} 9 8 7 6 5 4 3 2 1 -->Level 9
So, tester will continue until:
We've reached the middle of the word.
The word is not a palindrome
Example of case 2:
[1] 2 3 A 5 6 7 8 9 0 9 8 7 6 5 4 3 2 {1}
1 [2] 3 A 5 6 7 8 9 0 9 8 7 6 5 4 3 {2} 1
1 2 [3] A 5 6 7 8 9 0 9 8 7 6 5 4 {3} 2 1
1 2 3 [A] 5 6 7 8 9 0 9 8 7 6 5 {4} 3 2 1 --> !!!
I thought this method would be very helpful for the understanding of how is this recursion working
public static String positions(String word, int l, int r) {
char[] a = word.toCharArray();
String s = "";
// [letter] if left, {} if right, [{}] if both
for (int i = 0; i < a.length; i++) {
if (l == i && r == i) {
s += "{[" + a[i] + "]}";
} else if (l == i) {
s += "[" + a[i] + "]";
} else if (r == i) {
s += "{" + a[i] + "}";
} else {
s += a[i];
}
s+=" ";
}
return s;
}
And finally, the tester method.
public static boolean tester(String str, int left, int right) {
System.out.println(positions(str, left, right) +" tester(str, "+left +", "+right+")");
if (left>=right) // case 1
return true; // that's ok, we've reached the middle
// the middle was not reached yet.
// is the condition satisfied?
if (str.charAt(left) == str.charAt(right)) {
// yes. So, lets do it again, with the parameters changed
return tester(str, left + 1, right - 1);
}
//the condition was not satisfied. Let's get out of here.
else {
return false;
}
}
Some outputs:
Enter a potential palindrome:
1234567890987654321
[1] 2 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 2 {1} tester(str, 0, 18)
1 [2] 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 {2} 1 tester(str, 1, 17)
1 2 [3] 4 5 6 7 8 9 0 9 8 7 6 5 4 {3} 2 1 tester(str, 2, 16)
1 2 3 [4] 5 6 7 8 9 0 9 8 7 6 5 {4} 3 2 1 tester(str, 3, 15)
1 2 3 4 [5] 6 7 8 9 0 9 8 7 6 {5} 4 3 2 1 tester(str, 4, 14)
1 2 3 4 5 [6] 7 8 9 0 9 8 7 {6} 5 4 3 2 1 tester(str, 5, 13)
1 2 3 4 5 6 [7] 8 9 0 9 8 {7} 6 5 4 3 2 1 tester(str, 6, 12)
1 2 3 4 5 6 7 [8] 9 0 9 {8} 7 6 5 4 3 2 1 tester(str, 7, 11)
1 2 3 4 5 6 7 8 [9] 0 {9} 8 7 6 5 4 3 2 1 tester(str, 8, 10)
1 2 3 4 5 6 7 8 9 {[0]} 9 8 7 6 5 4 3 2 1 tester(str, 9, 9)
true
Test another palindrome (y/n)?
y
Enter a potential palindrome:
12345A678654321
[1] 2 3 4 5 A 6 7 8 6 5 4 3 2 {1} tester(str, 0, 14)
1 [2] 3 4 5 A 6 7 8 6 5 4 3 {2} 1 tester(str, 1, 13)
1 2 [3] 4 5 A 6 7 8 6 5 4 {3} 2 1 tester(str, 2, 12)
1 2 3 [4] 5 A 6 7 8 6 5 {4} 3 2 1 tester(str, 3, 11)
1 2 3 4 [5] A 6 7 8 6 {5} 4 3 2 1 tester(str, 4, 10)
1 2 3 4 5 [A] 6 7 8 {6} 5 4 3 2 1 tester(str, 5, 9)
false
Test another palindrome (y/n)?
In the main method,
System.out.println(tester(str, left, right));
In order to see the true/false output
Since your are using recursion (in its basic purposes mostly used to eliminate loops), isn't your while loop inside the tester() method supposed to be an if?
public static void tester (String str, int left, int right)
{
Scanner scan = new Scanner (System.in);
if (str.charAt(left) == str.charAt(right) && left < right)
{
System.out.println(str);
tester( str, left + 1, right -1);
}
else if (left < right)
{
System.out.println("That string is NOT a palindrome.");
}
else
{
System.out.println("That string IS a palindrome.");
}
}
I modified your tester() method and replaced your while with an if and moved your second if clause.
public static void tester(String str, int left, int right) {
if (str.charAt(left) == str.charAt(right) && left < right) {
tester(str, left + 1, right - 1);
} else {
if (left < right) {
System.out.println("That string is NOT a palindrome.");
} else {
System.out.println("That string IS a palindrome.");
}
}
}

Categories