Addition Using Stacks? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I want to add a pair of numbers that are separated by a space. So a user inputs multiple numbers of any length separated by a space. I'm using BigInteger for this. Using two stacks, each pair of numbers must be added together and the results need to be printed out. For example, the output would be like this:
10
+ 10
= 20
99
+ 1
= 100
1000000000000000000000000000000
+ 1000000000000000000000000000000
= 2000000000000000000000000000000
I need to use stacks to do this. This is what I have so far but I'm not sure where to go after this.
public static void main (String[] args)
{
Stack<BigInteger> stack = new Stack<BigInteger>();
System.out.println("Please write some pairs of numbers to add separated by a space: ");
Scanner input = new Scanner(System.in);
for (BigInteger number : input.nextLine().split(" "))
{
for (int i = 0; i < number.length(); i++)
{
stack.push(number);
}
while (!stack.isEmpty()) {
reverseInput += stack.pop();
}
}
}

You don't need inner for loop. If you are trying to add two numbers using stack, you can push them into Stack, pop and add to the result, e.g.:
Stack<BigInteger> stack = new Stack<BigInteger>();
System.out.println("Please write some pairs of numbers to add by a space: ");
Scanner input = new Scanner(System.in);
for (BigInteger number : input.nextLine().split(" "))
{
BigInteger result = new BigInteger("0");
while (!stack.isEmpty()) {
result.add(stack.pop());
}
System.put.println("Result : " + result);

First of all,
for (BigInteger number : input.nextLine().split(" "))
Isn't going to work, because that .split() returns an object of type String[], and you can't directly treat String asBigInteger.
Also, you're doubling up on your for loops. That line I copied above, if it worked the way you wanted, would loop through all of the numbers in your input. So there's no need for that inner for loop. In fact, it won't even compile, since BigInteger doesn't have a .length() method.
But you're on the right track. What you can do is tokenize the input like you're already doing, and push each element into a the stack as-is. Because there's no need to push them into the stack as BigInteger. You can have a Stack<String>, and then convert them into BigInteger when you pop them back off to do the addition. Or alternatively, convert them to BigInteger as you push each one onto the stack.

input.nextLine().split(" ");
returns a String[], you cannot automatically cast it to BigInteger[], as that will throw a ClassCastException.
Do you allow decimal values? If so, you'd be better off converting each String element to a primitive double representation, as you won't need the additional precision offered by BigDecimal.
As decimal values won't be allowed, you'd want to convert the String to its integer representation.
for (final String s : input.nextLine().split(" ")) {
final int value = Integer.parseInt(s);
stack.push(value);
}
The stack generic type will be Integer. So Stack<Integer>
Have you considered the case of bad user input? In that case you need to handle a NumberFormatException

Related

Java How to Read Data From a String (stringstream equivalent) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Let's say I have a String (call it s) with the following format:
[String] [String] [double] [int]
for example,
"YES james 3.5 2"
I would like to read this data into separate variables (a String, a String, a double, and an int)
Note that I come from a C++ background. In C++, I would do something like the following:
std::istringstream iss{s}; // create a stream to the string
std::string first, second;
double third = 0.0;
int fourth = 0;
iss >> first >> second >> third >> fourth; // read data
In Java, I came up with the following code:
String[] sa = s.split(" ");
String first = sa[0], second = sa[1];
double third = Double.parseDouble(sa[2]);
int fourth = Integer.parseInt(sa[3]);
However, I will have to do this to many different inputs, so I would like to use the most efficient and fastest way of doing this.
Questions:
Is there any more efficient/faster way of doing this? Perhaps a cleaner way?
Try it like this. Scanner's constructor can take a string as a data source.
Scanner scan = new Scanner("12 34 55 88");
while (scan.hasNext()) {
System.out.println(scan.nextInt());
}
prints
12
34
55
88
As it has been mentioned in the comments, if this is coming from keyboard (or really from an input stream) you could use Scanner class to do so. However, from input sources other than keyboard, I will not use Scanner but some other method to parse strings. For example, if reading lines from a file, you may want to use a Reader instead. For this answer, I will assume the input source is the keyboard.
Using Scanner to get the input
Scanner scanner = new Scanner(System.in);
System.out.print("Provide your input: ");
String input = scanner.nextLine();
input.close();
Break the String into tokens
Here you have a few options. One is to break down the string into substring by splitting the input using white space as a delimeter:
String[] words = input.split("\\s");
If the order of these substrings is guaranteed, you can assign them directly to the variables (not the most elegant solution - but readable)
String first = words[0];
String second = words[1];
double third = words[2];
int fourth = words[3];
Alternatively, you can extract the substrings directly by using String#substring(int) and/or String#substring(int, int) methods and test whether or not the obtained substring is a number (double or int), or just simply a string.

convert String to arraylist of integers using wrapper class

Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.
String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();
System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();
for (int i = 0; i < userString.length(); i++) {
userInts.add(new Integer(in.nextInt()));
}
If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.
If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.
Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.
Lets look at the lines:
String userString = ""
int[] userInt = new int[userString.length()];
At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.
Also this is an array not an arrayList. An arrayList would look like
ArrayList<Integer> myList = new ArrayList()<Integer>;
I'm assuming the in is for a Scanner.
I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.
List<Integer> arr = new ArrayList<Integer>();
while(in.hasNext())
arr.add(in.nextInt());
And, say you know that you will get 10 numbers..
int count = 10;
while(count-- > 0)
arr.add(in.nextInt());
Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.
5
3 20 602 3 1
The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.
This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.

Coding Challenge in Java: Given Letters and Returning What Rank They are in [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hey so for practice I found this coding challenge which I have now been working on for a few days. I have the first part, but I just can't seem to figure out how to continue from where I am. Here is the challenge:
Consider a "word" as any sequence of capital letters A-Z (not limited to
just "dictionary words"). For any word with at least two different letters,
there are other words composed of the same letters but in a different order (for
instance, STATIONARILY/ANTIROYALIST, which happen to both be dictionary words;
for our purposes "AAIILNORSTTY" is also a "word" composed of the same letters as
these two).
We can then assign a number to every word, based on where it falls in an
alphabetically sorted list of all words made up of the same set of letters. One
way to do this would be to generate the entire list of words and find the
desired one, but this would be slow if the word is long.
Write a program which takes a word as a command line argument and prints to
standard output its number. Do not use the method above of generating the entire
list. Your program should be able to accept any word 20 letters or less in
length (possibly with some letters repeated), and should use no more than 1 GB
of memory and take no more than 500 milliseconds to run. Any answer we check
will fit in a 64-bit integer.
Sample words, with their rank:
ABAB = 2
AAAB = 1
BAAA = 4
QUESTION = 24572
BOOKKEEPER = 10743
NONINTUITIVENESS = 8222334634
Your program will be judged on how fast it runs and how clearly the code is
written. We will be running your program as well as reading the source code, so
anything you can do to make this process easier would be appreciated.
So far, the code I have can return the correct answer if all of the letters are different. Here is my code:
import java.util.Arrays;
import java.util.Scanner;
public class AthenaDility {
public static void main (String[] args) {
//Finds word that is entered
Scanner scan = new Scanner (System.in);
String word = scan.next();
scan.close();
//added value
int value = 1;
//alphabetical representation
char[] charm = word.toCharArray();
char[] alphaCharm = word.toCharArray();
Arrays.sort(alphaCharm);
//Comparer
for (int m = 0; m < word.length(); m++) {
for (int c = 0; c < word.length()-1; c++) {
System.out.println(charm[m] + " " + alphaCharm[c]);
//Skips if alphaCharm is a space
if (alphaCharm[c] == '-') {
}
//If the same letter it breaks look and begins next
else if (charm[m] == alphaCharm[c]) {
System.out.println("Deleting: " + alphaCharm[c]);
alphaCharm[c] = '-'; //Delete letter for it is used and cannot be used to compare at later points
break;
}
//if the letter in alphaCharm comes before charm
else if (charm[m] > alphaCharm[c]){
System.out.println("Found!");
//factorial calculation
int factorial = 1;
//takes the length of the word minus the current location and one after for factorial
for (int f = word.length() - m - 1; f > 0; f--) {
System.out.print(f + " ");
factorial *= f;
}
//end loop
//Adding to others
System.out.println("\n" + "Factorial: " + factorial);
value += factorial;
}
else {
}
}
}
//Result
System.out.println("end: " + value);
}
}
To try and explain it as simply as I can, it creates two strings: one is the letters in alphabetical order and one is the original word. The program then compares each letter at a time and any letter that comes before the one in the original word alphabetically causes a factorial calculation for the number of combinations that would exist before the first word.
The part I need help factoring in is if the strings entered have more than one of the same letter. I have literally spent DAYS trying to figure this out. Thank you in advance!
p.s. the code has a lot of System.out.println for testing sake

Taking an element of An ArrayList and passing it as an argument [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am having a bit of a hiccup with this ArrayList. I am trying to store one or more elements from a String array into an Array list and assigning it to some string variable. My goal is to store keywords into an array list which i could use to search a text file. I can't seem to store found keywords into the array list Can someone help me figure this issue out? Here's some snippets from my code.
public static void main(String args[]) throws ParseException, IOException
{
List<String> matches = new ArrayList<String>();
String[] keywords = {"day", "book", "office", "hour",
"date of a test", "number of assignments", "sure",
"current assignment", "due day"};
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
int count = 0;
for (int i = 0; i < keywords.length; i++) {
if (input.contains(keywords[i])) {
matches.add(keywords[i]);
parseFile(keywords[i]);
}
}
}
And here is my parseFile method
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
// break;
}
}
}
One of the first things I'd do, is check that the stuff is actually going in to the array, so I'd have this:
if(matches.size() == 0)
{
System.out.println("There's nothing in here");
}
That way at least you know that there's nothing there, so then there's no point doing the rest of the program. You should always test your exit condition early where possible that way you save a bit of time, and energy, and allows for quicker debugging. But I digress.
So to add the stuff in to the array list you'd need to do the following:
for (int i = 0; i < keywords.length; i++)
{
String value = keywords[i];
System.out.println("Current Value is: " + value);
matches.add(value);
}
You can't just add an array element as the add method in ListArray is expecting a String. So you need to set the current content of the array to a String then pass THAT in to your matches.add function as above, so when I ran that program on my box, (just the main bit that is) I got the following output.
Current Value is: day
Current Value is: book
Current Value is: office
Current Value is: hour
Current Value is: date of a test
Current Value is: number of assignments
Current Value is: sure
Current Value is: current assignment
Current Value is: due day
Size of matches is: 9
Matches[i]: day
Matches[i]: book
Matches[i]: office
Matches[i]: hour
Matches[i]: date of a test
Matches[i]: number of assignments
Matches[i]: sure
Matches[i]: current assignment
Matches[i]: due day
Also for the record, you need to do the same when you're iterating through your matches as well, so let's say you want to print out your ArrayList, then you'd need to do the following:
for(int i = 0; i < matches.size(); i++)
{
String value = matches.get(i);
System.out.println("Matches[i]: " + value);
}
You'd need to get the string within the array list, you can't just give it an index, as that will not work, again you need to assign it to a string and then pass that back.
If in doubt, dive on to the Java ArrayList API, and have a look at what arguments the functions take.
Hope that helps.

if i entered numbers separated with commas, how could i extract the numbers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
for example....
26, 15, 37
how could i get the numbers from a Scanner , ( lets say for instance i want to add or subtract,,,?)
Take a look at String.split().
If you want to use the Scanner API:
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
for (;;) {
integers.add(scanner.nextInt());
if (scanner.hasNext(COMMA_PATTERN)) {
// Read and discard comma token, and continue parsing list.
scanner.next();
} else {
// Number is not followed by comma, stop parsing.
break;
}
}
return integers;
}
More error handling is needed, but hopefully, this example illustrates the approach.
You can also use Scanner.useDelimiter():
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter(COMMA_PATTERN);
while (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
// Reset delimiter
scanner.useDelimiter(oldDelimiter);
return integers;
}
Use Scanner.useDelimiter. It actually takes regex, so you'd want to learn some basics.
String text = "1 , 2 3, 4,5";
Scanner sc = new Scanner(text).useDelimiter("\\s*,?\\s*");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
} // prints "1", "2", "3", "4","5"
See also
http://www.regular-expressions.info/ -- the best tutorial resource
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Using hasNextInt() to prevent exception is much better than Integer.parseInt and catch NumberFormatException
String.split() is OK, but StringTokenizer works everywhere and in every version of Java.
StringTokenizer st = new StringTokenizer("26, 15, 37", ", ");
int sum = 0;
while (st.hasMoreTokens()) {
sum += Integer.parseInt(st.nextToken());
}
Try to set a delimiter for your scanner object:
Scanner s = new Scanner(System.in).useDelimiter(", *");
int first = s.nextInt();
int second = s.nextInt();
...
More examples can be found in Scanner documentation.
Look at useDelimiter. You need a regex that will match either whitespace or commas.

Categories

Resources