multiply output of string by using custom input - java

I am trying to write a program that would take an ArrayList containing "How", "Are" and "You?" and pass this to a 'stutter' method that will get the output to repeat the words after asking the user for number/how many times they want the word repeated.
Example: if user enters 4, i would pass How, Are and You? and 4 to this stutter method and the output would be How, How, How, How, Are, Are, Are, Are, You?, You?,You?,You?. This seems simple enough but i cannot get the output correct. Any help is appreciated!
import java.util.*;
public class Question3 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("how");
list.add("are");
list.add("you?");
Scanner input = new Scanner(System.in);
System.out.println("How many repeats?");
int repeat = input.nextInt();
System.out.println("Before stutter: " + list);
stutter(list, repeat);
}
public static void stutter(ArrayList<String> list, int repeat){
ArrayList<String> modifiedList = new ArrayList<String>();
for(String str : list) {
for(int i = 0; i < repeat; i++)
modifiedList.add(str);
System.out.print(modifiedList);
}
}
}

The print statement is running in the outer loop, so it prints modifiedList once for each str. Move it to the end of the method so it prints the final result once:
public static void stutter(ArrayList<String> list, int repeat){
ArrayList<String> modifiedList = new ArrayList<String>();
for(String str : list) {
for(int i = 0; i < repeat; i++)
modifiedList.add(str);
}
System.out.print(modifiedList);
}

Related

Can't get last element in arrayList without knowing the length

import java.util.Scanner;
import java.util.ArrayList;
public class kek2 {
public static void main(String[] args) {
Scanner imeskanera = new Scanner(System.in);
ArrayList<String> wordlist = new ArrayList <String>();
while(true) {
System.out.println("Type a word: ");
String word = imeskanera.nextLine();
int lenght =wordlist.size();
if(word.equals("")) {
for(int i = 0;i<lenght; i++) {
System.out.println(wordlist.get(lenght-i));}
break;
}
wordlist.add(word);
}
}
}
Im trying to print out the array in reversed order but i get error in (lenght-i) part, everything looks fine to me, am'I doing something wrong that Java doesnt allow?
It may be better to limit while loop to reading the inputs and when user is done, print the list contents in any desired order.
Scanner imeskanera = new Scanner(System.in);
List<String> wordlist = new ArrayList<>();
String word;
System.out.println("Type a word: ");
while(!(word = imeskanera.nextLine()).isEmpty()) {
wordlist.add(word);
System.out.println("Type a word: ");
}
for (int i = wordlist.size(); i-- > 0;) { // index decremented in condition
System.out.println(wordlist.get(i));
}
Or ListIterator may be retrieved using List::listIterator and its methods hasPrevious() / previous() can be used to iterate in reverse direction -- however, the size of list is needed anyway:
for (ListIterator i = wordlist.listIterator(wordlist.size()); i.hasPrevious();) {
System.out.println(i.previous());
}

Trying to remove the 5th name entered from my array. I'm getting a cannot find symbol error and I can't figure out why

import java.util.Scanner;
public class Assignment6APt2 {
public static void main(String[] args) {
int n = 10;
Scanner scan = new Scanner(System.in);
System.out.println("Enter 10 names: ");
String [] names = new String[n];
for (int i = 0; i < names.length; i++){
names[i] = scan.nextLine();
}
names.remove(4);
arrayMethod(names);
}
private static void arrayMethod(String[] names)
{
for (String a : names)
{
System.out.printf( "%s",a);
}
}
}
There isn't a remove method for arrays, and this operation really doesn't make sense anyway. What does it even mean to "remove" an item from a fixed-size array?
The closest thing you can do is set array index 5 to null, which is just a simple assignment. I'm not sure I recommend doing that, though. You probably want to either rethink doing that or just use a variable-size data structure.

First time using methods (java) and nothing is being returned to the console, where am I going wrong? [duplicate]

This question already has answers here:
Differences between System.out.println() and return in Java
(4 answers)
Closed 5 years ago.
I'm still learning the basics of coding in Java and have moved onto using methods which has thrown me. My issue is nothing is being returned to the console and I have no idea why. Here's my code:
public class MethodsPractice {
public int returnInteger (int num1, int num2){
return num1 + num2;
}
public String[] upperCaseString(String[] strings){
String[] upperStrings = new String[strings.length];
for (int i = 0; i < strings.length; i++){
upperStrings[i] = strings[i].toUpperCase();
}
return upperStrings;
}
public static void main(String[] args) {
MethodsPractice myMethods = new MethodsPractice();
int result = myMethods.returnInteger (10,20);
String[] names = {"Bob", "Alex", "Luke"};
String[] newNames = myMethods.upperCaseString(names);
}
}
Simply put, you just aren't putting anything to console. Your code creates a new object, does some math, then creates an array of strings, but it never does anything with those newly created objects, for ex: If you wanted to print the result of the math function you need to use:
System.out.println(result);
Java (mostly)does not print anything to console you don't tell it to.
System.out is the stream where you can print to console.
Of course, println is not the only function :) https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#out
upperCaseString just returns the a new array, which your main method saves to the newNames variable, and then does nothing with it. If you want to print it, you would have to do so explicitly, e.g.:
System.out.println(Arrays.toString(newNames));
To see content in the console, you need to call the methods from System.out like
print() : show content
println() : show content and go to next line
To easily print arrays, there is tips like :
String[] newNames = myMethods.upperCaseString(names);
System.out.println(Arrays.toString(newNames));
The classic way to print array will be with for (or foreach loop)
for(int i = 0; i<newNames.length ; i++) // for loop
System.out.print(newNames[i] + ", ");
for(String str : newNames) // foreach loop
System.out.print(str + ", ");
You have to add an Console Output with:
System.out.print(); //without new line
or
System.out:println(); //starts a new line after output
For example:
public class MethodsPractice {
public int returnInteger (int num1, int num2){
return num1 + num2;
}
public String[] upperCaseString(String[] strings){
String[] upperStrings = new String[strings.length];
for (int i = 0; i < strings.length; i++){
upperStrings[i] = strings[i].toUpperCase();
}
return upperStrings;
}
public static void main(String[] args) {
MethodsPractice myMethods = new MethodsPractice();
int result = myMethods.returnInteger (10,20);
String[] names = {"Bob", "Alex", "Luke"};
String[] newNames = myMethods.upperCaseString(names);
System.out.print(name[0]);
System.out.println(name[1]);
System.out.print(name[2])
}
}
In the Consol will output:
BobAlex
Luke

How do i return an ArrayList<String> from a method?

Here is my first method. I have a file that I added its contents to an ArrayList. I can print that just fine but I need to create a method that adds line numbers to the beginning of each String. I can do that outside the method but i'm having problems creating a method that returns an arrayList so i can use the updated arrayList in other methods and then I need to display the updated ArrayList. Here is my code.
My output for the first method should be
1 bird
2 cat
etc...
My output for the second method should return the elements in the ArrayList in reverse order.
2 cat
1 bird
etc...
import java.util.*;
import java.io.*;
public class List
{
public static void main(String[] args) throws IOException
{
int line =1;
ArrayList<String> textArray = new ArrayList<String>();
ArrayList<String> newArray = new ArrayList<String>();
File f = new File("src/List.txt");
Scanner sc = new Scanner(f);
int num = 1;
while(sc.hasNext())
{
textArray.add(sc.nextLine());
}
numbered(textArray);
reverseOrder(textArray);
}
public static ArrayList<String> numbered(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : results)
{
r = num + " " + results;
num++;
}
return results;
}
public static ArrayList<String> reverseOrder(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : results)
{
}
return results;
}
You are returning your arrays correctly, the problem is that you are creating new Objects inside your methods, instead of using the ones you receive as parameters
ArrayList<String> results = new ArrayList<String>(textArray.size());
So you are iterating empty arrays.
Inside your for loop, you could just iterate the received ArrayList
for (String r : textArray)
Also, your results array is always empty, you should add new elements like this:
results.add(r);
This may work:
public static ArrayList<String> numbered(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : textArray)
{
r = num + " " + results;
num++;
results.add(r);
}
return results;
}
Have not tested this but it should work. As you can see pretty straight forward. Best of Luck and happy coding.
public ArrayList<String> numList(ArrayList<String> originalArrayList)
{
ArrayList<String> newNumberedList = new ArrayList<String>();
for(int i = 0;i< originalArrayList.size(); i++){
int newi = i+1;
newNumberedList.add(newi+". "+originalArrayList.get(i));
}
return newNumberedList ;
}
You are instantiating the 'results' arraylist, and iterating it. You need to iterate the textArray list for starters and call results.add("text");

Sorting an array of strings in Java

The user is allowed to play with an array of strings. They can add strings to the array, remove strings from the array, search for strings in the array, and eventually they will be able to sort the array. The sorting is what is messing me up. I've tried a few different approaches. The first approach was to convert the array into an ArrayList and use Collections to sort the ArrayList, which would be converted back into the static class array. It doesn't work. The second approach I tried was to iterate through the array and try to sort only the strings added by the user instead of everything in the array (since there are some null values in the array). Perhaps I should iterate through the array and then store the non-null values into a new array that I can then sort? But what if I want to add more strings after sorting the new array? That's why I stopped with the second solution. The third attempt was to use Arrays.sort() on my array but for some reason it does not work.
Here is the exception:
Exception in thread "main" java.lang.NullPointerException
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
at testingSearch.sortArray(testingSearch.java:93)
at testingSearch.main(testingSearch.java:42)
Here is my code:
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testingSearch {
static String[] strArray;
static {
strArray = new String[5];
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add string to the string array.");
System.out.println("2. Remove string from the string array.");
System.out.println("3. Display strings in string array.");
System.out.println("4. Search the string array for a string.");
System.out.println("5. Sort the strings in the string array.");
int userChoice = 0;
userChoice = input.nextInt();
switch(userChoice) {
case 1:
addString();
break;
case 2:
removeString();
break;
case 3:
displayStrings();
break;
case 4:
searchArray();
break;
case 5:
sortArray();
break;
}
}
}
public static void addString(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to add?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
stringList.add(userInput);
strArray = stringList.toArray(strArray);
}
public static void removeString(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to remove?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
stringList.remove(userInput);
strArray = stringList.toArray(strArray);
}
public static void displayStrings(){
for (String s: strArray){
if (!(s == null)){
System.out.println(s);
}
}
}
public static void searchArray(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to search the array for?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
if (stringList.contains(userInput)){
System.out.println("The string array contains that string!");
}
else {
System.out.println("The string array does not contain that string...");
}
}
public static void sortArray(){
/*ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray);*/
/*for (String s: strArray) {
if (!(s == null)){
Arrays.sort(strArray);
}
}*/
List<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray);
//Arrays.sort(strArray);
}
}
The reason you're getting NullPointerExceptions can be explained by the javadoc for Arrays#sort() (emphasis mine):
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface.
Because Arrays.sort() expects Comparable elements and not null values, you end up with a NullPointerException when the method tries to call compareTo().
The fix-this-now way of solving this would be to simply make sure all null elements in your array are replaced with something non-null, such as "". So loop through your array at creation and after removing a String and set null elements to "". However, this solution probably wouldn't perform too well for your code, as it requires another loop after every String is removed, which could grow onerous. At least it won't require you to create a bunch of objects, due to the magic of the String pool, so it's a bit better than what you might do with a different object.
A better solution would be to simply use ArrayList<String> instead of a raw array; after all, you're already using one to manage addString() and removeString(), so you would have less converting from array to ArrayList and back to do. In addition, you wouldn't need to worry about NPEs when sorting (at least for your use case; adding null to a Collection would still result in NPEs when sorting).
You can also just use a raw array, but managing that would get kind of annoying, so I wouldn't recommend that. If you do it right you won't have to worry about NPEs though.
No problem! Here you go:
1. Create a new array
2. Insert items to that array, in the right order
public class sorter {
public static void main(String[] args){
String[] array = new String[]{"HI", "BYE", null, "SUP", ":)"};
//Sort:
String[] newArray = new String[array.length];
int index = 0;
for(int m = 0 ; m < newArray.length; m++){
String leastString = null;
int i = 0;
for(i = 0; i < array.length; i++){
if(leastString==null&&array[i]!=null){
leastString = array[i];
break;
}
}
for(int j = i+1; j < newArray.length; j++){
if(array[j]!=null){
if(array[j].compareTo(array[i])<0){
leastString = array[j];
i = j;
}
}
}
if(i==newArray.length)break;
newArray[m] = leastString;
array[i] = null;
}
for(String s : newArray){
System.out.println(s);
}
}
}
This prints:
:)
BYE
HI
SUP
null
EDIT: Another very simple way to solve this in a very effiecient manner, is to use ArrayList:
public class AClass {
public static void main(String[] args){
String[] array = new String[]{"HI", "BYE", null, "SUP", ":)"};
//Sort:
ArrayList<String> newArray = new ArrayList<String>();
for(String s : array){
if(s!=null){
newArray.add(s);
}
}
Collections.sort(newArray);
String[] retval = new String[newArray.size()];
retval = newArray.toArray(retval);
for(String s : retval){
System.out.println(s);
}
}
}
I guess the simple way of doing things really would be:
static String[] strArray;
static {
strArray = new String[5];
for(int i = 0, i < strArray.length; i++)
{
strArray[i] = "";
}
}
And then just call
Arrays.sort(strArray);
When you want to sort it. If that doesn't work, although I think it should; your initial approach would have been the following:
List<String> stringList = new ArrayList<String>();
for(int i = 0; i < strArray.length; i++)
{
stringList.add(strArray[i]);
}
Collections.sort(stringList);
strArray = stringList.toArray(new String[stringList.size()]);
Although it clearly doesn't seem very memory-friendly.

Categories

Resources