I am developing a simple program to print seat numbers, where the row are numbered from 1-5 and columns from a-e. the code i am using is as follows
public class JavaApplication5 {
public static void main(String[] args) {
int j =1,k;
int i;
char c;
String[] arr = new String[25];
for( i = 0;i < arr.length;i++)
{
while(j <= 5)
{
for(k = 97;k < 102; k++)
{
c = ((char)k);
arr[i] = j + "" + c;
System.out.println(arr[i]);
}
j++;
}
}
}
}
this displays desired result. but when I print an element outside the for loop I get the result as null like below
public static void main(String[] args) {
int j =1,k;
int i;
char c;
String[] arr = new String[25];
for( i = 0;i < arr.length;i++)
{
while(j <= 5)
{
for(k = 97;k < 102; k++)
{
c = ((char)k);
arr[i] = j + "" + c;
}
j++;
}
}
System.out.println(arr[6]);
}
how to solve this?
this will leave all elements as null
String[] arr = new String[25];
this will iterate until j == 5 so only until arr[5]
while(j <= 5) {
j++;
}
Therefore arr[6] is still null
Change
arr[j] = j + "" + c;
instead of
arr[i] = j + "" + c;
Now it works.
public static void main(String[] args) {
int j = 1, k;
int i;
char c;
String[] arr = new String[25];
for (i = 0; i < arr.length; i++) {
while (j <= 5) {
for (k = 97; k < 102; k++) {
c = ((char) k);
arr[j] = j + "" + c;
}
j++;
}
}
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
System.out.println(arr[4]);
System.out.println(arr[5]);
System.out.println(arr[6]); // null because your check j <= 5 in while loop
}
You can access the array elements normally outside of the loop. In your example, arr[6] is just null. The fault is not in the way you access it. (Although i cant see the bug yet ;))
The problem in your code is that you simply write 5 time on index 1, then 5 time on index 2 and so on.
So you never wrote on index 6.
Your code should be changed to code below:
String[] arr = new String[25];
int i = 0;
int j = 1;
while (j <= 5) {
for (k = 97; k < 102; k++) {
c = ((char) k);
arr[i++] = j + "" + c;
}
j++;
}
System.out.println(arr[6]);
Because your loops run 5*5 times, then your i index will never pass arr array length.
But you better control it like this to prevent your code from being error prone:
if(i < arr.length) {
arr[i++] = j + "" + c;
} else {
break;
}
Related
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]);
This method is supposed to sort the words from a given file in alphabetical order after it is selected. Everything is working except it doesn't properly sort it. The input file reads "kundu is a man kundu man", but no matter what I try I get "[is, kundu, a, man, kundu, man]".
I tried taking away the "-1" and the "+1" but that did nothing to help.
private String[] selectionSort(String[] stringArray)
{
for(int j = 0; j < stringArray.length - 1; j++)
{
int min = j;
for(int k = j + 1; k < stringArray.length; k++)
{
if(stringArray[k].compareTo(stringArray[min]) < 0)
min = k;
swap(stringArray, j, min); //this method swaps the words
// by using a temp
//swap(intArray, j, min);
}
}
return stringArray;
}
private void swap(String [] stringArray, int i, int j) //swap method
{
String temp = stringArray[i];
stringArray[i] = stringArray [j];
stringArray[j] = temp;
}
Your swap call should be after the inner loop. Like,
private String[] selectionSort(String[] stringArray) {
for (int j = 0; j < stringArray.length - 1; j++) {
int min = j;
for (int k = j + 1; k < stringArray.length; k++) {
if (stringArray[k].compareTo(stringArray[min]) < 0) {
min = k;
}
}
swap(stringArray, j, min);
}
return stringArray;
}
After that, with no other changes and your input, I get
[a, is, kundu, kundu, man, man]
I'm trying to make a program that will format text entered so that each line is set to a specific Length and cant go over e.g. 20 and then have the characters format accordingly on each line and have "." pad the gaps to make up the set length.
This is the output I've got so far:
This.is..an..example
of..text..that..will
have..straight..left
and.right....margins
after formatting ...
For some reason the "." are not appearing between after and formatting as well as after the "g" a dot is missing a space is taking its place instead. It seems to always happen's on the last line.
This is what the output should look like:
This.is..an..example
of..text..that..will
have..straight..left
and.right....margins
after.formatting....
Code:
import java.util.*;
public class FormattedPadding {
public static ArrayList<String> fullJustify(ArrayList<String> a, int b) {
ArrayList<String> result = new ArrayList<String>();
if(a == null || a.size() == 0)
return result;
int i = 0;
int currentLength = 0;
String temp = "";
for(i = 0; i < a.size(); i++){
currentLength += a.get(i).length() + 1;
if(currentLength > b + 1) {
result.add(temp);
temp = "";
currentLength = 0;
i--;
//System.out.println("Intermediate result: " + result);
}
else
temp += a.get(i) + " ";
}
if(!temp.equals(""))
result.add(temp);
for(i = 0; i < result.size() - 1; i++){
temp = result.get(i);
String[] tempArray = temp.split(" ");
int totalLength = 0;
for(int j =0; j < tempArray.length; j++)
totalLength += tempArray[j].length();
int[] spaceCount = getSpaceCount(b-totalLength, tempArray.length);
for(int l =0; l < spaceCount.length; l++)
System.out.print(spaceCount[l] + " " );
System.out.println();
temp = "";
for(int j = 0; j < tempArray.length; j++){
temp += tempArray[j];
for(int k = 0; k < spaceCount[j]; k++)
temp += ".";
}
result.set(i, temp);
}
temp = result.get(result.size() - 1);
if(temp.length() < b){
while(temp.length() < b)
temp += ".";
}
else if(temp.length() > b)
temp = temp.substring(0, b);
result.set(result.size() - 1, temp);
return result;
}
public static int[] getSpaceCount(int freeSpace, int numOfStrings) {
int size = numOfStrings - 1;
int[] ret = new int[size + 1];
if(size == 0){
ret[0] = freeSpace;
}
else {
for(int i =0; i < ret.length; i++) {
if(size != 0){
ret[i] = freeSpace % size == 0 ? freeSpace/size : freeSpace/(size + 1);
}
freeSpace = freeSpace - ret[i];
size--;
}
}
return ret;
}
public static void main(String[] args) {
//ArrayList<String> a = new ArrayList<String>();
System.out.println("#Enter ");
String usrInput = BIO.getString();
String[] items = usrInput.split("\\s+"); // Split where whitespace is encounterd using the RegEx
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(items));
// ^Split input into ArrayList
int b = 20; // Line length
ArrayList<String> result = fullJustify(newList, b);
for(int i =0; i < result.size(); i++) {
System.out.println(result.get(i));
}
System.out.println(result);
}
}
First of all, I think your code will go to infinite loop if any of the words has length more than "b"
About the issue, you create different logic for the last line
temp = result.get(result.size() - 1);
if(temp.length() < b){
while(temp.length() < b)
temp += ".";
}
else if(temp.length() > b)
temp = temp.substring(0, b);
result.set(result.size() - 1, temp);
You can remote those part, and change the loop from result.size()-1 to result.size(), so it will cover all lines:
for(i = 0; i < result.size(); i++){
I got homework "Take two given array(already sorted up, for example {1,2,3}) and create a new array contains both arrays and then sort him up", we have a function to sort up arrays so it's not the problem, however it gets a little bit complex to me, here is my code:
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int[] a = new int[3];
int[] b = new int[5];
Help_arr.scan(a);
Help_arr.scan(b);
Help_arr.print(peula(a, b));
}
public static int[] peula(int[] a1, int[] b1) {
int[] c = new int[a1.length + b1.length];
for (int i = 0; i < a1.length; i++)
c[i] = a1[i];
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
}
Help_arr.sortup(c);
return c;
}
Functions used from Help_arr class:
1) Scan an array:
public static void scan(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter number" + (i + 1));
arr1[i] = in.nextInt();
}
}
2) Print an array:
public static void print(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
}
3) Sort up an array:
public static void sortup(int[] arr1) {
int i, mini, temp, j;
for (j = 0; j < arr1.length; j++) {
mini = j;
for (i = j; i < arr1.length; i++) {
if (arr1[i] < arr1[mini])
mini = i;
}
temp = arr1[j];
arr1[j] = arr1[mini];
arr1[mini] = temp;
}
}
I get an error in the line c[i]=b1[i]; the array is going out of index bounds but I followed the code and this for will run until i=7 as the c.length is 8 and it is possible. But maybe I am missing something, here is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at arrays.PgRonTargilMivhan.peula(PgRonTargilMivhan.java:21)
at arrays.PgRonTargilMivhan.main(PgRonTargilMivhan.java:13)
The issue is with this code:
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
here b1 index should start with 0 but you are starting with a1.length. You should have a separate index for b1 or use b1[i-a1.length].
Please find the logic ..
you were using 'i' index for array b is the problem.
Solution is below. Good luck
int[] c = new int[a.length + b.length];
int i = 0;
for (i = 0; i < a.length; i++)
c[i] = a[i];
for (int j = 0; j < b.length; j++)
c[i] = b[j];
}
I have been trying to figure out how to properly print the return of my method.
When the program prints the return of my method, I am giving a nullPointerException error on line 45(the line where i am trying to print the method).
*I did try to make the return to the method static so it is accessible.
How do I initialize the "answer" variable so that i can print it outside of my method?
Thank you in advance
import javax.swing.JOptionPane;
public class ListSortMerge {
static int[]answer;
public static void main(String[] args) {
int v1 = 0, v2 = 0;
for(int c = 0; c <= 1; c++) {
String values = JOptionPane.showInputDialog("How many values would you like to store in list "+(c+1)+"?");
if (c==0) {
v1 = Integer.parseInt(values);
}
else{
v2 = Integer.parseInt(values);
}
}
int[] numbers1 = new int[v1];
int[] numbers2 = new int[v2];
merge(numbers1,numbers2);
int i;
System.out.println("\nList 1 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v1); i++) {
System.out.println(numbers1[i]);
}
System.out.println("\nList 2 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v2); i++) {
System.out.println(numbers2[i]);
}
System.out.println("\nList after the sort");
System.out.println("--------------------");
for(i = 0; i < (v1+v2); i++) {
System.out.println(answer[i]);
}
}
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
for(int c = 0; c < (a.length); c++)
{
String aVal1 = JOptionPane.showInputDialog("Input list 1 value " +(c+1));
a[c] = Integer.parseInt(aVal1);
}
for ( int c = 0; c < (b.length); c++){
String aVal2 = JOptionPane.showInputDialog("Input list 2 value " +(c + 1));
b[c] = Integer.parseInt(aVal2);
}
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
answer[k++] = a[i++];
else
answer[k++] = b[j++];
}
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
}
You have two different answer variables: one is a local variable in the merge function and another is a static field in the class. You never initialize the second one.