I am learning about arrays and I did quiet a few experiments, most of them went well, however now I'm stuck.
What I want to archive is, find if an specific value (String, int or whatever), exists inside an Array and if it does, use that value for something i.e the code below which I basically count how many times that value was present inside the array:
package arraysOnly;
import java.util.*;
public class ArrayContainsString
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int arraySize = 0;
int wordCount = 0;
System.out.println("How many words are you gonna type?: ");
arraySize = sc.nextInt();
String[] words = new String[arraySize]; // Simple array, the size of which will be decided from the user-input
for(int count = 0; count < arraySize; count++)
{
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
}
//Basically this is the part I'm having troubles
if(in_array("ubt", $words)
{
wordCount++;
}
}
}
I know about this,
if(Arrays.asList(words).contains("ubt"));
which basically converts the array into an List / ArrayList or whatever, however I want to treat this as an array only if possible.
An array is the wrong data structure; a Set is the weapon of choice:
Set<String> words = new HashSet<>()
for (int count = 0; count < arraySize; count++) {
System.out.println("Enter your " + (count+1) + ": ");
words.add(sc.next());
}
if (words.contains("ubt"))
wordCount++;
}
The contains() method of a HashSet completes in constant time not matter how large the set is. Although performance is irrelevant for small input sizes like this usage, it's good to get in the habit of choosing the right tools for the job. It also makes your code cleaner.
Generally speaking, don't use arrays unless you absolutely have to; they are only rarely used in commercial code.
The simple solution
public static boolean contains(String toFind, String[] strings) {
for (String str : strings) {
if (str.equals(toFind)) return true;
}
return false;
}
EDIT:
To increase it after the user inputs a word, use this in the loop:
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
if (words[count].equals("ubt")) wordCount++;
You can just iterate over array
for (String str : array){
if(str.equals("ubt")){
wordCount++;
}
}
Edit:
It's just equivalent to a normal for loop
for(int i=0; i<array.length; i++) {
if(array[i].equals("ubt")){
wordCount++;
}
}
Related
I recently got into Java Programming (Maybe it's already getting too hard for me), and I'm doing some exercises daily to practise. One of the challenges I need to do, is to search an Element (int), and if it's in the Array, the Index should be displayed (All index's should be displayed if Element duplicates found in Array).
Here's the code I have so far!
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
break;
}
list.add(input);
}
System.out.println("");
// implement here finding the indices of a number
System.out.println("Search for?");
int arraySize = list.size();
int numToSearch = Integer.valueOf(scanner.nextLine());
for(int i = 0; i <arraySize-1; i++){
int pos = list.indexOf(numToSearch);
if(list.indexOf(i)==pos){
System.out.print(numToSearch+" is at Index: "+pos);
}
}
}
}
So far I've managed to get it to print the Index of the Element I search for, but it only does it for the first correct Index it finds.
Sorry for the clunky code, haven't yet learnt much in terms of neat code!
In the last loop, you were checking the equality between the index of numToSearch in list and the index of 0...arraySize-2 in list. Unless I am understanding the question incorrectly, the correct approach should be checking the equality of each array member and numToSearch. Then print out the string with the current index you are at.
This could be represented like this:
for (int i = 0; i < arraySize; i++) {
if (list.get(i) == numToSearch) {
System.out.println(numToSearch + " is at Index: " + i);
}
}
The code below takes user input of 10 integers, uses String.split(" ") on the space, parses them as integers and prints them out.
public class variableGrowth
{
public main variableGrowth()
{
System.out.print('\u000c');
//scanner and variables
Scanner scan = new Scanner(System.in);
String inputInt = scan.nextLine();
System.out.println("These are the integers you entered: "+inputInt);
String[] items = inputInt.split(" ");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
System.out.println(stuff);
}
catch (NumberFormatException nfe) {
System.out.println(results);
System.out.println(errorMessage);
}
}
}
}
}
For each iteration of the loop, can the output be accessed so I could complete a sum in the loop and print it out? For example:
System.out.print(stuff(firstInt)); -- the first integer entered,
result= current + (current * (firstInt/ 100)); // or anything like this
System.out.print("something meaningful: "+result);
Your code won't compile unless you declare the variable errorMessage.
You just initialize an array to store your results but you never use it. In your loop, you should store each parsed value.
results[i] = stuff;
Then outside your loop you can access all your integers to do some stuff.
But for a simple sum operation, you can define a variable then sum each new int inside the loop.
int sum;
for ...
// get your stuff here
sum += stuff;
Also I did not notice your method signature at first. But the signature of a main method is
public static void main(String args[])
In Java, your method signature should follow :
[accessor] [static] 'returnType' yourMethodName('yourParams')
All you need to do is create an additional variable which will contain your running total.
int total = 0;
for (...) {
System.out.println(value);
total += value;
System.out.println("Running Total: " + total)
}
Go with streams (Java 8):
import java.util.*;
import java.lang.*;
class Main
{
public static void main(String[] args) {
System.out.print('\u000c');
//scanner and variables
Scanner scan = new Scanner(System.in);
String inputInt = scan.nextLine();
System.out.println("These are the integers you entered: "+inputInt);
String[] items = inputInt.split(" ");
int sum = Arrays.stream(items)
.mapToInt(x -> Integer.parseInt(x))
.sum();
System.out.println(String.format("Sum is: %s", sum));
}
}
There are a few ways you can do this. If you are looking for a direct sum of all the numbers, just keep a sum variable outside of the loop and keep a working sum through all iterations.
int sum = 0;
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
sum += stuff;
...
}
Another way is to store all of the numbers (especially if you need to perform other operations with them) in a list or an array and perform your operations after the fact.
int[] numbers = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
numbers[i] = stuff;
...
}
// Perform operations here
I am kinda new to Java, please do not tell me to use methods, etc. because I do not know how to do them. But I do know some charAt things, so can anyone help me find the amount of words, and avg of each word, i did the first part. Here is my code.
import java.util.Scanner;
public class FavouriteQuote {
public static void main(String[] args) {
// TODO Auto-generated method stub
String sQuote;
int counter = 0;
Scanner input = new Scanner (System.in);
System.out.print("Enter one of your favourite quotes: ");
sQuote = input.nextLine();
input.close();
for (int i = 0; i < sQuote.length(); i ++) {
counter ++;
}
System.out.println(counter);
}
}
But what average do you need? average word length in quote?
then your code may look like:
...
input.close();
System.out.println("Characters in quote:" + sQuote.length());
String[] words = sQuote.split("\\s");
// or
// String[] words = sQuote.split(" ");
System.out.println("words in quote:" + words.length);
int totalWordsLength =0;
for (String word: words)
{
totalWordsLength = totalWordsLength + word.length();
}
//or with loop counter
// for (int i=0; i < words.length; i++)
// {
// totalWordsLength += words[i].length();
// }
System.out.println("average word length in quote:" + (totalWordsLength/ words.length));
Keep in mind: here average is int so it will be only integer portion of divide result. i.e. 11/3 = 3
BTW (aside of question) - You do not need your for loop. It does not make any sense.
counter = sQuote.length() does the same.
I have to first take as input the number of strings to be sorted. As they are entered, I have to sort them in ascending order, not at the end. The first part came out fine, but I don't know how to sort them (preferred method per instructor is the compareto method) when I have nothing to compare until it's entered. I cannot use the Arrays class or Collection class, which means I have to work around it to test my ingenuity.
Does anyone have any tips or pseudo code to lead me in the right direction?
Thanks.
Here is the code:
import java.util.*;
public class Sort_as_Inserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of elements to be sorted: ");
String element_number = input.nextLine();
String[] user_word = new String[Integer.parseInt(element_number)];
for (int i = 0; i < Integer.parseInt(element_number); i++)
{
System.out.print("Element " + (i + 1) + ": ");
user_word[i] = input.nextLine();
}
System.out.println();
}//end Main Method
}//end Class
I am supposed to sort these elements as they are put in, not after (which makes it even more difficult for me). I cannot use anything in the Arrays class or Collection class to sort them. They have to be sorted in ascending order. So, if a user types "4" as the number of elements, then types "Cherry, Banana, Orange, Apple," it will output: "Apple, Banana, Cherry, Orange."
Looks like you need Insertion Sort. Google it and try to understand the concept. Then try implementing it. Once you got that far you will probably have questions about specific parts where you struggle (if you'll struggle at all).
I got it and it worked as intended. It took some thinking, but it's done. I wanted to post my completed code for future questions from others.
import java.util.Scanner;
public class Sort_as_Inserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of elements to be sorted: ");
int array_size = input.nextInt();
String[] user_words = new String [array_size];
input.nextLine();
for (int i = 0; i < user_words.length; i++)
{
System.out.print("Element " + (i + 1) + ": ");
user_words[i] = input.nextLine();
}//end for
System.out.println();
sortStrings(user_words);
printTheArray(user_words);
}//end Main
public static void sortStrings(String[] words) {
/**
* This method will utilize an Insertion Sort Algorithm
*/
for (int i = 0; i < words.length; i++)
{
for(int j = i + 1; j < words.length; j++)
{
if(words[i].compareToIgnoreCase(words[j]) > 0)
{
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}//end if
}//end inner for
}//end outer for
}//end sortSTrings Method
public static void printTheArray(String[] the_words) {
/**
* This following code block will print the array, and format it properly
* so there is no comma after the last word in the array.
*/
if (the_words.length >= 1)
{
System.out.print(the_words[0]);
}
for (int i = 1; i < the_words.length; i++)
{
System.out.print(", " + the_words[i]);
}
}//end printTheArray Method
}//end Sort_As_Inserted Class
The goal of this code was to create a program using main method java to analysis a piece text which has been entered from a user.
They do this by entering the text into a scanner which is then analysed by the program. The analysis is to produce word frequency, for example " This is a test" produces this results:
This is a test
1 letter words: 1
2 letter words: 1
3 letter words: 0
4 letter words: 2
5 letter words: 0
The bit that I'm stuck on is producing a mean/average, My guts telling to divide
counts.length by str.length but I'm not the Best at java and I've tried to implement this but all I get are errors. I'm not expecting anyone to just hand me code, but if someone could give me a hint in what I should do or just point me the right direction it would be greatly appreciated.
Code:
import java.util.Scanner;
public class Text_AD {
public static void main (String[] args) {
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}}}
By average, I am assuming that you mean the mean length. I am also assuming you want to get a floating point mean. In which case you just need to divide the total of all the lengths in strings by the length of the array itself.
You could do something like the following;
int total = 0;
for(String s : strings) total += s.length();
System.out.println((double)total/strings.length);
I hope this helps.
Without breaking up your code much, you could run a for loop through your counts[] array, adding up all the values, and then dividing by counts.length to get the average.
Be aware of type casting though. You may want to do Double division instead of integer.
It this what you are looking for?
import java.util.Scanner;
public class While_Loop {
public static void main (String[] args) {
int lengthSum, wordCount;
lengthSum = wordCount = 0;
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
wordCount++;
lengthSum += str.length();
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
System.out.println("Average: " + lengthSum/wordCount);
}}}
NOTE: I only added stuff to your code. The way it is written is pretty messy. I'd clean up some of the for loops and the brackets at the end for practice making the code more readable.
When I understand you correct you should have one variable int totalCount = 0; where you add
totalCount += i*counts[i]; in your last for loop.
After the loop you can simply divide through the size-1 (because 0 does not count)
double average = totalCount/(counts.length-1);
Alternative way
You take the inputstring length without the spaces and divide it by the number of spaces + 1 (which is equal to the number of words)
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
System.out.println("Enter text: ");
String s = "This is a sample text";
System.out.println("" + s);
String[] strings = s.split(" ");
for(String str : strings) {
Integer counter = map.get(str.length())==null?0:map.get(str.length());
map.put(str.length(),counter++);
}
Integer sum=0;
Integer counter=0;
for(Integer len : map.keySet()) {
sum+=len*map.get(len);
counter+=map.get(len);
}
Double average = Double.valueOf(sum/counter);
Or you can combine the loops
Few suggestions which might help you (not related to the specific question).
Choose a meaningful class name rather than While_Loop .
Do, Scanner input = new Scanner(System.in); before the start of the loop.
As soon as you read each line, do the following.
Split the line using "\\s+" .
Create a HashMap with Key as Count (Integer) and Value as a list of Words with that count. Create this outside the loop.
For each split word,,get the length . and check if the map already contains the count, get the list (value), add he current word to it. else, add a new entry with the word as the single entry in the list.
Get the keySet of the map, add values of all keys i.e, *count * number of elements in the list*. then divide by total number of elements.
And yes, I know this is a very big change (something you might as well ignore..). But this is the right way to go.