How to use a sorting algorithm in Java? - java

My assignment is to ask a user for the number of strings he would like to input. Then i will prompt him to right the strings. Then i am supposed to print the stings in alphabetical order. I got most of the assignment done, just need a sorting algorithm such as Bubble sort to finish it. this is my code.
import java.io.*;
public class sorting
{
private static BufferedReader stdin=new BufferedReader(new InputStreamReader( System.in));
public static void main(String[] arguments) throws IOException
{
System.out.println("How many strings would you like to enter?");
int stringCount = Integer.parseInt(stdin.readLine());
String[] stringInput = new String[stringCount];
for(int i = 0; i < stringCount; i++)
{
System.out.print("Could you enter the strings here: ");
stringInput[i] = stdin.readLine();
}
//Now how do i use a sorting algorithm?
}
}

Arrays.sort().

Use Rhino as a Javascript parser so you can include jQuery into your project. Then sorting becomes trivial as you can just load the Strings into a <table> and run this nifty plugin on it.
^ DO NOT DO THIS. (well if you do, post the source and tell us what grade you got on the assignment ;)
No really, just write bubble sort by yourself. It's not that long. You probably learned the pseudocode in class. If you need an additional reference, take a look at the Wikipedia article on it. If there's something in particular that you don't understand about the algorithm, post a specific question and we'll help you out. Other than that, you look like you're on the right track so far :)

If this wasn't an exercise you'd just use Arrays.sort(stringInput)

import java.io.*;
import java.util.*;
public class sorting
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
System.out.print("How many strings would you like to enter? ");
String[] stringInput = new String[Integer.parseInt(input.nextLine())];
for(int i = 0; i < stringInput.length; i++)
{
System.out.print("Could you enter the strings here: ");
stringInput[i] = input.nextLine();
}
Arrays.sort(stringInput);
for(String s : stringInput) System.out.println(s);
}
}

It seems to me that you are not being asked to sort the string array, but to print the strings in alphabetical order, which is likely to be a whole lot uglier but a whole lot simpler.
Once the user has typed all of the input strings, you might choose to iterate over the array stringCount times finding, in each iteration, the lowest-valued string; printing it; and then clearing it so that you won't see it in the next iteration.
BUT if you really are being asked to apply a bubble sort (or any kind of sort) on the array, well, that's a whole 'nother question, namely: how do I write a bubble sort for an array of strings. That's a tricky problem for anyone because the strings in the array are of differing lengths: they cannot just be swapped blindly but have to be written into some temp array somewhere that somehow knows how to accomodate their various lengths.
EDIT: Oh, wait a sec: maybe Java knows all about variable-length strings and how to handle them. If so, I take it all back.

Just use the Set str = TreeSet();
then loop through the string str.add("z");
when you iterate the str variable it is automatically sorted.

Related

Want to programm calculator, want to change String into real operator

I want to code a simple calculator and already got some code. But now I want to change the String I got there into an Operator. For example:
My input is: "1,5 - 1,1 + 3,2 ="
Now I have a double array and a String array.
So after that I want to put it together, so it calculates this complete task.
double result = double[0] String[0] double[1] ....
I hope you can help there, and I apologize for my grammar etc., english is not my main language.
import java.util.*;
public class calculator
{
public static void main(String[] args)
{
int a = 0;
int b = 0;
double[] zahl;
zahl = new double[10];
double ergebnis;
String[] zeichen;
zeichen = new String[10];
Scanner input = new Scanner (System.in);
while (input.hasNext())
{
if (input.hasNextDouble())
{
zahl[a] = input.nextDouble();
a++;
}
else if (input.hasNext())
{
zeichen[b] = input.next();
if (zeichen.equals ("=")) break;
b++;
}
}
input.close();
}
}
If I type in: "1,5 + 2,3 * 4,2 =" I want to get the result with point before line and without .math
What you want to do is parse a single String and convert it into a mathematical expression, which you then want to resolve and output the result. For that, you need to define a "language" and effectively write an interpreter. This is not trivial, specifically if you want to expand your syntax with bracketing and thelike.
The primary question you have to answer is, whether you want to use a solution (because you are not the first person to attempt this) or if you want to actually write this yourself.
There are "simple" solutions, for example, you could instantiate a javascript engine in Java and input your string, but that would allow much more, and maybe even things you don't want. Or you could use a library which already does this. This Thread already answered a similar question with multiple interesting answers:
How to evaluate a math expression given in string form?
Otherwise, you might be in for a surprise, concerning the amount of work, you are getting yourself into. :)

Hackerrank Java Map Question Timeout Problem

I have solved hackerrank Java Map Problem but I had timeout result for 2 cases. When I changed just the printf line problem solved. However I could not understand why it is ? Here my code:
import java.util.*;
import java.io.*;
class Solution{
private static HashMap<String, Integer> phoneBook = new HashMap<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String search = "";
int n=in.nextInt();
in.nextLine();
for(int i=0; i<n; i++) {
String name=in.nextLine();
int phone=in.nextInt();
phoneBook.put(name, phone);
in.nextLine();
}
while(in.hasNext()) {
search = in.nextLine();
if (phoneBook.get(search) != null)
System.out.printf(search + "=" + phoneBook.get(search) + "\n"); // this works
// System.out.printf("%s=%d\n", search, phoneBook.get(search)); // this does not work why ?
else
System.out.println("Not found");
}
}
Formatter.format() takes time
Formatter.format() (and its shortcut System.out.printf()) requires parsing, validating and formatting. All that takes a huge amount of time.
So just dump the data as quick as possible. Hackerrank requires you to make fast programs, so just do that: a fast program. Concatenate your items instead of formatting them. Also, if you have no parameter, just use System.out.println() instead of System.out.printf.
When you do a formatting output, java parses the string to format ("%s=%d\n" in your case) to put values instead placeholders. It takes at least O(n) complexity, which is important in your case.
Also you call phoneBook.get(search) twice. Try to keep the result in a variable. It also can speed up the program.
To break the string into separate lines, we need to use %n specifier in printf statement.
System.out.printf("%s=%d%n", search, phoneBook.get(search));
OR you can use the String.format() shown in the below statement.
System.out.println(String.format("%s=%d",s,p));
Short Answer: Lookup performance of Hashmap + Formatting the fetched value from the HashMap was computationally more Intensive than just concatenating the string without any format.
To be a bit verbose, the HashMap Implementation which is designed for an amortized complexity of O(1) for get(Key) functions does have a nasty complexity of O(n) (stressing the term worst case :) ) if either all or most of the keys share a common hash. Such occurrences, although not very common would've occurred when the test case feeder gave an enormous test case input with multiple duplicate values. Such a situation combined with simultaneous formatting would've resulted in a crash.

Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.
//.....
Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;
String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}
}
This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!
Don't know how to stablish a dynamic string[] length, letting the user establish the string[].length
It is not necessary to do that. But here's how.
Approach #1: ask the user to give you a number and then allocate the array like this:
String[] strings = new String[theNumber];
Warning: the requirements don't say you are allowed to do that, and you may lose marks for deviating from the requirements.
Approach #2: use an ArrayList to accumulate a list of words, the use List.toArray to create an array from the list contents. (Read the javadocs for list to work it out.)
Of course, error here, just did it to put one System.out.print of how should the result be.
Yea. One problem is that the length is 1000, but you don't have 1000 actual strings in the array. The same problem affects your earlier code too. Think about is ...
I'm not going to fix your code to make it work. I've given you enough hints for you to do that for yourself. If you are prepared to put in the effort.
One more hint: you can / should use break to break out of the first loop.
I know some words are not in English but in Catalan, but the code can be perfectly understood, yesterday I finally programmed this answer:
public static void main(String[] args) {
Scanner entrada= new Scanner(System.in);
System.out.println("Escriu les paraules que vulguis, per acabar, usa la paraula 'fi'.");
String paraules = "";
int c=0;
do {
String paraula = entrada.next();
if (paraula.equals("fi")) {
c++;
} else {
if (paraula.compareTo(paraules) > 0) {
paraules = paraula;
}
}
} while (c==0);
System.out.println("L'última parala ordenada alfabèticament és "+paraules+".\n");
}
}

Breaking up a string in Java into a string array

I've researched this subject thoroughly, including questions and answers on this website....
this is my basic code:
import java.util.Scanner;
class StringSplit {
public static void main(String[] args)
{
System.out.println("Enter String");
Scanner io = new Scanner(System.in);
String input = io.next();
String[] keywords = input.split(" ");
System.out.println("keywords" + keywords);
}
and my objective is to be able to input a string like "hello, world, how, are, you, today," and have the program break up this single string into an array of strings like "[hello, world, how, are, you, today]...
But whenever i compile this code, i get this output:
"keywords = [Ljava.lang.String;#43ef9157"
could anyone suggest a way for the array to be outputted in the way i require??
Sure:
System.out.println("keywords: " + Arrays.toString(keywords));
It's not the splitting that's causing you the problem (although it may not be doing what you want) - it's the fact that arrays don't override toString.
You could try using Java's String.Split:
Just give it a regular expression that will match one (or more) of the delimeters you want, and put your output into an array.
As for output, use a for loop or foreach look to go over the elements of your array and print them.
The reason you're getting the output you're getting now is that the ToString() method of the array doesn't print the array contents (as it would in, say, Python) but prints the type of the object and its address.
This code should work:
String inputString = new String("hello, world, how, are, you, today");
Scanner scn = new Scanner(inputString);
scn.useDelimiter(",");
ArrayList<String> words = new ArrayList<String>();
while (scn.hasNext()) {
words.add(scn.next());
}
//To convert ArrayList to array
String[] keywords = new String[words.size()];
for (int i=0; i<words.size(); ++i) {
keywords[i] = words.get(i);
}
The useDelimiter function uses the comma to separate the words. Hope this helps!

Java, how to compare Strings with String Arrays

I have been searching here for some time but haven't been able to find the answer to it.
I am basically required to use an array for this assignment from college. And then I am supposed to check that the input (which is also a String) matches whatever's stored within the String array.
I know one can easily compare Strings by using the .equals() method. However, the same method is not working with the String array.
I created the following example of code for the purpose of StackOverflow so you can use it to explain it to me, if you'd like.
What am I doing wrong?
import java.util.Scanner;
class IdiocyCentral {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
/*Prints out the welcome message at the top of the screen*/
System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf("%55s", "=================================\n");
String [] codes = {"G22", "K13", "I30", "S20"};
System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
System.out.printf("Enter one of the above!\n");
String usercode = in.nextLine();
if (codes.equals(usercode)) {
System.out.printf("What's the matter with you?\n");
}
else {
System.out.printf("Youda man!");
}
}
}
I apologize if this has been asked before and I just missed it, if its a double question, I will remove it.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.
if(Arrays.asList(codes).contains(userCode))
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
Iterate over the codes array using a loop, asking for each of the elements if it's equals() to usercode. If one element is equal, you can stop and handle that case. If none of the elements is equal to usercode, then do the appropriate to handle that case. In pseudocode:
found = false
foreach element in array:
if element.equals(usercode):
found = true
break
if found:
print "I found it!"
else:
print "I didn't find it"
If I understand your question correctly, it appears you want to know the following:
How do I check if my String array contains usercode, the String that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
Instead of using array you can use the ArrayList directly and can use the contains method to check the value which u have passes with the ArrayList.
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}

Categories

Resources