Can not figure out how get certain inputs to work? - java

I am making a post fix calculator and i can not figure out how to do functions without having an equal sign. For example " a = 3 5 + " will print 8 , but " 3 5 + " will make the program crash. Here is what i have so far
if (values.peek().matches("[a-z]") || values.search("=") > -1 )
{
String a = values.pop();
values.pop();
double answer = compute(values);
memory.put(a, answer);
var.add(a);
System.out.println(" " + answer);
}
else
{
double answer = compute(values);
System.out.println(answer);
}

I guess your parsing of input has some problem. If you want to split the input by space, try this way:
String str = " 3 5 + ";
String[] splited = str.split("\\s+");
Inspired by the first answer of this question:

Related

Print the formula used to describe the addition of two numbers

I am stuck in the U of Helsinki Java MOOC:
Create a program that can be used to add two integers together. In the beginning, the user is asked to give two integers that are to be summed. The program then prints the formula that describes the addition of the numbers.
Example output:
Give the first number:
5
Give the second number:
4
5 + 4 = 9
I am trying to get the system to print " "first" + "second" is "result". For some reason I am stumped on this otherwise easy question. My code is always throwing an error. What am I doing wrong in the last line?
import java.util.Scanner;
public class AdditionFormula {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// write your program here
System.out.println("Give the first number: ");
int first = Integer.valueOf(scanner.nextLine());
System.out.println("Give the second number: ");
int second = Integer.valueOf(scanner.nextLine());
//System.out.println("first" " + " Integer.valueOf(first) + Integer.valueOf(second));
System.out.println(first + " + " + second " = " + (first + second));
}
The code you provided does not compile
Change to
System.out.println(first + " + " + second + " = " + (first + second));

How to only add something to a string if it doesn't contain it?

I am making a Lipogram program where any words with the banned letter are printed, however, the words are sometimes printed twice. How do I get it to not repeat the words?
Here is my code:
public String allWordsWith(char letter) {
String str = "";
String word = "";
s = s.replace(".", " ");
s = s.replace(",", " ");
s = s.replace("?", " ");
s = s.replace("!", " ");
s = " " + s + " ";
for (int i = 0; i <= s.lastIndexOf(letter); i++) {
if (s.charAt(i) == letter) {
if (str.contains(s.substring(s.lastIndexOf(" ", i), s.lastIndexOf(" ", i) + 1) + '\n') == true) {
} else {
word += s.substring(s.lastIndexOf(" ", i), s.indexOf(" ", i)) + '\n';
str += word;
}
}
}
return str;
}
Important clarification: Is the function run with the letter chosen as "o" on the string "hello hi hello howdy" meant to return "hello hello howdy" or "hello howdy". I.e., if the word appears twice, do you want to print it twice, or do you only want to print it once regardless of repetition?
If only once regardless of repetition, then you should be using a Set to store your data.
However, I think there's a chance you're instead dealing with an issue that when running the function with the letter chosen as "l" on that same string, "hello hi hello howdy", you are getting an output of "hello hello hello hello". Correct?
The issue here is that you are checking every letter and not testing each word. To fix this, I would use:
String[] words = s.split(" ");
to create an array of your words. Test each value in that array to see if it contains the given letter using:
if(words[index].contains(letter)){
str += " " + words[index];
}

an array does not get a value

I have a problem with the following code
public static void SideBet(int numberDice,int bet,int money) {
System.out.println("You established a " + "\""+ "point" + "\"" + ". " + "Your " + "\""+ "point" + "\"" + " is " + numberDice + ". " + "You have to roll a(n) " + numberDice + " to win your bet, "+ bet +" chips." );
System.out.println();
System.out.println("You can put side bets for 4,5,6,8,9 or 10.");
SideBetChoice = Console.readLine("Would you like to make any side bets ? (Type " + "\""+ "Yes" + "\"" + " or "+ "\""+ "No" + "\"" + ", then hit Enter.)");
int s = 0;
int r = 0;
if (SideBetChoice.equals("Yes")) {
System.out.println("You can put as many side bets as you would like for the numbers 4,5,6,8,9 or 10.");
int SideBetNumber = Console.readInt("How many side bets would you like to make ? (Introduce a number, minimum 1, maximum 6.)");
int[] SBNArray = new int[SideBetNumber];
int[] sbArray = new int[SideBetNumber];
for (s = 0; s <= (SideBetNumber -1) ; s++) {
SBNArray[s] = Console.readInt("On which number would you like to put a side bet ?");
sbArray[s] = Console.readInt("Currently you have " + money + " chips, how much would you like to bet ?");
money = money - sbArray[s];
System.out.println("Thank you for your " +sbArray[s]+ " chip side bet on number " +SBNArray[s]+".");
System.out.println();
}
}
if (SideBetChoice.equals("No")) {
return;
}
sbArray and SBNArray does not get a value and it keeps crashing ...
Can anyone help me out and tell me what is wrong, why the 2 arrays do not get a value, therefor they are null ?
There is no readInt()-method in Console.
Also I'm not sure if you're using console correctly, it should look like this:
Console console = System.console();
console.readLine("Type something");
Just use readLine() and convert it to an int:
Console console = System.console();
String input = console.readLine("Type a number");
try
{
int myNumber = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.println("This ain't a number!");
}
Also please never use Capital Letters for Variables' Names or method-names, it's very confusing because you could think it would be a Class or a Type.
So please change the name of SBNArray and SideBetNumber, SideBetChoice etc. etc.
Only Constants should be written with only Capital Letters and Classes and Types start with Capital Letters.
EDIT:
Sorry, it seems that you're using BreezyGUI.Console, therefore there is a readInt()-method.
Could you give more information?
I'd like to know if the text of the readInt() is even displayed.

Trouble reading next int

(original question, already answered)
I want a program to read integers from a text file. The data file looks like this:
5 4
3 5
4 5
3 2
The first number of each row is the par, and the second number is the score. Because 5 - 4 = 1, the score is one under par (which is a birdie). My code for the first line:
in = new Scanner (dataFile);
System.out.println("Golf Scores: ");
String line1 = in.nextLine();
System.out.println("Score 1: " + line1);
int par1 = in.nextInt();
System.out.println("Par is: " + par1);
When I run it, I get this:
Golf Scores:
Score 1: 5 4
Par is: 3
So the par and score shows up correctly. However, the displayed par shows the par of the next line from the text file. I want it to show "5" again. I tried putting the in.nextInt before the in.nextLine, but when I tried that I got this
Golf Scores:
Score 1: 4
Par is: 5
Also please let me know if I need to add anything to explain my question better.
You can't "rewind" the scanner, once you've read the line, it's gone and you can't read from it again. You can try something like this:
int par = in.nextInt();
int score = in.nextInt();
System.out.println("Score: " + par + " " + score);
System.out.println("Par is:" + par);
Here, we're reading and storing the two integers separately to begin with, and displaying them just after.
You shouldn't care if it's an int (although it's always an int - in your case) so you don't have to bother using nextInt():
String line = in.nextLine();
String[] nums = line.split(" ");
System.out.println("score: " + nums[0]/*par*/ + " " + nums[1]/*score*/);
System.out.println("par is:" + nums[0]);
You could read the line the split it like so
String line1 = in.nextLine();
String[] parScore = line.split(" ");
System.out.println("Score 1: " + parScore[1]);
System.out.println("Par is: " + parScore[0]);

I do not know why I keep on getting strange feedback when I am trying to format phone numbers from a user in java.

Whenever I type in a phone number, this program below that I wrote to format phone numbers from the user gives me back weird numbers that I did not even enter at all. Can someone please explain to me why I am getting such weird errors?
I want it so when someone enters just 12345678978 it will format to 1-234-567-8978
If they enter 2345678978 it will format to 234-567-8978
And if they enter 5678978 it will change to 567-8978.
I always get weird numbers that sometimes aren't even what I entered like
12345678978 I get 144-34--567-
2345678978 I get 153-567-8978
5678978 I get 162-8978
I would really appreciate some help. Thanks.
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner y = new Scanner(System.in);
String phoneNumber;
int phoneNumberLength;
System.out.print
("Please enter your phone number WITHOUT spaces or dashes: ");
phoneNumber = y.nextLine();
phoneNumberLength = phoneNumber.length();
if (phoneNumberLength == 11) {
phoneNumber = phoneNumber.charAt(0) + "-" + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ phoneNumber.charAt(3)
+ "-" + phoneNumber.charAt(4) + phoneNumber.charAt(5)
+ phoneNumber.charAt(6)
+ "-" + phoneNumber.charAt(7) + phoneNumber.charAt(8)
+ phoneNumber.charAt(9)
+ phoneNumber.charAt(10);
}
if (phoneNumberLength == 7) {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5) + phoneNumber.charAt(6);
}
else {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5)
+ "-" + phoneNumber.charAt(6) + phoneNumber.charAt(7)
+ phoneNumber.charAt(8)
+ phoneNumber.charAt(9);
}
System.out.println("So your phone number is " + phoneNumber + "?");
}
By the way. I know it is not formatted correctly but I am very confused with how stackoverflow allows you to add code.
Java is converting the characters from your charAt() calls to numerical values. Use substring methods instead, e.g.
phoneNumber = phoneNumber.substring(0, 3) + "-" + phoneNumber.substring(3);
Any string that starts like this:
number = number.charAt(0) + number.charAt(1) + ...
will cause the problem, because you are adding two char types together. This is treated as integer arithmetic, not string concatenation. It would be a lot better to add substrings together, so that the operator is string concatenation, instead of integer addition.
number = number.substring(0, 3) + '-' + number.substring(3, 6) + ...

Categories