Java String Insertion Sort Not Working As Desired - java

My objective is to create a working insertion sort that can handle strings and integers using the array given to us in the main method. For this example I called it list.
public class insort{
public static void main(String[]list){
sort(list);
printsort(list);
}//main
public static void sort(String[]list){
for (int index = 1; index < list.length; index++){
int key = list[index];
int position = index;
while (position > 0 && key.compareTo(list[position-1]) < 0){
list[position] = list[position-1];
position--;
}//while
list[position] = key;
}//for
}//sort
public static void printsort(String[]list){
while ( i < list.length){
System.out.print(i);
}//while
}//printsort
}//insort

Some of the things to note for successful compilation:
The 'i' in the 'printsort' method is not declared and initialized. You will need to something like int i=0 before you start the while loop.
Also the while loop variable needs to be updated inside the loop so as to meet an end condition. The end condition will help you stop the loop from going into an infinite loop. So you will need an i++ after your System.out.print().
In the System.out.print() you are passing the variable i which will print the numbers from 0 to length-1 instead of the Strings in your list array. So you will need something like System.out.print(list[i]).
In the 'sort' method you have int key = list[index], the RHS will return a String object instead of an int that you have on the LHS. So String key = list[index] is what you need there.
I haven't checked the code for proper working of insertion sort. Just pointed out some syntactic mistakes that will help you compile the code.
All the best :)

You mixed couple things. It would be much easier to sort int or Integer objects, than String objects (especially that you need to be sure that String[] list contains only numerics), however if you want to sort String objects you need to change couple things:
you try to assign a reference to String object to primitive variable
int:
int key = list[index];
You can change it for example to:
int key = Integer.valueOf(list[index]);
or change list from String[] to int[].
you try to use compareTo() method on primitive variable int:
int key = list[index];
(key.compareTo(list[position-1])) < 0
Primitive variables doesn't have methods. You can solve the 1 and 2
problems with usage of Integer object instead of int variable:
Integer key = Integer.valueOf(list[index]);
or, if you want to stay with int variables, try with:
key < list[position-1]
instead of:
(key.compareTo(list[position-1])) < 0
your while loop is wrong:
while ( i < list.length){
System.out.print(i);
}//while
try with:
for(String element : list){
System.out.println(element);
}
to print every element of list.
also you changed a main method, from main(String[] args) to main(String[] list), and you try to use sort on String[] list. You should create new String[] array, and try with it, for example:
String[] list = {"4","6","1","8"};
sort(list);

Related

int cannot be converted to int []

new to programming here and i keep getting the error message, incompatible types, int cannot be converted to int [], the question is to add R1 & R2 together if they are of equal lengths and if not, print a message that says 'the arrays must be same length', if that matters, not sure where im going wrong, any help would be greatly appreciated
public int[] arrayAdd(int[] R1, int[] R2)
{
int[] sumArray= new int[R1.length];
if( R1.length!= R2.length)
{
System.out.println("The arrays must be same length");
}
else
{
for(int i=0; i< R1.length; i++)
for (int j=0; j<R2.length; j++)
{
sumArray= R1[i]+ R2[j]; // Error
}
}
return sumArray;
}
not sure where im going wrong
You are attempting to assign an int to a variable whose type is int[].
That is not legal ... and it doesn't make sense.
This:
sumArray= R1[i]+ R2[j];
should be this
sumArray[something_or_other] = R1[i] + R2[j];
... except that you have a bunch of other errors which mean that a simple "point fix" won't be correct.
Hint: you do not need nested loops to add the elements of two arrays.
sumArray[i]= R1[i]+ R2[j]; // updated line
you need to assign to an array element, but you were doing it wrong.
Your code is broken in many several ways, at least:
You declared returning an array but what is the value of it when inputs are of the wrong size? Manage such errors in better ways (stop, throw exception, return error code, etc). At least never display something at this place, this is not the place were you have to tackle the error, this is the place here you detect it, just report it to caller(s).
You (tried to) created space for the returned value but how could this be if conditions for having a return value is not met?
You used Java syntax to declare an array, int []sumArray should be `int sumArray[0].
You can't dynamically allocate an array like this, to capture a dynamic allocation you must use a pointer, an array is not a pointer. But a pointer can be set to the memory address of an allocated array, like int *sumArray = new int[10]
sumArray is an array so to set an element of it use sumArray[index] = ...
So this may be better:
public int *arrayAdd(int[] R1, int[] R2) {
if( R1.length!= R2.length) {
return nullptr;
}
int *sumArray= new int[R1.length];
for(int i=0; i< R1.length; i++) {
sumArray[i] = R1[i]+ R2[i];
}
return sumArray;
}
After question editing
If you want to sum two arrays, element by element, then a single loop is sufficient...
Actually in that line sumArray is an integer array and you are assigning it as integer only and also you haven't declared variable j.
Try this-
public int[] arrayAdd(int[] R1, int[] R2)
{
int[] sumArray= new int[R1.length];
if( R1.length!= R2.length)
{
System.out.println("The arrays must be same length");
}
else
{
for(int i=0; i< R1.length; i++)
{
sumArray[i]= R1[i]+ R2[i]; // Error
}
}
return sumArray;
}

Sorting two dimensional String array as per LastName then on FirstName without using any API

Hi all I am very new for the Java. I would like to sort below array of strings as per LastName then on FirstName without use of any API i.e. I am not supposed to use Arrays.sort() , compareTo(), equals() etc..
Input array String
String [][]name={{"Jen","Eric"},
{"Brain","Adams"},
{"Jon","Methew"},
{"Antino","Ronald"},
{"Cris","Ronald"}
};
my out put should be like.
Brain,Adams
Jen,Eric
Jon,Methew
Antino,Ronald
Cris,Ronald
Please Help.
public class StringArraySort {
public static void main(String[] args) {
//System.out.println(str.length);
String [][]name={{"Jen","Eric"},
{"Brain","Adams"},
{"Jon","Methew"},
{"Antino","Ronald"},
{"Cris","Ronald"}
};
String []str1= new String [name.length];
String []str2= new String [name.length];
for(int i=1;i<name.length;i++)
{
int j=i;
str1[i]=name[i][j];
str2[i]=name[i-1][j];
//System.out.println(str1[i]+" "+str2[i]);
}
/*for(String tmp:name)
{
char a[] = new char[tmp.length()] ;
//System.out.println(tmp);
for(int i=0;i<tmp.length();i++)
{
a[i]=tmp.charAt(i);
System.out.println(a[i]);
}
}*/
}
}
I will not give you any code, as this is clearly an assignment, but here's some general guidance:
Don't try to put everything into main. You may not be allowed to use any exiting API, but you can define your own! Write your own compare and sort methods.
Start with a method compare(String, String) -> int, or isSmaller(String, String) -> boolean. Use String.toCharArray to get the individual characters and compare them, in pairs from both strings. Make sure to handle the case of the strings having different lengths.
Now write a method compare(String[], String[]) -> int. This can look very similar to the above (in fact, you could make a generic one for both), but it might be simpler to make this one specific for the "lastname-firstname" case, particularly since here you want to sort by the second element first.
Finally, write your own sort method. An in-place bubble sort should be the easiest and the algorithm can easily be found on the internet. Other sort algorithms are faster, but if speed is an issue, the requirement not to use any API is nonsensical in the first place. If you want to score bonus-points, though, you can try to implement an in-place quick sort, but only after you've got it running with the bubble sort.
Also, you should test each of those methods individually. Don't try to run your sort method before you've made sure your compare methods actually work. Call them individually with different outputs and see whether they yield the correct result.
public class NameSort {
public static void main(String[] args) {
String [][] names={{"Jen","Eric"},
{"Brain","Adams"},
{"Jon","Methew"},
{"Antino","Ronald"},
{"Cris","Ronald"}
};
for(int m=0;m<names.length;m++)
{
for(int n=m+1;n<names.length;n++)
{
if(myCompare(names[m][1],names[n][1])==1)
{
swap(names, names[m], names[n], m, n);
}
else if (myCompare(names[m][1],names[n][1])==0)
{
if(myCompare(names[m][0],names[n][0])==1)
{
swap(names, names[m], names[n], m, n);
}
}
}
}
for (int i=0;i<names.length;i++)
{
System.out.println(names[i][0]+" " +names[i][1] );
}
}
public static void swap(String [][] names,String[] a,String[] b,int m,int n)
{
names[n]=a;
names[m]=b;
}
public static int myCompare(String a, String b)
{
int minLength= a.length()<b.length()?a.length():b.length();
for(int i=0;i<minLength;i++)
{
if(a.charAt(i)>b.charAt(i))
{
return 1;
}
else if(a.charAt(i)<b.charAt(i)){
return -1;
}
}
if(a.length()>minLength)
return 1;
else if (b.length()> minLength )
return -1;
else
return 0;
}
}
In order to let you learn at least something, I am going to give you the answer in psuedo-code and let you do the coding. The solution is based on bubble sort and comparing names (=Strings) by looping on their characters
in bubble sort we iterate over the array, in each iteration, we compare two adjacent cells and possibly swap them so that they are in the correct order.
at the end of the 1st iteration, the biggest cell will be in the correct position (=last). so we start another iteration but skip the last cell. by the end of the 2nd iteration, the 2nd biggest cell will in its correct position. we cotinue iterating, each time going over one less cell until there are no more cells to iterate over.
I give you the comparing method:
The solution assumes you are allowed to call length() and charAt() methods of String class.
/**
* returns negative, zero or positive value
* if s1 is smaller, equal or bigger than s2, respectively
* comparison is lexicographical
*/
static int compareStrings(String s1, String s2)
{
int i = 0;
for (i = 0; i < s1.length() && i < s2.length(); i++) {
int diff = s1.charAt(i) - s2.charAt(i);
if (diff != 0) return diff;
}
if (i == s1.length()) {
if (i == s2.length()) return 0; // equal lengths
else return 1; // exhausted s2 before s1
}
return -1; // exhausted s1 before s2
}
seeing the loop in your code, I think one last note is in order: you should be aware that arrays in Java start with index 0 and the last cell is at length-1.

Array in Method Header: error ']' expected (Java)

I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!

Sorting a randomized array in Java

I am trying to make an app for sorting a randomized array
I made some code and I can not see what is wrong with it that it returns wrong values
Notes: I am trying to learn programming. So don't suggest whole different ways of solving the problem. I just want to see what is wrong with this code so I can get better.
What RandomArrayCreator.create() returns is just an array of numbers in randomized order.
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j]) j=k;
}
siralanmish[i]=siyahi[j];
siyahi[j]=siyahi.length+1;
}
System.out.println(siralanmish[i]);
}
}
}
I know you did not want suggestions but I'm going to offer one anyway.
Hopefully this will help guide you along the way, but still allow you to come up with your own solution.
Sort smallest to biggest.
did I have swap an element?
while I swapped an element
assume I did not swap an element
for element i in the array
is i > i+1?
if yes
swap the elements
I did swap an element
else
do nothing
Given that you mentioned you wanted to learn how to improve your current program, here are minimalist changes that will have your code produce a sorted array.
A few notes on the changes:
1.
if (siyahi[k]<siyahi[j]) j=k;
This I assume is for trying to swap the values at each indexes. Instead you are assigning the value of k to j which will cause problems with the entire for loop. I replaced this with the following:
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
This creates a temporary variable to store one of the values so that you can swap the value at each index without losing one of your values.
2.
siralanmish[i]=siyahi[j];
This was replaced with:
siralanmish[j]=siyahi[j];
This allows you to directly copy the values from the same index from the source array to the target array.
3.
siyahi[j]=siyahi.length+1;
This code will just fill up your array with the value of length+1 for your original array and you will lose your other values.
Your code with the fixes are below:
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
}
siralanmish[j]=siyahi[j];
}
System.out.println(siralanmish[i]);
}
}

Is there anything wrong in these two methods that copy & returns an array

Is there anything wrong in these two methods that copy & returns an array?
This is how i called it :
o2[i].addArr(o1.getArr());
And at the end the result is that o2[i].getArr(); is empty. I don't know why but this is my code if you could help me
NOTE: The class Array i wrote it here Array while it's another class name in my code. just to make it clear for you
public Array[] getArr(){ //first method
int count=0;
for(int i=0;i<10;i++){
if(Arrlist[i]!=null)
count++;}
Array[] arr=new Array[count];
for(int i=0;i<count;i++)
arr[i]=Arrlist[i];
return arr;}
public void addArr(Array[]arr){ //second method
for(int i=0;i<arr.length;i++)
Arrlist[i]=arr[i];
}
Yes. In getArr, you're going to overrun the length of the array you're creating if you have any null entries in the array you're copying.
In the loop where you're actually copying, you need separate variables for the index into arr and the index into Arrlist, because you need to skip nulls.
E.g., along these lines (untested):
int i, j;
j = 0;
for (i = 0; i < Arrlist.length; ++i) {
if (Arrlist[i] != null) {
arr[j++] = Arrlist[i];
}
}
addArr is okay if (and it's a big "if") Arrlist is allocated and it's the same size as arr. (You could replace it with System.arraycopy.) Note that the name is misleading, though; you're overwriting Arrlist, not adding to it. And again, those are some pretty big "if"s.

Categories