I have no idea how to get my new list to print
import java.util.ArrayList;
import java.util.List;
public class InsertionSort {
public static int insertion(List<String> sorted) {
sorted = new ArrayList<String>();
String list[] = {"Banana","Pear","Apple","Peach","Orange"};
String temp="";
int f = list.length;
for(int i=0;i<f;i++){
for(int j=i+1;j<f;j++){
if(list[i].compareToIgnoreCase(list[j])>0){
temp = list[i];
list[i]=list[j];
list[j]=temp;
}
}
}
System.out.print(list);
return list[].InsertionSort;
I keep getting this error for the line above
1 error found:
InsertionSort.java [line: 22]
Error: class expected
}
}
You want to use the for-each loop, it will look like so :
for ( String i : list){
System.out.print(i);
}
You can't print out the array like you did here:
System.out.print(list); // DOES NOT WORK
Because println takes in a variety of parameters, but not an array( although one version takes an array of chars ). See the API
But if you said,...
System.out.print(list[1]);
for example, it would compile..
You have other issues to fix though..
return list[].InsertionSort //what's mean is code?
if you want to print list you can like this:
for(String str:list) //this list is list<String>
{
System.out.println(str);
}
Related
I am working on the first part of a String permutation problem and I am just looping over the first char of a string and swap it with every following char of that same String. I initialized an empty ArrayList to store all of those permutations called listeFinale. When I am printing that ArrayList, I am getting a collection of object and not values ([[C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba]), how can I print each char stored in the ArrayList?
import java.util.ArrayList;
import java.util.List;
public class checkPermu {
public static void main(String[] args) {
String myString = "aabc";
applyPermu(myString);
}
public static void applyPermu(String toCheck){
char[] newString = toCheck.toCharArray();
List listeFinale = new ArrayList();
for(int i = 0 ; i < newString.length ; i ++){
char temp = newString[0];
newString[0] = newString[i];
newString[i] = temp;
listeFinale.add(newString);
System.out.println(listeFinale);
}
}
}
First of all, don't use raw types for your List please.. Change:
List listeFinale = new ArrayList();
to:
List<char[]> listeFinale = new ArrayList<>();
As for your actual problem. Those values you see are the default toString() outputs of your inner character-arrays. You could iterate over your list, and call the java.util.Arrays.toString(char[]) method for them like this:
listeFinale.forEach(arr -> System.out.println(Arrays.toString(arr)));
Or, if you want to print them back as String again, use new String(char[]):
listeFinale.forEach(arr -> System.out.println(new String(arr)));
Try it online.
I wrote a program that asks users to input names into an array and then the names are sorted in alphabetical order...The program works good but I was wondering if I could sort each of the names entered by the 2nd, 3rd, or 4th character in each string? For example, if the user entered Bob, Dan, and Kris the program should sort them as Dan, Bob, Kris. This is my program that sorts my array of strings by the first letter of the string:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SortingAnArrayOfStrings {
public static void main(String[] args) {
{
//Ask the user for names to add to the array
List<String> list=new ArrayList<String>();
Scanner in=new Scanner(System.in);
do {
System.out.println(" The names on the list are "+list);
System.out.println("Would you like to add another name to the list? (y/n)");
if (in.next().startsWith("y")) {
System.out.println("Enter:");
list.add(in.next());
}else{break;
}
} while (true);
//display the names that have been added to the array
System.out.println("The names on the list are "+list);
//sort the array of names in alphabetical order
String[] Arr=list.toArray(new String[list.size()]);
String[] stringArray=new String[Arr.length];
for(int i=0;i<Arr.length;i++)
{
for (int j = i+1; j < Arr.length; j++) {
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
String temp=Arr[j];
Arr[j]=Arr[i];
Arr[i]=temp;
}
}
stringArray[i]=Arr[i];
}
//display the sorted list of names
System.out.println("This is the list of names after sorting them in alphabetical order : ");
for(String ss:stringArray){
System.out.print(ss + " ");
}
}
}
}
You could try something like bellow using a custom java.util.Comparator:
String[] names = {"Dan", "Bob", "Kris"};
java.util.Collections.sort(java.util.Arrays.asList(names), new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.charAt(1) - s2.charAt(1);//comparision
}
});
for (String name : names) System.out.println(name);
output:
Dan
Bob
Kris
You could try this, just add a custom comparator by using Lambda expressions if you are using java version 1.8 or above :
list.add("Bob");
list.add("Dan");
list.add("Kris");
Collections.sort(list, (s1, s2) -> {
String sb1 = s1.substring(1);
String sb2 = s2.substring(1);
return sb1.compareTo(sb2);
});
System.out.println("list = " + list);
The Result:
list = [Dan, Bob, Kris]
I haven't tested this one but you could try this one. Replace the condition part of your code by this one.
Though, there may be some performance issue.
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
Replace with:
if (Arr[i].trim().charAt(nthChar) > Arr[j].trim().charAt(nthChar)) {
The nthChar is the character placement to compare.
Here is sample tested code. You need to use comparator so as to implement the order.
Here value of order can be anything based on your requirement. You can replace your current code with this because it is fine for normal sorting as well (based on index 0). It might require some tweaks based on your need.
String str[] = {"abc","bca","avc","ert"};
final int ORDER = 1;
Arrays.sort(str, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.toLowerCase().charAt(ORDER) - o2.toLowerCase().charAt(ORDER) ;
}
});
Add different implementations of java.util.Comparator based on the requirement and use
public static <T> void sort(List<T> list,
Comparator<? super T> c) in collections class to sort the list.
You want to use a custom comparator.
This generates the array.
public word (String file)
{...
public int[] getArray()
{
int[] array = {... } ;
return array;
}
}
And I need to reference that array in another class
public static void main()
{
word numarray = new word("doc.txt");
int [] heightarray = numarray.getArray();
System.out.println(heightarray);
}
I'm not getting any errors but I get things like [I#1a6fa30c as a result.
What you are getting in the output is the hashcode of the array. In order to print the contents of the array you can you either of the below options :
Option 1 : Print the elements one by one using a loop a below :
for(int val : heightarray)
{
System.out.print(val + ",");
}
Option 2 : Use Arrays utility class for printing the array
System.out.println(Arrays.toString(heightarray));
You can print it using the Arrays.toString() method:
System.out.println(Arrays.toString(heightarray));
I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
When I try to return the sorted array to the main method it gives me the following error on the return line:
Incompatible Types
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
[Ljava.lang.String;#6d782f7c
Take a look at the method
public static String bubbleSortDesc(String[] names)
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck.
There are 2 points to fix. First you should return String array
public static String[] bubbleSortDesc(String[] names)
and therefore you should define it like this:
String descSort[];
public static String bubbleSortDesc(String[] names)
should be
public static String[] bubbleSortDesc(String[] names)
and also declare descSort as String array.
Also you are just printing the array objects. This will not print the list for you. You have iterate over the array.
Include this in you code:
for (String name:names)
{
System.out.println(name);
}
Do the same for descSort too....
You can fix your print command by changing it to the following:
System.out.println("Names listed sorted in descending order (via BubbleSort): "+ java.util.Arrays.deepToString(descSort));
If you want the nitty gritty, descSort is a String[]. In Java when you convert String[] into a String it gives you that crazy string representation. You have to instead converte each entry in the array to a String individually. Fortunately the deepToString method will do that for you.
I am trying to write a method that takes an ArrayList of Strings as a parameter and that places a string of four asterisks in front of every string of length 4.
However, in my code, I am getting an error in the way I constructed my method.
Here is my mark length class
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
And the following is my main class:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
ish.marklength4(words);
}
}
Essentially in this case, it should run so it adds an arraylist with a string of "****" placed before every previous element of the array list because the lengths of the strings are all 4.
BTW
This consists of adding another element
I am not sure where I went wrong. Possibly in my for loop?
I got the following error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Marklength.marklength4(Marklength.java:7)
at MarklengthTestDrive.main(MarklengthTestDrive.java:18)
Thank you very much. Help is appreciated.
Let's think about this piece of code, and pretend like you don't get that exception:
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
Ok, so what happens if your list just contains item.
You hit the line if(n.length() ==4){, which is true because you are looking at item, so you go execute its block.
Next you hit the line themarklength.add("****");. Your list now has the element **** at the end of it.
The loop continues, and you get the next item in the list, which happens to be the one you just added, ****.
The next line you hit is if(n.length() ==4){. This is true, so you execute its block.
You go to the line themarklength.add("****");, and add **** to the end of the list.
Do we see a bad pattern here? Yes, yes we do.
The Java runtime environment also knows that this is bad, which is why it prevents something called Concurrent Modification. In your case, this means you cannot modify a list while you are iterating over it, which is what that for loop does.
My best guess as to what you are trying to do is something like this:
import java.util.ArrayList;
public class Marklength {
ArrayList<String> marklength4(ArrayList <String> themarklength){
ArrayList<String> markedStrings = new ArrayList<String>(themarklength.size());
for(String n : themarklength){
if(n.length() ==4){
markedStrings.add("****");
}
markedStrings.add(n);
}
System.out.println(themarklength);
return markedStrings;
}
}
And then:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
words = ish.marklength4(words);
}
}
This...
if(n.length() ==4){
themarklength.add("****");
}
Is simply trying to add "****" to the end of the list. This fails because the Iterator used by the for-each loop won't allow changes to occur to the underlying List while it's been iterated.
You could create a copy of the List first...
List<String> values = new ArrayList<String>(themarklength);
Or convert it to an array of String
String[] values = themarklength.toArray(new String[themarklength.size()]);
And uses these as you iteration points...
for (String value : values) {
Next, you need to be able to insert a new element into the ArrayList at a specific point. To do this, you will need to know the original index of the value you are working with...
if (value.length() == 4) {
int index = themarklength.indexOf(value);
And then add a new value at the required location...
themarklength.add(index, "****");
This will add the "****" at the index point, pushing all the other entries down
Updated
As has, correctly, been pointed out to me, the use of themarklength.indexOf(value) won't take into account the use case where the themarklength list contains two elements of the same value, which would return the wrong index.
I also wasn't focusing on performance as a major requirement for the providing a possible solution.
Updated...
As pointed out by JohnGarnder and AnthonyAccioly, you could use for-loop instead of a for-each which would allow you to dispense with the themarklength.indexOf(value)
This will remove the risk of duplicate values messing up the index location and improve the overall performance, as you don't need to create a second iterator...
// This assumes you're using the ArrayList as the copy...
for (int index = 0; index < themarklength.size(); index++) {
String value = themarklength.get(index);
if (value.length() == 4) {
themarklength.add(index, "****");
index++;
But which you use is up to you...
The problem is that in your method, you didn't modify each string in the arraylist, but only adds 4 stars to the list. So the correct way to do this is, you need to modify each element of the arraylist and replace the old string with the new one:
void marklength4(ArrayList<String> themarklength){
int index = 0;
for(String n : themarklength){
if(n.length() ==4){
n = "****" + n;
}
themarklength.set(index++, n);
}
System.out.println(themarklength);
}
If this is not what you want but you want to add a new string "**" before each element in the arraylist, then you can use listIterator method in the ArrayList to add new additional element before EACH string if the length is 4.
ListIterator<String> it = themarklength.listIterator();
while(it.hasNext()) {
String name = it.next();
if(name.length() == 4) {
it.previous();
it.add("****");
it.next();
}
}
The difference is: ListIterator allows you to modify the list when iterating through it and also allows you to go backward in the list.
I would use a ListIterator instead of a for each, listiterator.add likely do exactly what you want.
public void marklength4(List<String> themarklength){
final ListIterator<String> lit =
themarklength.listIterator(themarklength.size());
boolean shouldInsert = false;
while(lit.hasPrevious()) {
if (shouldInsert) {
lit.add("****");
lit.previous();
shouldInsert = false;
}
final String n = lit.previous();
shouldInsert = (n.length() == 4);
}
if (shouldInsert) {
lit.add("****");
}
}
Working example
Oh I remember this lovely error from the good old days. The problem is that your ArrayList isn't completely populated by the time the array element is to be accessed. Think of it, you create the object and then immediately start looping it. The object hence, has to populate itself with the values as the loop is going to be running.
The simple way to solve this is to pre-populate your ArrayList.
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>() {{
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
}};
}
}
Do tell me if that fixes it. You can also use a static initializer.
make temporary arraylist, modify this list and copy its content at the end to the original list
import java.util.ArrayList;
public class MarkLength {
void marklength4(ArrayList <String> themarklength){
ArrayList<String> temp = new ArrayList<String>();
for(String n : themarklength){
if(n.length() ==4){
temp.add(n);
temp.add("****");
}
}
themarklength.clear();
themarklength.addAll(temp);
System.out.println(themarklength);
}
}