Add and Subtract - java

I feel like I've tried everything, searched everything I know to search, and I've been working on this for about 6 classes now.
I'm trying to make a program that accepts a string input like "6 + 6 -3+ 2", and can add/subtract everything to output the correct answer. I got it to work with either addition or subtraction at one time (can't do anything like "6 + 6 - 3") and there also always have to be a space between any digit. It also can't add multi-digit numbers, but I'll worry about that once it can correctly add/subtract in the first place.
So I don't think I'm understand how Scanner and delimiters work, (since that's what the chapter is on) but I can't seem to find anything online that's helped me understand what I'm doing wrong.
This is what I have so far:
package addEmUp;
import java.util.*;
public class TesterShell {
public static void main(String[] args){
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter some addition/subtraction problem: ");
String s = kbIn.nextLine();
Scanner numChecker = new Scanner(s);
Scanner valueChecker = new Scanner(s);
numChecker.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*");
int sum = 0;
while(numChecker.hasNext()){
if(valueChecker.next().equals("-")){
sum = sum - numChecker.nextInt();
}
else{
sum = sum + numChecker.nextInt();
}
System.out.println(sum); //Just for checking what's going on, will remove in the end
}
System.out.println("Sum = " + sum);
}
}
Based on the other questions I've found on StackOverflow, a better way to do this would be to use index, but the Chapter I'm in set me up with a shell program using strings and scanner.
What am I missing here? What did I misunderstand/not understand at all?

For plain addition/subtraction you can do something simple like
String[] nums = s.replaceAll(" ", "").replaceAll("\\+", " ")
.replaceAll("-", " -").split(" ");
int res = 0;
for (String n : nums) {
if (!n.isEmpty())
res += Integer.parseInt(n);
}

Related

Matching user input against a string array in java?

I am incredibly new to java and have been given the following task:
Write a Java Program to prompt a user for a 3 letter body part name which has to be in the 'official' list of 3 letter body parts. (Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe)
If a user makes a guess correctly then display the correct guess as part of a list.
Allow the user to keep guessing until they have all 10.
If a body part is incorrect then display an appropriate message.
Display the number of guesses they have made including
the correct ones.
The advice given was to use Arrays and Collections as well as Exception Handling where appropriate but I don't know where to go from what I've coded so far. Any help would be appreciated so much, thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] bodyparts = new String [10];
bodyparts[0] = "Arm";
bodyparts[1] = "Ear";
bodyparts[2] = "Eye";
bodyparts[3] = "Gum";
bodyparts[4] = "Hip";
bodyparts[5] = "Jaw";
bodyparts[6] = "Leg";
bodyparts[7] = "Lip";
bodyparts[8] = "Rib";
bodyparts[9] = "Toe";
Set<String> bodypartSet = new TreeSet<>();
Collections.addAll(bodypartSet, bodyparts);
System.out.println("Please enter a 3 letter body part: ");
String bodypart = input.nextLine();
if (bodypartSet.contains(bodypart)) {
System.out.println("Correct, " + bodypart + " is on the list!");
} else {
System.out.println("Nope, try again!");
}
}
There are a lot of way to do this. The following, isn't the best or the most efficient, but it should work...
First of all, you have to put your "official" list in a structure, like an array:
private static String[] offList={Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe};
Now you have to write a method that can find a world in that "offList", like that:
private static boolean find(String word){
for( int i=0; i<offList.length; i++){
if(word.equals(offList[i])) //if "word" is in offList
return true;
}
return false;
}
Now, let's create this guessing game GUI:
public static void main(String[] args){
LinkedList<String> guessed=new LinkedList<>();
String s;
Scanner input = new Scanner(System.in);
while(guessed.size()<offList.length){
System.out.println("Guessed= "+guessed.toString()); //you have to change it, if you want a better look
System.out.print("Try:");
s=input.nextLine();
/*Here we ask to the user the same thing, unless the guessed list
contains all the words of offList.
Every time we print the guessed worlds list*/
if(find(s)){
System.out.println("This world is in offList!");
if(!guessed.contains(s)) //the world is counted only one time!
guessed.add(s);
}else
System.out.println("Sorry...");
}
System.out.println("The complete list is "+guessed.toString());
}
If you want to show this game in a window, you should have to study some Java Swing classes.
EDIT: I post my answer before the main post editing. First of all you have to understand the Collections advantages and usage... When you know all the LinkedList methods, for example, this assignment looks like a joke! ;)
You need a loop for that, otherwise it will only ask for input once.
Something like this should do:
ArrayList<String> bodyParts = new ArrayList<String>();
bodyParts.add("Arm");
bodyParts.add("Ear");
bodyParts.add("Eye");
bodyParts.add("Gum");
bodyParts.add("Hip");
bodyParts.add("Jaw");
bodyParts.add("Leg");
bodyParts.add("Lip");
bodyParts.add("Rib");
bodyParts.add("Toe");
String input = "";
int totalGuesses = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Start guessing...");
while (!bodyParts.isEmpty()) {
totalGuesses++;
input = sc.nextLine();
if (input.length() != 3 || !bodyParts.contains(input)) {
// incorrect, do nothing
System.out.println("Nope.");
} else {
// correct, remove entry
bodyParts.remove(input);
System.out.println("Correct! " + (10 - bodyParts.size()) + " correct guess" + ((10 - bodyParts.size()) != 1 ? "es" : ""));
}
}
System.out.println("Done. You have found them all after " + totalGuesses + " guesses.");
sc.close();
Also, this is case sensitive. It will not find Arm when typing arm. And if you need the number of all guesses you can simply add an int before the loop and increase it inside.
The result of my example:
Start guessing...
arm
Nope.
Arm
Correct! 1 correct guess
Arm
Nope.
Ear
Correct! 2 correct guesses
Eye
Correct! 3 correct guesses
(...)
Rib
Correct! 9 correct guesses
Toe
Correct! 10 correct guesses
Done. You have found them all after 12 guesses.

useDelimiter for any number of whitespace characters in combination with other delimiters?

I'm trying to make a program to just derive a user-entered polynomial. I'm trying to account for things like "3x2 + 5x4 + 3" instead of just "3x2+5x4+3". I currently have the delimiter setup as scan.useDelimiter("[A-Za-z\\s+-]");. I thought this would cover any letter, the + or - symbols, as well as ANY number of whitespace characters? But when I put the input as something like "3x2 + 5x4 + 3" the scanner just stops at that point when I'm using scan.nextInt().
I'll throw in the relevant parts of the code that I'm using to test stuff out. I'm sure there's much more efficient routes(maybe a HashMap, and removing the constant from the list, etc) but I'll worry about that after I get something like this figured out!
ArrayList<Integer> coeffArr = new ArrayList<>();
ArrayList<Integer> expArr = new ArrayList<>();
String polynomial;
Scanner scan = new Scanner(System.in);
System.out.println("Write your polynomial in the form of (coefficient)(variable)(exponent). (ie: 3x2 is 3x squared):");
polynomial = scan.nextLine();
scan = new Scanner(polynomial);
scan.useDelimiter("[A-Za-z\\s+-]");
while(scan.hasNextInt())
{
coeffArr.add(scan.nextInt());
if(scan.hasNextInt())
expArr.add(scan.nextInt());
}
if(coeffArr.size() != expArr.size())
constant = coeffArr.get(coeffArr.size()-1);
for(int i = 0; i < expArr.size(); i++)
{
System.out.print( (coeffArr.get(i) * expArr.get(i)) + "x" + (expArr.get(i)-1) + " ");
}
So essentially, if I put the input as "3x3+5x2+4" it will output "9x2 + 10x1", but if I were to do "3x3 + 5x2 + 4" all I'll get in the output is "9x2". How do I fix that and why does it happen?

How do I read a single text file and have the values placed into a cookie cutter sentence format?

Here's the content of the text file:
1 2 3 4 5 6 7 8 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
I want it to read and print out like this
The number ____ was at 00:00.
The number ____ was at 01:00.
and so on...
Here is what I have so far. I have found a lot about reading a .txt file but not much with how to take the info and format it in such a way.
One part of the code is for solving another objective which is to find the avg, min,, and max value. I just need help with the printing out the list format.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class NumberThingy {
public static void main(String[] args) throws IOException {
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
//Ask human for file name
System.out.println("Please enter the name of your data file with it's extension i.e Whatever.txt: ");
String fileName = in.next();
// Access the file provided
Scanner fileToRead = new Scanner(new File(fileName));
double Sum = 0;
int NumberOfEntries = -1;
double HighestValue = 0, LowestValue = 0;
boolean StillRecording = true;
double CurrentValue;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble())
{
NumberOfEntries++;
CurrentValue = fileToRead.nextDouble();
if (StillRecording)
{
HighestValue = CurrentValue;
LowestValue = CurrentValue;
StillRecording = false;
}
else
{
HighestValue = Math.max(HighestValue,CurrentValue);
LowestValue = Math.min(LowestValue, CurrentValue);
}
Sum += CurrentValue;
}
else
{
fileToRead.next();
}
}
System.out.println("Here are your resutlts:");
System.out.println("Minimum Temp = " + LowestValue);
System.out.println("Maximum Temp = " + HighestValue);
System.out.println("Average Temp: " + Sum/NumberOfEntries);
System.out.println("There are " + NumberOfEntries + " temp recordings.");
System.out.println("It dipped down to 32 F " + FreezeCounter + " times.");
}
}
Thank you for your time and patience! I'm a student and love this community's enthusiasm.
It seems like you do have a lot of good things in place already, but as you are new to these concepts I'd recommend breaking this program into small working examples--little "aha" success moments.
For example, with the Scanner class, hard-code in the file location and simply get it to print the values from the file.
Scanner fileToRead = new Scanner(new File("c:\\hard-coded-file.txt"));
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble())
{
System.out.println(fileToRead.nextDouble());
}
else
{
fileToRead.next();
}
}
Once you can do that, then add in your analysis logic. As of right now, it appears that your highest and lowest values will likely turn out to be the same value.
Lastly, consider reviewing the class and variable naming conventions for Java (you should do this for every language you work in) as, for example, standard variable names are written in camelCasing rather than PascalCasing as you have done.
EDIT/UPDATE
In regards to the cookie cutter format, I think you are on the correct track. To achieve what you are wanting, you will likely have to add a println statement within the while loop and print as you go, or you could experiment with something like a list of strings
LinkedList<String> outputStrings = new LinkedList<String>();
and adding the strings
outputStrings.add("The number ___ was at 00:00"));
to that list. You could then loop through the list at the end to print it all at once. Note that you may consider looking into String.format() to get leading zeroes on numbers.
Do you know about printf? Here is a cheatsheet I used when I was learning java.
https://www.cs.colostate.edu/~cs160/.Summer16/resources/Java_printf_method_quick_reference.pdf
System.out.printf("Today's special is %s!", "tacos");
Basically the method will replace whatever %s %f you have in the first string with the variables listed after the first string. It prints "Today's special is tacos!" You have to match the types right: %s is for string, %f for floating points.
Its all in the link.

Finding the index of each character in a substring

I feel like my logic is decent here; I don't feel like I'm completely lost. However, I do know what exactly I'm doing wrong. I can always find the index of the start of the substring, but I can never find the full count (ex. 3,4,5,6) of the index of whatever word the user enters as the substring.
I have been struggling with this for about a week trying to figure out how to do it on my own, I can't get it right.
import java.util.Scanner;
public class midterm
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
String simplePhrase;
String portionPhrase;
int portionIndex;
int portionCount;
int portionIndexTotal;
System.out.println("Enter a simple phrase:");
simplePhrase = keyboard.nextLine();
int phraseLength = simplePhrase.length();
System.out.println("Phrase length:" +phraseLength);
System.out.println("Enter a portion of previous phrase:");
portionPhrase = keyboard.nextLine();
String portionPhraseSub = simplePhrase.substring(portionPhrase);
portionIndex = simplePhrase.indexOf(portionPhraseSub);
for (portionIndex; portionIndex <= portionPhrase; portionIndex++)
{
System.out.println("Portion phrase index:"+portionIndex);
}
}
}
I'm still confused on what you want. There are just two simple things to know and you seem to be making this more complicated than it needs to be.
To get the index of a single character, such as "c" in the word "acorn", you would do this:
String s = "acorn";
int cIndex = s.indexOf("c");
System.out.println("The index of c is: " + cIndex);
If you want to see if the string contains a chunk, you use the exact same method. So if we are looking at the word "acorn" again and you want to see where "orn" happens, you'd do this:
String s = "acorn";
int ornIndex = s.indexOf("orn");
System.out.println("The index of orn is: " + ornIndex);
Remember that indexes start from 0 in java, so the index of "a" in "acorn" is 0, of "c" is 1, of "o" is 2, and so on.
I hope that helps. Good luck :)
EDIT: You just commented this:
"I guess, my question is one i get my code to compile, How would I go about counting every single letter of my substring?"
I'll answer that as best as I can, though again, that still is a confusing question.
What do you even mean by count" every letter? If you want to break your word into individual letters, you can do something like this:
String s = "acorn";
char[] characters = new char[s.length()-1];
for(int i = 0; i < s.length() - 1; i++) {
char[i] = s.charAt(i);
}
But I have no clue why you'd want to do that...you can always access any character in a string at a given index with STRING.charAt(index), or if you want to have a String result, STRING.substring(index, index+1)

Java text analysis program

The following requisites are those for the program I'm currently having an issue with:
The program must be able to open any text file specified by the user, and analyze the frequency of verbal ticks in the text. Since there are many different kinds of verbal ticks (such as "like", "uh", "um", "you know", etc) the program must ask the user what ticks to look for. A user can enter multiple ticks, separated by commas.
The program should output:
the total number of tics found in the text
the density of tics (proportion of all words in the text that are tics)
the frequency of each of the verbal tics
the percentage that each tic represents out of all the total number of tics
My program is working very well, but what I basically need to do is that I must use separate methods for each component of the analysis. So I think the idea is that I need to split up the program in a few parts, which I have done by using the comments // because I'm basically having problems determining which type I should return, I know the last part (// public static void output(){)
should definitely be void because it returns nothing and only prints out.
public static void main(String[] args) throws FileNotFoundException {
double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
int totalticks = 0;
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
// public static int[] initialise()
System.out.println("What words would you like to search for? (please separate with a comma)");
String ticks = sc.nextLine();
ticks = ticks.toLowerCase();
String[] keys = ticks.split(",");
int[] values = new int[keys.length];
// public static int[] processing(){?
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
values[x]+=1;
}
}
}
for (Integer u : values) {
totalticks += u;
}
//public static void output(){
System.out.println("Total number of tics :"+totalticks);
System.out.printf("Density of tics (in percent): %.2f \n", ((totalticks/totalwords)*100));
System.out.println(".........Tick Breakdown.......");
for (int z = 0; z<keys.length; z++){
System.out.println(keys[z] + " / "+ values[z]+" occurences /" + (values[z]*100/totalticks) + "% of all tics");
}
}
Essentially the problem I'm having is the scope of the variables because Eclipse (my IDE) no longer recognizes the variables within each method once I get them out of comments - I know I need to use some static variables but would really like a hand as to how I could hook my program up together using methods.
Thanks a bunch,
M
You should do an object (class) decomposition. First ask the question "What objects do I have". (At a quick glance you might have "Text" and "Ticks" objects. You then want to see what methods you want to use for each object. For example in Text have countTicks(Ticks). Conotinue in this fashion to decompose your program.
First, please indent your code more consistently, with the first line of a block three spaces farther to the right, such as
for(...) {
//Do stuff
if(...) {
//Do stuff
}
}
It is hard to read what you've posted (luckily someone spruced it up for you!).
Consider re-writing your program from scratch, instead of trying to fix what you already have. Your current knowledge of the problem should allow you to recreate it pretty quickly. You will probably be able to cut and paste bits and pieces from your original code as well.
How about starting small, with something like
Scanner sc = getInputScannerFromUserInput();
private static final Scanner getInputScannerFromUserInput() {
System.out.println("What file would you like to open?");
return new Scanner(System.in);
}
and just go from there. Bit by bit. Good luck!

Categories

Resources