Java silently failing to print from array - java

I'm trying to convert an integer into an array of digits, then print those digits out in order. It's an early problem in Java: How to Program, and I'm confused as to why I can't make it work.
Here's my class:
public class AnyDigits {
private int[] ns;
public AnyDigits(int n){
this.ns = new int[String.valueOf(n).length()];
for(int i = 0, x = n; x > 0; i++, x = x / 10){
this.ns[i] = x % 10;
}
}
public void printDigits(){
for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
}
}
I have this code in my main method:
AnyDigits digitsTest = new AnyDigits(42339);
digitsTest.printDigits();
Any comments on the organisation, style and formatting of my code are also welcomed.
Any help gratefully received!

for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
This won't work, you are iterating while i==0, i will never be 0 at the first loop unless this.ns.length == 1.
You need
for(int i = this.ns.length - 1; i != 0; i--){
System.out.printf("%d ", this.ns[i]);
}
or
for(int i = this.ns.length - 1; i >= 0; i--){
System.out.printf("%d ", this.ns[i]);
}
Anyway, if you want to print an array, you can just do
System.out.println(Arrays.toString(yourArray));

Another way aside from BackSlash's answer-
private static int[] makeArrayFromInt(final int val){
String temp = String.valueOf(val);
int[] digits = new int[temp.length()];
for(int i = 0; i < temp.length(); i++){
digits[i] = Integer.parseInt(temp.substring(i, i + 1));
}
return digits;
}
Test:
int[] digits = makeArrayFromInt(12234);
for(int i = 0; i < digits.length; i++){
System.out.println(digits[i]);
}

Related

trouble implementing counting sort for strings

I get this error when I attempt to sort it based off the second char in the string but it runs
fine when I use the first char
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 8
at StringCountSort.countingSort(StringCountSort.java:27)
at StringCountSort.main(StringCountSort.java:38)
import java.util.Arrays;
public class StringCountSort{
public static void countingSort(String[] array, int size, int digit)
{
String[] result = new String[size+1];
int maximum = 122;
int[] count = new int[maximum + 1];
for (int i = 0; i < count.length; i++){
count[i] = 0;
}
for (int i = 0; i < size; i++){
count[array[i].charAt(digit)] +=1;
}
for (int i = 1; i < count.length; i++){
count[i] += count[i-1];
}
for (int i = size -1; i >= 0; i--){
result[count[array[i].charAt(digit)] - 1] = array[i];
count[array[i].charAt(0)]--;
}
for (int i = 0; i < size; i++) {
array[i] = result[i];
}
}
public static void main(String args[]){
String[] data = { "eg", "fa", "bz", "ch", "hv", "df", "ag" };
StringCountSort.countingSort(data, data.length, 1);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}
line 28 result[count[array[i].charAt(digit)] - 1] = array[i];
line 37 StringCountSort.countingSort(data, data.length, 1);
Change
count[array[i].charAt(0)]--;
to
count[array[i].charAt(digit)]--;
This should do the trick.
I also suggest the following improvements:
You don't need to pass the length of array as an argument.
You don't need to set every int of count to 0;
maximum should be Character.MAX_VALUE, to support every possible character.
The finished function could look like this:
public static void countingSort(String[] array, int digit) {
String[] result = new String[array.length];
int[] count = new int[Character.MAX_VALUE + 1];
for (int i = 0; i < array.length; i++){
count[array[i].charAt(digit)]++;
}
for (int i = 1; i < count.length; i++){
count[i] += count[i-1];
}
for (int i = array.length -1; i >= 0; i--){
result[count[array[i].charAt(digit)] - 1] = array[i];
count[array[i].charAt(digit)]--;
}
for (int i = 0; i < array.length; i++) {
array[i] = result[i];
}
}
Things that need to be changed are (if you want to sort the strings on the basis of first character)
count[array[i].charAt(digit)] +=1 to count[array[i].charAt(0)] +=1
result[count[array[i].charAt(digit)] - 1] = array[i]; count[array[i].charAt(0)]--; to result[--count[array[i].charAt(0)]] = array[i];
If you want to sort the string on the basis of the second character then simply change :
count[array[i].charAt(0)]--; to count[array[i].charAt(digit)]--;

Using Bubble Sort to Alphabetically Sort Array of Names in Java

I've been trying to tackle this bug for a while, but I can't get around to it. The purpose of the program below is to use bubble sort to alphabetically order an array of names. For example, if the names are ["Bob Joe", "Bob Frank", and "Bob Johnson"], the correctly sorted array would be ["Bob Frank", "Bob Joe", "Bob Johnson"].
The main challenge I am having is comparing any 2 strings past name.charAt(0). If I only compare the characters of any 2 strings at 1 specific index point, my code works. However, if I try to make the comparison move past index 0 if index 0 of both strings are equal to each other, my program no longer works.
The code is outlined below
public static void sortAlpha (String names[])
{
for (int i = 0 ; i < names.length - 1 ; i++)
{
for (int a = 0 ; a < names.length - 1 - i ; a++)
{
int length1 = names [a].length ();
int length2 = names [a + 1].length ();
int min = 1;
if (length1 > length2)
{
min = length2;
}
else
{
min = length1;
}
for (int b = 0 ; b < min ; b++)
{
if ((int) names [a].toLowerCase ().charAt (b) > (int) names [a + 1].toLowerCase ().charAt (b))
{
String tempName = names [a];
// sort:
names [a] = names [a + 1];
names [a + 1] = tempName;
break;
}
}
}
}
}
If I simply default the min value to 1, the code runs and does its intended job. However, if the min value stays dynamic, the program does not work. I'm trying to discern why this is so and what the fix is. Any help would be appreciated!
Check this out.
public static void sortAlpha(String names[]) {
for (int i = 0; i < names.length - 1; i++) {
for (int a = 0; a < names.length - 1 - i; a++) {
int lengthLeft = names[a].length();
int lengthRight = names[a + 1].length();
int minLength = lengthLeft > lengthRight ? lengthRight : lengthLeft;
for (int b = 0; b < minLength; b++) {
int letterLeft = (int) names[a].toLowerCase().charAt(b);
int letterRight = (int) names[a + 1].toLowerCase().charAt(b);
if (letterLeft > letterRight) {
String tempName = names[a];
// sort:
names[a] = names[a + 1];
names[a + 1] = tempName;
break;
} else if (letterLeft == letterRight) {
// if the letters are the same go for the next letters
continue;
} else {
// if it's already in the right position - stop.
break;
}
}
}
}
}
Use this
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
You can simply use compareTo() and a temp variable to compare and store
Scanner sc = new Scanner(System.in);
String n[]= new String[5];
System.out.println("Enter the String");
for(int k = 0;k<5;k++) {
n[k] = sc.nextLine();
}
String temp;
System.out.println("sorted order:");
for (int j = 0; j < n.length; j++) {
for (int i = j + 1; i < n.length; i++) {
if (n[i].compareTo(n[j]) < 0) {
temp = n[j];
n[j] = n[i];
n[i] = temp;
}
}
System.out.println(n[j]);

ArrayIndexOutOfBoundsException Java Issue

So I have been working on this problem for a while now. I keep getting an ArrayIndexOutOfBoundsException but I am unable to locate where the issue lies. If someone could point me in the right direction, I would really appreciate it! Thanks!
public class Answer {
public static void main(String[] args){
double[] y = {23, 11.1, 50.4};
double[] x = {22.2, 46, 100.0};
Answer answer = new Answer();
answer.answer(y, x);
}
public static int answer(double[] y, double[] x) {
int result = 0;
double percent_1, percent_2;
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
// Calculate percent of first 2 x value array items with y
// all y values. Store the results in a seperate list.
for(int i = 0; i < x.length; i++){
percent_1 = compare(y[i], x[0]);
percent_2 = compare(y[i], x[1]);
compareList_1[i] = percent_1;
compareList_2[i] = percent_2;
}
// Compare those lists to find common number
// There you have your answer.
result = (int)compareLists(compareList_1, compareList_2);
return result;
}
// Calculates percentage from x and y values
public static double compare(double y, double x){
double result = 1 - (y/x);
return result;
}
// Finds common value in lists
public static double compareLists(double[] list_1, double[] list_2){
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
if(list_1[i] == list_2[j]){
return list_1[i];
}
}
}
// Just cus this shouldn't ever return.
return 100;
}
}
In your iteration (compareLists), you should use 'length' (not length + 1)
for(int i = 0; i < list_1.length; i++)
for(int j = 0; j < list_2.length; i++)
I think the problerm is in
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
i < list_1.length + 1 or j < list_2.length + 1 change it to
for(int i = 0; i < list_1.length; i++){
for(int j = 0; j < list_2.length ; j++){
remove +1 from each condition.For j < list_2.length + 1 the list_2.length will give you length of array ie lastIndex +1 and you are adding another +1 in it causing loop condition to be j<lastIndex +1 giving you index error on the last iteration of loop in the line if(list_1[i] == list_2[j]){ for list_2[j]
Also in answer method you declare array by
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
and in the loop you are iterating upto x.length if x.length is greater than y.length the you can get the Index error in compareList_2[i] = percent_2;(inside the loop) because its length is y.length.

Printing a triangle in Java

I'm practicing basic coding exercises and trying to print the following triangle in Java:
*
***
*****
***
*
The following code gives me the results but I feel like there must be a much more elegant solution
for (int i = 1; i <= 5; i++) {
if (i % 2 == 1) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
for (int i = 3; i > 0; i--) {
if (i % 2 == 1) {
for (int j = 1; j < i + 1; j++) {
System.out.print("*");
}
System.out.println("");
}
}
Can anyone provide some insight into how to make this work in a better way?
Ok, here's some more code that produces the correct result that uses just the two for loops, but it looks even uglier:
for (int i = 1; i <= 10; i += 2) {
if (i <= 5) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
else if(i > 5 && i < 8){
for(int j = i/2; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
else{
for(int j = 1; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
}
First, you are skipping each 2nd iteration of the loop because you want to increase two steps at once. You can do this by changing the "i++" in your loop to "i += 2" and "i--" to "i -= 2", that will have the same effect and allows you to remove the if inside both loops.
Another improvement would be using a single outer loop and figuring out whether the inner loop should be increasing or decreasing the amount of asterisks. Maybe you can come up with an equation that gives you the amount of asterisks based on the value of i? (I didn't want to solve it completely so you have some exercise left, just comment if you want a full solution)
Updated with a solution that might be considered elegant as you can change the height of the triangle and there is no repetition:
int height = 5;
for (int i = 1; i <= 2 * height; i += 2) {
int numAsterisks;
if (i <= height) {
numAsterisks = i;
} else {
numAsterisks = 2 * height - i;
}
for (int j = 0; j < numAsterisks; j++) {
System.out.print("*");
}
System.out.println();
}
What about the following?
public void printTriangle(int size) {
int half = size / 2;
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
char[] a = new char[stars];
Arrays.fill(a, '*');
System.out.println(new String(a));
}
}
Or just a bit more optimized:
public void printTriangle(int size) {
int half = size / 2;
char[] a = new char[size];
Arrays.fill(a, '*');
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
System.out.println(new String(a, 0, stars));
}
}
for(int i = 0; i < 7; i++) {
for(int j = 0; j < i; j++) {
print("*");
}
print("\n");
}
This can be another solution to print a regular right triangle...
Here's a different way of looking at the problem. By using an integer array, I can solve lots of shape drawing problems by changing the values in the array.
When solving more difficult problems, you would use model classes instead of simple integers. The idea, however, is the same.
Here's the output.
*
***
*****
***
*
And here's the code:
public class Triangle {
public static void main(String[] args) {
int[] heights = {1, 3, 5, 3, 1};
for (int i = 0; i < heights.length; i++) {
for (int j = 0; j < heights[i]; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
How about...
int width = 5;
for (int i = 1; i <= width; i+=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
for (int i = width-2; i > 0; i-=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
Or, even better yet...
int width = 7;
double half = width / 2
for (int i = 0; i < width; i++){
System.out.println(String.format("%"+((i < half ? i : (width-i-1))*2+1)+"s", "").replaceAll(" ", "*"));
}
Gives
*
***
*****
***
*

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories