For this program, I need to have the user input strings, which will then be put into an array along with their reversed counterparts. The entire array would then be alphabetized. So it should work like this:
Input: strawberry banana, apple, grapes
Output: apple, ananab, banana, elppa, grapes, separg, strawberry, yrrebwarts
I have the code for this, and it works to some degree. However, it only alphabetizes the reversed and the normal but separately. So it ends up looking like this:
Output: ananab, elppa, separg, yrrebwarts, apple, banana, grapes, strawberry
As you can see it is alphabetizing the words to some degree, but not how it should be. Here is my code:
import java.util.Scanner;
public class WordGame {
public static void main(String[] args) {
String reverseInput = " "; //creates an empty string where the reverse will be stored before putting it into the array
String[] wordArray = new String[1000]; //creates an array that allows for 500 words, and 500 reverses of said words
int s = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the words you would like to reverse. To finish entering words enter a blank line:");
String userInput = sc.nextLine(); //allows for user to input words
int length = userInput.length();
int i = 0;
while (!userInput.equals("")){ //runs until the user enters a blank line
reverseInput = " ";
for(i = length - 1; i >= 0; i--)
reverseInput += userInput.charAt(i);
wordArray[s] = userInput; //reverses user inputted strings by taking the last letter and putting it in front, repeating until the whole word is reversed
wordArray[s + 1] = reverseInput;
s += 2;
userInput = sc.nextLine();
length = userInput.length();
}
for(int j = 0; j < s-1; j++){ //beginning of alphabetical sorting
for(int k = 0; k < s-1-j; k++){
int l = 0;
while((int)wordArray[k].charAt(l) == (int)wordArray[k+1].charAt(l))
l++;
if ((int)wordArray[k].charAt(l) > (int)wordArray[k+1].charAt(l)){
String holder = wordArray[k];
wordArray[k] = wordArray[k+1];
wordArray[k+1] = holder;
}
}
}
for(i = 0; i < wordArray.length; i++){
if (wordArray[i]!= null){
System.out.print(wordArray[i] + " "); //prints out contents of array
}
}
}
}
I am not sure what the issue is. Any help would be much appreciated. Thanks!
As far as I can see you put an extra blank in front of your "reverseInput" with reverseInput = " ";
Because your reverse string won't start with a char you think (it starts with a blank) the result is not what you really want. Try to delete the blank and retry you code.
There are definitely easier ways to do this, depending on if you want to use Java's built in classes for this kind of thing. I just wrote this up, it accomplishes the sort with reversed Strings that you want.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
public static void main(String args[]) {
ArrayList<String> values = new ArrayList<String>();
values.add("strawberry");
values.add("banana");
values.add("apple");
values.add("grapes");
Solution s = new Solution();
values = s.sortList(values);
int itemCt = 1;
for (String item : values) {
System.out.println(itemCt + ": " + item);
itemCt++;
}
}
public ArrayList<String> sortList(List<String> strings) {
ArrayList<String> combinedList = new ArrayList<String>();
for (String str : strings) {
combinedList.add(str);
combinedList.add(new StringBuilder(str).reverse().toString());
}
Collections.sort(combinedList);
return combinedList;
}
}
Related
Java is my first programming language, and I'm still unfamiliar with how arrays work. However, I was able to make this program, which accepts user-input for an integer array; it then outputs indexes and values, to show how arrays store numbers. I would like to recreate this program using a string array, to make a table containing a list of friends.
The .length property also confuses me...
Could someone explain the .length property and help me make the string array program work?
Thank you very much.
Here is the working code for the integer array table program
import java.util.*;
public class AttemptArrayTable
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Let me show you how arrays are stored ");
System.out.println("How many numbers do you want your array to
store? ");
int arrayInput [] = new int[scan.nextInt()];
System.out.println("Enter numbers ");
for (int count = 0; count<arrayInput.length; count++)
arrayInput[count] = scan.nextInt();
System.out.println("");
System.out.println("Index\t\tValue");
for (int count2=0; count2<arrayInput.length; count2++)
System.out.println(" [" + count2 + "]"+"\t\t " + arrayInput[count2]);
}
}
Here is the code for the string array program I'm working on
import java.util.*;
public class ArrayTableofFriends
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many female friends do you have? ");
String arrayOfFriendsFem [] = new String [scan.nextInt()];
System.out.println("List the name of your female friends");
for(int countF = 0; countF<arrayOfFriendsFem.length; countF++)
arrayOfFriendsFem[countF]= scan.nextLine();
System.out.println("How many male friends do you have? ");
String arrayOfFriendsMale [] = new String [scan.nextInt()];
System.out.println("List the name of your male friends");
for(int countM = 0; countM<=arrayOfFriendsFem.length; countM++)
arrayOfFriendsMale[countM]= scan.nextLine();
System.out.println("How many alien friends do you have? ");
String arrayOfFriendsAliens [] = new String [scan.nextInt()];
System.out.println("List the name of your alien friends");
for(int countA = 0; countA<=arrayOfFriendsFem.length; countA++)
arrayOfFriendsAliens[countA]= scan.nextLine();
{
System.out.println("Female\t\t\t" + "Male\t\t\t" + "Aliens");
for(int countF2 = 0; countF2<arrayOfFriendsFem.length; countF2++)
System.out.println(arrayOfFriendsFem[countF2]);
for(int countM2 = 0; countM2<=arrayOfFriendsMale.length; countM2++)
System.out.println("\t\t\t" + arrayOfFriendsMale[countM2]);
for(int countA2 = 0; countA2<=arrayOfFriendsAliens.length; countA2++)
System.out.println("\t\t\t\t\t\t" +arrayOfFriendsAliens[countA2]);
}
}
.length property stores number of elements in the array. But elements are starting from 0. So, when .length = 1, then there is only one element in the array, with index 0.
It seems in your String arrays program in the for loop the <= should be changed to <
Like this:
for (int countA = 0; countA < arrayOfFriendsFem.length; countA++)
I'm doing a task in which I am told to check for the '-'s in sample data, when a - is found in the data and there are adjacent dashes within the hashes, this only counts for 1 occurrence, e.g. in this sample data the answer would be 4.
I started by creating a 2D array to populate it then I was going to check for the dashes in the array but I am a bit puzzled as to how I would go about actually counting the occurrences, Any help would be appreciated.
Here's what I have so far;
Scanner input = new Scanner(System.in);
int a = input.nextInt(); //no. of rows
int b = input.nextInt(); //no. of columns
String arr[][] = new String[a][b]; //array of strings of 10 x 20
for(int i = 0; i<a; i++){
for(int j = 0; j<b; j++){
arr[i][j] = input.next();
}
}
//for test purposes
for(String[] s : arr){
for(String e : s){
System.out.print(e);
}
}
Here's the sample input:
10 20
#################---
##-###############--
#---################
##-#################
########---#########
#######-----########
########---#########
##################--
#################---
##################-#
Simplest way to use regex. Consider each row as string, trim string and then allow only 20 characters in string(based on your column count).
Other approaches could be to use DSL algos.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String... args) throws Exception {
Scanner input = new Scanner(System.in);
int a = input.nextInt(); // no. of rows
int b = input.nextInt(); // no. of columns
Pattern pattern = Pattern.compile("#(--+)#");
int count = 0;
for (int i = 0; i < a; i++) {
String temp = input.next().trim();
if (temp.length() > b) {
temp.substring(0, b);
}
Matcher matcher = pattern.matcher(temp);
if (matcher.find()) {
count++;
}
}
System.out.println(count);
}
}
This is my first question on this site, I'm running this on NetBeans 8.0.2 and trying to print out my user-defined array but it keeps returning null values. For example if you say there are 2 employees and enter both of their names, it will return [null, null]
How to fix this error? I'm a novice.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;
class Tips_Calculation2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
// counter for the if statement that should return all employees from the array
int counter = numberOfEmps;
int[] nOEarray = new int[numberOfEmps];
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
String[] namesArray = new String[i];
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
}
}
Disregard import java.text.DecimalFormat as I plan to use this import later on in my code. Thank you in advance to anyone who is kind/smart enough to respond.
First of all you never put your nameCycler to array. Second of all you create your namesArray every iteration which I think is wrong.
You're creating a brand new (full of null) array namesArray on every pass through the loop--and then never assigning anything to it. I think you're looking for something like this instead. Note that Java indexes from zero, not one.
String[] names = new String[numberOfEmps]
for(int i = 0; i < names.length; i++) {
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
First of all, you should initialise the array outside of your loop. Secondly, you forgot to set the name to the array value(s).
Try this:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;
class Tips_Calculation2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
int[] nOEarray = new int[numberOfEmps];
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
String[] namesArray = new String[numberOfEmps];
for (int i = 0; i < numberOfEmps; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
Replace
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
String[] namesArray = new String[i];
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
With
String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++)
{
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
And see whether it works.
You never assign the name to the array and in every iteration you define the array new:
String[] namesArray = new String[numberOfEmps];
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
namesArray [i] = nameCycler ;
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
Added comments in the code to point out changes.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
// removed 'nOEarray' and 'counter'
if (numberOfEmps > 0) {
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
// initializing 'namesArray' outside for loop.
String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++) { // initialized with 0 and updated condition with '<'
namesArray[i] = scan.next(); // assigning value to 'i'th position of namesArray
}
System.out.println(Arrays.toString(namesArray)); // Printing array outside for loop
}
}
"How to fix this error" not. This is not an error.
String[] namesArray = new String[i]; // step one, you declare an array of Strings
// which you don't initialize
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
//you print all the (non-initialized) elements of namesArray
//since you didn't initialize the elements, it takes the default value, which is null
}
fill the elements of the array with Strings before trying to print them.
I'm trying to use Java to solve a simple challenge but I have unsuccessful and I can't find an answer. The idea is that the user enters a string of text, and the program returns the longest word in that string. I can use Scanner to accept the input from the user, and then the .split() method to split the string at the spaces with .split(" ") but I can't figure out how to store the split sentence in an array that I can iterate through to find the longest word. I always get a console output that looks like this:
[Ljava.lang.String;#401a7a05
I have commented out the code that I think should find the longest word so as to focus on the problem of being unable to use Scanner input to create an array of Strings. My code at the moment is:
import java.util.*;
import java.io.*;
class longestWord {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
//for (int i = 0; i <= b.length(); i++) {
// if (longest < b[i].length()) {
// longest = b[i].length();
// word = b[i];
// }
//}
//System.out.println(word);
System.out.println(c);
}
}
That's because you are iterating over the string, not the array, and trying to output the entire array. Change your for loop to use c instead:
for (int i = 0; i < c.length; i++) //In an array, length is a property, not a function
{
if (longest < c[i].length())
{
longest = c[i].length();
word = c[i];
}
}
That should fix your first output. Then you want to change how you output your array, change that to something like this:
System.out.println(Arrays.toString(c));
Which will display the array like so:
[word1, word2, word3, word4]
So you want to get the input as a string and automatically make it an array? You can do that simply by calling the split function after nextLine on the scanner:
String[] wordArray = n.nextLine().split(" ");
there are many mistakes in you code. such a
you were
iterating over string not on array.
if (longest < b[i].length()) as b is your string not array of string
try this it will work it will print the longest word and its size as well.
class Test {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
for (int i = 0; i < c.length; i++) {
if (longest < c[i].length()) {
longest = c[i].length();
word = c[i];
}
}
System.out.println(word);
System.out.println(longest);
}
}
I have this question Write a static method which takes an ArrayList of Strings and an integer and changes the ArrayList destructively to remove all Strings whose length is less than the integer argument. i have this code so far could someone explain where I'm going wrong. it compiles but it doesn't remove any strings from the array list.
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
}
}
System.out.println("The ArrayList is "+a);
}
}
When you remove an item of the ArrayList be sure to decrement "j". Also, although it is not common, set the for-condition to j < a.size(). Otherwise create a separate variable to store the size before the loop and then decrement it as well.
The following code should work.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<a.size(); j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
j--;
}
}
System.out.println("The ArrayList is "+a);
}
You traverse the list from left to right and remove items as you go along. This causes a problem when removing multiple items, because the indices don't match any more.
This can be fixed quite easily by traversing the list from end to begin, instead of from begin to end.
Because now, if you remove an item, this doesn't affect the items to be removed later on:
for (int j = words.length - 1; j >= 0; j--)
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static ArrayList<String> a;
public static ArrayList<String> presenter;
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
a = new ArrayList<String>();
presenter = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if((b.length()<len))
{
//do nothing
}
else
{
presenter.add(a.get(j));
}
}
System.out.print("The ArrayList is " + presenter);
}
}
This is an alternative since you said the other codes didn't work, I simply transferred the "Good" data to another arraylist and printed out that one.