Can't detect 2 digit numbers when converting from RPN to Infix - java

i am trying to implement a java method which accepts an input in RPN (Reverse Polish Notation) and through use of a stack converts it into an infix notation and calculates it. I have built the stack and a working converter but i am finding problems when it comes to accepting multiple digit numbers (such as 10), my idea to solve this was to enter each separate entity separated by a space, 10+20 would be entered as "10 20 +" but this is resulting in an out of bounds error. Without the section marked below the program works fine for equations such as "12+" (1+2) and more complex ones as long as they involve single digit values. The stack is fully functiopnal too with push and pop methods
public static void stackRPN(){
Stack myStack = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("Enter an equation: ");
String eq = sc.nextLine();
int len = eq.length();
for (int i = 0; i < len; i++){
String car1 = String.valueOf(eq.charAt(i));
if ("+".equals(car1) || "-".equals(car1) || "/".equals(car1) || /*"car1"*/"x".equals(car1)){
String a = myStack.pop();
String b = myStack.pop();
//This handlws all the digits
double bI = Double.parseDouble(b);
double aI = Double.parseDouble(a);
double finalNo = 0;
switch (car1) {
case "+": finalNo = bI + aI;
break;
case "-": finalNo = bI - aI;
break;
case "/": finalNo = bI / aI;
break;
case "x": finalNo = bI * aI;
break;
}
myStack.push(finalNo+"");
String finEq = b+car1+a;
System.out.println(finEq + " = " +finalNo);
} else {
This bit does not work
while (len < i+1 && eq.charAt(i+1) != ' '){
car1 = car1+eq.charAt(i+1);
i++;
}
Till here
myStack.push(car1);
}
}
mainMenu();
}

This was fixed using the split method in the string class as so
public static void stackRPN(){
Stack myStack = new Stack();
Scanner sc = new Scanner(System.in);
System.out.print("Enter an equation: ");
System.out.println();
String eq = sc.nextLine();
//This Bit splits up the string where it meets a space
String[] eqS = eq.split(" ");
int len = eqS.length;
for (int i = 0; i < len; i++){
String car1 = eqS[i];
if ("+".equals(car1) || "-".equals(car1) || "/".equals(car1) || /*"car1"*/"x".equals(car1)){
String a = myStack.pop();
String b = myStack.pop();
//This handlws all the digits
double bI = Double.parseDouble(b);
double aI = Double.parseDouble(a);
double finalNo = 0;
switch (car1) {
case "+": finalNo = bI + aI;
break;
case "-": finalNo = bI - aI;
break;
case "/": finalNo = bI / aI;
break;
case "x": finalNo = bI * aI;
break;
}
myStack.push(finalNo+"");
String finEq = b+car1+a;
System.out.println(finEq + " = " +finalNo);
} else {
myStack.push(car1);
}
}
mainMenu();
}

Related

Is there way to display number in exponent format

I have a large number and I don't want to display it in EditText as for example 1.1E12. I want to display it in format like this: 1.1 x 10^12 (see image). Is there way to do this?
I think you are asking how to generate a string that represents a number in “math textbook” scientific notation, like 6.02214076×10²³.
You can split the number into its base and exponent using Math.log10, then convert the exponent’s digits to Unicode superscript characters:
public static String formatInScientificNotation(double value) {
NumberFormat baseFormat = NumberFormat.getInstance(Locale.ENGLISH);
baseFormat.setMinimumFractionDigits(1);
if (Double.isInfinite(value) || Double.isNaN(value)) {
return baseFormat.format(value);
}
double exp = Math.log10(Math.abs(value));
exp = Math.floor(exp);
double base = value / Math.pow(10, exp);
String power = String.valueOf((long) exp);
StringBuilder s = new StringBuilder();
s.append(baseFormat.format(base));
s.append("\u00d710");
int len = power.length();
for (int i = 0; i < len; i++) {
char c = power.charAt(i);
switch (c) {
case '-':
s.append('\u207b');
break;
case '1':
s.append('\u00b9');
break;
case '2':
s.append('\u00b2');
break;
case '3':
s.append('\u00b3');
break;
default:
s.append((char) (0x2070 + (c - '0')));
break;
}
}
return s.toString();
}

please check my Java homework, dialog boxes and variable type mismatches

The title says this is homework, I have been beating my head into the wall for hours, so please help. It works fine, at least the math part does, I work the conversion it worked just fine. I went to change the output dialog box to list what the ending unit was, instead of just listing the variable e.g. your lbs is the end. And not to allow negative starting weights.
Now I can't get the dialog box to not give me an error. (Lines 145 -148) I put in a sample dialog box using the Return option that doesn't work, but if I set it to a variable in my case test, it will work fine. He gave us starting code, I recopied his original code and that doesn't work. The next error I get is I wrote a method that takes two doubles and a char. When I call the function I pass it two doubles and a char it says it can't convert a string (Line 255).
This has been frustrating I over engineered this and now to have it not work is killing me. I don't understand how I can copy his original code in and it no longer works. Dialog boxes confuse me but I think I understand them.
return JOptionPane.showConfirmDialog(A)(null(B), display(C),0,1);
A is the call of the for the box what type
B is the object type my understanding its always call
C is the string, text message of the box
The last two got to do with the the icon and button displayed.
He got us started on eclipse, which said I had error in code where there none, I spent hours looking at them, they went away once I reloaded my code.
Please any thing would be helpful, but an example or corrected code (I know that is a lot) with explanations on why there are correct would be helpful. My husband knows java but not dialog boxes, so he can't help. And the method call looks right to both of us.
/*
* Uses: methods, dialog boxes, and a menu to convert weights
*
*/
import javax.swing.JOptionPane;
public class WeightCon {
char choices, choicee;
public static char menu() {
char choice;
int typeNum = 3;
boolean OK;
String prompt, results, title;
prompt = "Choose Starting Unit\n";
prompt += "A. Pounds\n";
prompt += "B. Kilograms\n";
prompt += "C. Stones\n";
prompt += "D. ounces\n";
prompt += "E. Netons\n";
prompt += "F.Grams\n";
prompt += "\n\nEnter the letter of your choice:";
title = "Weights";
do {
results = JOptionPane.showInputDialog(null,prompt,title, typeNum);
choice = results.toUpperCase().charAt(0);
if(choice >= 'A' && choice <= 'F') {
OK = true;
}
else {
OK = false;
title = "Not Valid Input!";
typeNum = 0;
}
}while(! OK);
return choice;
}
public static double LbstoKG(double k) {
return k * 0.453592;
}
public static double KtoLBS(double L) {
return L / 0.453592;
}
public static double LbstoStone(double S) {
return S / 14;
}
public static double LBStoOunce(double O) {
return O / .0625;
}
public static double LbstoNewton(double N) {
return N * 4.4482216282509;
}
public static double LBStoGarm(double G) {
return G / 0.00220462 ;
}
public static double KtoL(double L) {
return L / 0.453592;
}
public static double stoneToLbs(double L) {
return L * 14;
}
public static double ounceToLBS(double L) {
return L * .0625;
}
public static double NewtonToLBS(double L) {
return L / 4.4482216282509;
}
public static double GramtoLBS(double L) {
return L * 0.00220462 ;
}
//public static double
public static double getDouble(String prompt) {
boolean OK;
double val=0;
String temp, title = "Enter a double value";
int typeNum = 3;
do {
OK = true;
temp = JOptionPane.showInputDialog(null, prompt, title, typeNum);
try {
val = Double.parseDouble(temp);
}
catch(Exception e) {
OK = false;
title = "Error! Invalid input. Must be a double value";
typeNum = 0;
}
try {
val = Double.parseDouble(temp);
}
catch(Exception b) {
if( val < 0) {
title = "Error! Invalid input. Must be a positive double value";
typeNum = 0;
}
}while(! OK);
}while(! OK);
return val;
}
public static String outputResults(double start, double end, char choices){
int test;
String end1;
if(choices == 'A') {
end1 = "Your end weight is the following pounds: ";
} else if (choices == 'B') {
end1 = " Your end weight is the following kilograms: ";
} else if (choices == 'C') {
end1 = " Your end weight is the following stones: ";
} else if (choices == 'D') {
end1 = " Your end weight is the following ounces: ";
} else if (choices == 'E') {
end1 = " Your end weight is the following newtons: ";
} else if (choices == 'F') {
end1 = " Your end weight is the following grams: ";
} else {end1 = " ERROR ERROR UNDEFINDED ERROR PLEASE CONSOLT DOCUMENTATION";}
String endreal = String.valueOf(end);
String display = "" + end1 + endreal;
//int input =
test = JOptionPane.showConfirmDialog(null, display,0,1);
test = JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1);
}
//display += "Do again?";
//return JOptionPane.showConfirmDialog(null,"test",0,1);
//return JOptionPane.showConfirmDialog(null,display,0,1);}}
//return JOptionPane.showConfirmDialog(null, "test",0,1);}}
//}
//
public static void main(String[] args) {
double get;
double lbs=0,ounce=0,kgs=0, stone=0,newton=0,gram=0 ;
double temp,start, end;
char choice, choices;
int button;
//String end1;
start =-99;
end = -999;
get = 0;
temp = 0;
do {
choice = menu();
choices = choice;
switch(choice) {
case 'A':
get = getDouble("Enter pounds : ");
lbs = get;
start = get; //LbstoKG(get);
temp = kgs;
break;
case 'B':
get = getDouble("Enter kilograms : ");
kgs = get;
start = KtoL(get);
temp = lbs;
break;
case 'C':
get = getDouble("Enter Stones : ");
stone = get;
start = stoneToLbs(get);
temp = lbs;
break;
case 'D':
ounce = getDouble("Enter Ounces : ");
start = ounceToLBS(get);
temp = lbs;
break;
case 'E':
get= getDouble("Enter Newtons : ");
newton = get;
start = NewtonToLBS(get);
temp = lbs;
break;
case 'F':
get = getDouble("Enter grams : ");
gram = get;
start = GramtoLBS(get);
temp = lbs;
break;
}
//button = outputResults(get,get);
//} while(button == 0);
// do {
choice = menu();
switch(choice) {
case 'A':
//get = getDouble("Enter pounds : ");
//lbs = getDouble("Enter pounds : ");
//kgs = get;
end = start;
break;
case 'B':
//get = getDouble("Enter kilograms : ");
end = LbstoKG(start);
break;
case 'C':
//get = getDouble("Enter Stones : ");
//stone = get;
end = LbstoStone(start);
break;
case 'D':
//ounce = getDouble("Enter Ounces : ");
end = LBStoOunce(start);
break;
case 'E':
//get= getDouble("Enter Newtons : ");
end = LbstoNewton(start);
System.out.printf("Hello");
break;
case 'F':
//get = getDouble("Enter grams : ");
end = LBStoGarm(start);
break;
}
button = outputResults(end,start,choice);
} while(button == 0);
}}
After copying and pasting your code into my compiler, there were multiple errors.
First Mistake in outputResults(): Remove the 0, and the 1.
The method showConfirmDialog(Component, Object, String, int) in the type JOptionPane
is not applicable for the arguments (null, String, int, int)
Line:
test = JOptionPane.showConfirmDialog(null, display,0,1);
Correction:
test = JOptionPane.showConfirmDialog(null, display);
Second and Third Mistake also in outputResults(): You cannot return two objects. Also, your method returns a String.
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1); // 0, 1 again.
// The second return statement is dead code, and this also makes the first mistake again
Your method returns a String.
JOptionPane.showConfirmDialog(null, display); returns an int.
So in your method returning a String, if you return an int instead, it will be a compiler error. For example:
... String outputResults(...){
return JOptionPane.showConfirmDialog(null, display);
}
1 quick fix: change return type to int (method: String outputResults(double, double, char))
Fourth Mistake in main(): Fix your Third Mistake and ignore this fix.
int button = ...;
...
button = outputResults(end,start,choice); // Returns String, but button is an int
// Change button to a string?
// Integer.parseInt(outputResults(end,start,choice)); ?

Craps Project - Debugs for non apparent syntax errors

I'm making a bare-bones Craps simulator with Java on the Eclipse IDE, I'm having a terribly hard time debugging the things that don't seem to indicate any errors in syntax only during the compiling process.
I'm running into this issue when trying to assign a value to the first bet on the "table."
The Pass()method isn't operating as I expected it would, I don't have any immediate error messages however it does not want to compile past this point, which is only line 33 down on the main method.
char answer = keyboard.nextLine().toUpperCase().charAt(0); This line seems to be the largest hurdle in getting all of my methods to operate smoothly throughout.. from what I understand.
I do have a die class but that's proving to be a non issue so I didn't include it in this post.
EDIT: This is the entirety of the program as it stands. I've been tweaking left and right on either end to find the appropriate ways to compile this absolute mess.
Any input is much appreciated. Thank you in Advance.
import java.util.Scanner;
public class Craps {
//Declaring start value of balances
static double totalMoney = 0.00;
static double rollMoney = 0.00;
public static void main(String[] args) {
//Creating Die Objects
Die die1 = new Die();
Die die2 = new Die();
//Beginning of loop
do {
//Displaying the rules for the game
displayMenu();
//Array to hold both Dice and create total for the first roll
//as well as every roll there after
//Initialized 'purses' for the first bets
int dice[] = new int[2];
int intTotal = 0;
int total = 0;
int passBet = 2;
double pass = 0.00;
double dontPass = 0.00;
//Rolling Dice for the first time in the Round
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
intTotal = (dice[0] + dice[1]);
//Assigning Value to Pass/Don't Pass bets
do {
while(Pass() == true) {
try{
pass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
while(dontPass() == true) {
try{
dontPass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
//Display of each individual rolls
//Display of total
//Win-Loss-Continue Play check
switch(intTotal) {
case 7:
case 11:
rollMoney = (pass*passBet);
dontPass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Don't Pass line, better luck next time.");
System.out.println("You have made: " + pass);
System.out.println("Total Earnings: " + totalMoney);
case 2:
case 3:
case 12:
rollMoney = (dontPass*passBet);
pass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Pass line, better luck next time.");
System.out.println("You have made: " + dontPass);
System.out.println("Total Earnings: " + totalMoney);
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
//"Actual" Game of Craps
do {
double placeBet[] = {1.2, 1.5, 2.0};
int hardBet[] = {7, 9};
int hornBet[] = {15, 30};
//List<Double> place = new ArrayList<Double>();
//List<Double> hard = new ArrayList<Double>();
//List<Double> horn = new ArrayList<Double>();
double place[] = new double[6];
double hard[] = new double[4];
double horn[] = new double[4];
int pBetMax = 6;
int haBetMax = 4;
int hoBetMax = 4;
int pBets[] = new int[pBetMax];
int haBets[] = new int[haBetMax];
int hoBets[] = new int[hoBetMax];
//Gathering Place Bets w/ Location and Value
if(Place() == true) {
pBets = getPlace();
for(int pBetOffset = 1; pBetOffset <= pBetMax; pBetOffset++) {
switch(pBets[pBetOffset]) {
case 4:
place[0] += getBet();
case 5:
place[1] += getBet();
case 6:
place[2] += getBet();
case 8:
place[3] += getBet();
case 9:
place[4] += getBet();
case 10:
place[5] += getBet();
case 0:
break;
}
}
}
//Gathering Hardway Bets w/ Location and Value
if(Hard() == true) {
haBets = getHard();
for(int haBetOffset = 1; haBetOffset <= haBetMax; haBetOffset++) {
switch(haBets[haBetOffset]) {
case 4:
hard[0] += getBet();
case 6:
hard[1] += getBet();
case 8:
hard[2] += getBet();
case 10:
hard[3] += getBet();
case 0:
break;
}
}
}
//Gathering Horn Bets w/ Location and Value
if(Horn() == true) {
hoBets = getHorn();
for(int hoBetOffset = 1; hoBetOffset <= hoBetMax; hoBetOffset++) {
switch(hoBets[hoBetOffset]) {
case 2:
horn[0] += getBet();
case 3:
horn[1] += getBet();
case 11:
horn[2] += getBet();
case 12:
horn[3] += getBet();
case 0:
break;
}
}
}
//Redefining the roll separate from the intRoll
dice = new int[2];
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
total = (dice[0] + dice[1]);
if(intTotal != total) {
switch(total) {
case 11:
rollMoney += (horn[2] * hornBet[1]);
case 2:
rollMoney += (horn[0] * hornBet[2]);
case 3:
rollMoney += (horn[1] * hornBet[1]);
case 12:
rollMoney += (horn[3] * hornBet[2]);
case 4:
if(dice[0]== dice[1]) {rollMoney += (hard[0] * hardBet[1]);}
rollMoney += (place[0] * placeBet[3]);
case 5:
rollMoney += (place[1] * placeBet[2]);
case 6:
if(dice[0]== dice[1]) {rollMoney += (hard[1] * hardBet[2]);}
rollMoney += (place[2] * placeBet[1]);
case 8:
if(dice[0]== dice[1]) {rollMoney += (haBets[2] * hardBet[2]); }
rollMoney += (place[3] * placeBet[1]);
case 9:
rollMoney += (place[4] * placeBet[2]);
case 10:
if(dice[0]== dice[1]) {rollMoney += (haBets[3] * hardBet[1]);}
rollMoney += (place[5] * placeBet[3]);
case 7:
//Wiping the bets clean off the board
pass = 0.00;
place = new double[10];
hard = new double[10];
horn = new double[10];
//Redefining the initial roll for the game
intTotal = 0;
total = 0;
totalMoney += (dontPass * 2);
crapOut();
}
}
}while(crapOut() == true);
}
}while(keepPlaying() == true);
}while(displayMenu() == true);
}
/*
* This method determines if the player will continue after the round is over
*/
public static boolean keepPlaying() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("");
System.out.println("Do you want to roll some more? (Y/N)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
public static boolean crapOut() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("Crap Out! All Bets are OFF!");
System.out.println("After this roll you now have: $" + rollMoney + " on the board!");
System.out.println("Which bring's your grand total to.. $" + (totalMoney + rollMoney));
System.out.println("Care to make another wager?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
/*
* This method will assign values to all the bets available to the player
*/
public static double getBet() {
System.out.println("How much would you like to bet?");
Scanner keyboard = new Scanner(System.in);
String bet = keyboard.nextLine();
float num;
num = Float.parseFloat(bet);
keyboard.close();
return num;
}
/*
* This method will ask if the player would like to Accept or Press their bet
*/
public static boolean pressBet(int bet) {
Scanner keyboard = new Scanner(System.in);
boolean press = false;
System.out.println("Press your bet? (Double your initial wager)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
press = answer == 'Y';
bet = bet * 2;
keyboard.close();
return press;
}
/*
* Methods to check if play would like to place wager
* Methods to assign those bets to appropriate places on the table
*/
public static boolean Pass() {
Scanner keyboard = new Scanner(System.in);
boolean pass = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
pass = answer == 'y';
keyboard.close();
return pass;
}
public static boolean dontPass() {
Scanner keyboard = new Scanner(System.in);
boolean dontPass = false;
System.out.println("Would you like to make a Don't Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
dontPass = answer == 'Y';
keyboard.close();
return dontPass;
}
public static boolean Place() {
Scanner keyboard = new Scanner(System.in);
boolean place = false;
System.out.println("Would you like to make a Place Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
place = answer == 'Y';
keyboard.close();
return place;
}
public static int[] getPlace() {
int counter = 1;
int max = 6;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[6];
do {
System.out.println("Make selections from the numbers (4, 5, 6, 8, 9, 10), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Horn() {
Scanner keyboard = new Scanner(System.in);
boolean horn = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
horn = answer == 'Y';
keyboard.close();
return horn;
}
public static int[] getHorn() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make selections from the numbers (2, 3, 11, 12), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Hard() {
Scanner keyboard = new Scanner(System.in);
boolean hard = false;
System.out.println("Would you like to make a Hardway Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
hard = answer == 'Y';
keyboard.close();
return hard;
}
public static int[] getHard() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make a selection from the numbers (4 (2&2), 6 (3&3), 8(4&4), 10(5&5)");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
/*
* Method to display rules and parameters of game prior to playing
*/
public static boolean displayMenu() {
System.out.println("Welcome to the Crosby Casino!");
System.out.println("The Game is Craps, Rules Are:");
System.out.println("If a 7 or 11 is the first roll on the table,");
System.out.println("Pass bets get paid on the first roll!");
System.out.println("If a 2, 3, or 12 is the first roll on the table, ");
System.out.println("Don't pass bets get paid on the first roll!");
System.out.println("If any other value is rolled, the game begins..");
System.out.println("Pass bets believe whatever other value was rolled will appear before the next 7 does.");
System.out.println("Don't Pass bets believe that the 7 will appear before the initial roll's value is shown again.");
System.out.println("During the duration of the roll you can make up to 3 separate side bets");
System.out.println("'Place bets' - (2, 5, 6, 8, 9, 10) Which pay out every time these numbers appear following the initial roll");
System.out.println("'Hard bets' - (4, 6, 8, 10) Which has the most coverage of all potential outcomes");
System.out.println(" & 'Horn bets' - (2, 3, 11, 12) The best payout odds on the table");
System.out.println("The table minimum is $5.00 to play");
System.out.println("All side bet minimums are $1.00 to play");
Scanner keyboard = new Scanner(System.in);
boolean menu = false;
System.out.println("Would you like play?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
menu = answer == 'Y';
keyboard.close();
return menu;
}
}
Java arrays are 0-origin. Basically, that means that the first element in arrays have an index of 0, not 1, as your dice array shows. Thus, you need to replace dice[1] and dice[2] with dice[0] and dice[1], respectively.
EDIT Based on new info from comments:
This sounds like a new error than the AIOOBE that you previously described. The issue with your code is that you need to ensure that you use Scanner's hasNextLine() method before calling the nextLine() method. Essentially, you are calling nextLine() when there is no "next line", causing the NoSuchElementException.

Not allowed try catch block for basic input computation

If ENTER is inputted, i.e. null or empty string, the following error is thrown. Can't seem to work around it.
Exception in thread "main" java.lang.NumberFormatException: empty String at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
com.company.Main.main(Main.java:67) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Instructions
Design a program that will prompt for and read in two numbers as
strings. The numbers could be decimal numbers (double or float) or
whole numbers (int). Convert these numbers from String to numeric.
You can either choose the correct numeric type for the number of
convert directly to double since it is the largest enclosing type. If
the numbers are not valid, please inform the user and prompt again.
After both valid numbers are read in, read in an operator (+, -, *,
/). If the operator read in is not one of the allowed operators,
inform the user and prompt again. Once everything is valid perform the
indicated operation using the two numbers.
Do not use a try...catch block to intercept errors. All other options
are open to you.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String sInput;
String nInput;
double dInput;
String sInput2;
String nInput2;
double dInput2;
boolean inputOK = false;
String operator = "";
int decCount;
String operatorSelect;
double total = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
do {
System.out.print("Enter first number: ");
//decimals count validation reset.
decCount = 0;
sInput = scanner.nextLine();
if (sInput == null) {
sInput = "0";
}
//purge !numerals || !decimals.
nInput = sInput.replaceAll("[^0-9.]", "");
//decimal count validation.
for (int i = 0; i < nInput.length(); i++) {
if (nInput.charAt(i) == '.') {
decCount = decCount + 1;
}
}
//break if input valid.
if (decCount <= 1) {
break;
}
} while (true);
dInput = Double.parseDouble(nInput);
do {
System.out.print("Enter second number: ");
//decimals count validation reset.
decCount = 0;
sInput2 = scanner.nextLine();
//purge !numerals || !decimals.
nInput2 = sInput2.replaceAll("[^0-9.]", "");
//decimal count validation.
for (int i = 0; i < nInput2.length(); i++) {
if (nInput2.charAt(i) == '.') {
decCount = decCount + 1;
}
}
//break if input valid.
if (decCount <= 1) {
break;
}
} while (true);
dInput2 = Double.parseDouble(nInput2);
while (inputOK == false) {
System.out.println("Operator to select: \n1) +\n2) -\n3) *\n4) /\n");
operatorSelect = scanner.nextLine();
switch (operatorSelect) {
case "1":
total = dInput + dInput2;
inputOK = true;
operator = "+";
break;
case "2":
total = dInput - dInput2;
inputOK = true;
operator = "-";
break;
case "3":
total = dInput * dInput2;
inputOK = true;
operator = "*";
break;
case "4":
total = dInput / dInput2;
inputOK = true;
operator = "/";
break;
default:
System.out.println("Invalid input.");
}
}
System.out.println(dInput + " " + operator + " " + dInput2 + " = " + total);
}
}
}
If you press enter, sInput is not null, it's an empty String.
sInput = scanner.nextLine();
if (sInput.equals("")) {
sInput = "0";
}
The expression ^-?\d+(,\d+)*(\.\d+(e\d+)?)?$ will match a string that starts with an optional negative sign, one or more digits, optionally followed by a comma and more digits, followed by an optional fractional component which consists of a period, one or more digits, and another optional component, the exponent followed by more digits.
This is not the only solution as there can be many expressions that can match these sets of number strings.
I haven't optimized your code just added the regex check and empty check
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String sInput;
String nInput;
double dInput;
String sInput2;
String nInput2;
double dInput2;
boolean inputOK = false;
String operator = "";
int decCount;
String operatorSelect;
double total = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
do {
System.out.print("Enter first number: ");
//decimals count validation reset.
decCount = 0;
sInput = scanner.nextLine();
if (sInput.isEmpty()) {
System.out.println("Empty value Please Enter again");
continue;
}
if (!sInput.matches("^-?\\d+(,\\d+)*(\\.\\d+(e\\d+)?)?$")) {
System.out.println("Invalid input Please Enter again");
continue;
}
break;
//Not needed regex will take care of everything
// //purge !numerals || !decimals.
// nInput = sInput.replaceAll("[^0-9.]", "");
// //decimal count validation.
// for (int i = 0; i < nInput.length(); i++) {
// if (nInput.charAt(i) == '.') {
// decCount = decCount + 1;
// }
// }
// //break if input valid.
// if (decCount <= 1) {
// break;
// }
} while (true);
dInput = Double.parseDouble(sInput);
do {
System.out.print("Enter second number: ");
//decimals count validation reset.
decCount = 0;
sInput2 = scanner.nextLine();
if (sInput2.isEmpty()) {
System.out.println("Empty value Please Enter again");
continue;
}
if (!sInput2.matches("^-?\\d+(,\\d+)*(\\.\\d+(e\\d+)?)?$")) {
System.out.println("Invalid input Please Enter again");
continue;
}
break;
//purge !numerals || !decimals.
// nInput2 = sInput2.replaceAll("[^0-9.]", "");
// //decimal count validation.
// for (int i = 0; i < nInput2.length(); i++) {
// if (nInput2.charAt(i) == '.') {
// decCount = decCount + 1;
// }
// }
// //break if input valid.
// if (decCount <= 1) {
// break;
// }
} while (true);
dInput2 = Double.parseDouble(sInput2);
while (inputOK == false) {
System.out.println("Operator to select: \n1) +\n2) -\n3) *\n4) /\n");
operatorSelect = scanner.nextLine();
switch (operatorSelect) {
case "1":
total = dInput + dInput2;
inputOK = true;
operator = "+";
break;
case "2":
total = dInput - dInput2;
inputOK = true;
operator = "-";
break;
case "3":
total = dInput * dInput2;
inputOK = true;
operator = "*";
break;
case "4":
total = dInput / dInput2;
inputOK = true;
operator = "/";
break;
default:
System.out.println("Invalid input.");
}
}
System.out.println(dInput + " " + operator + " " + dInput2 + " = " + total);
break;
}
}
}

How can i separate two data types in user input?

I am creating a calculator in which a user will directly input the numbers and the operator...
Here is my code:
int answer = 0;
int num1, num2;
char operator;
System.out.print("Enter calculation: ");
num1 = kb.nextInt();
operator = kb.next().charAt(0);
num2 = kb.nextInt();
The code above will accept the user input when there are spaces like this:
1 + 1
so the program will give an answer which is 2.
But if i input 1+1 it will give an error
Exception in thread "main" java.util.InputMismatchException
How can i do that it will separate integer to character? because i set the operator as character. So that it will accept one digit to several digit numbers. Like 500+84 or 1520/872, 30*5, 148-65?
I don't have much experience with the java.util.Scanner class. But, I suspect that it tokenizes on a well-defined token separator, such as spaces, tabs, a comma, pipe characters, etc. So, this may be a poor choice in tokenizing your type of input.
To successfully tokenize your type of input, I suggest implementing a proper lexical analyzer. This may be overkill here (like using a tank to hunt a rabbit), but to do it properly and formally with some guarantee of success, you would need to write a lexical analyzer. The web is chock-full of examples of writing a lexical analyzer. For your input, it may look something like this:
public class Scanners {
public static void main(String args[]) {
Lexer lexer = new Lexer("32221-8 +45 ");
for(String token : lexer)
System.out.println("token = "+token);
}
private static final class Lexer implements Iterable<String> {
private int pos=0;
private final String input;
private final int inputLength;
private String token;
public Lexer(String input) {
this.input = input;
this.inputLength = input.length();
advance();
}
private void advance() {
if(pos>=inputLength) {
token = null;
return;
}
char c = input.charAt(pos++);
if(Character.isDigit(c))
token = advanceNumber(c);
else if(Character.isJavaIdentifierStart(c))
token = advanceVariable(c);
else if(Character.isWhitespace(c)) {
advanceWhitespace();
advance();
} else
// here, assuming a one-character operator
token = Character.toString(c);
}
private String advanceNumber(char c) {
StringBuilder sb = new StringBuilder().append(c);
while(pos<inputLength) {
c = input.charAt(pos);
if(Character.isDigit(c)) {
sb.append(c);
++pos;
} else
break;
}
return sb.toString();
}
private String advanceVariable(char c) {
StringBuilder sb = new StringBuilder().append(c);
while(pos<inputLength) {
c = input.charAt(pos);
if(Character.isJavaIdentifierPart(c)) {
sb.append(c);
++pos;
} else
break;
}
return sb.toString();
}
private void advanceWhitespace() {
while(pos<inputLength && Character.isWhitespace(input.charAt(pos)))
++pos;
}
#Override
public Iterator<String> iterator() {
return new Iterator<String>() {
#Override
public boolean hasNext() {
return token != null;
}
#Override
public String next() {
String retval = token;
advance();
return retval;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
}
// output
// ------
// token = 32221
// token = -
// token = 8
// token = +
// token = 45
It does not expect negative operands. It throws an exception if a number is too big. It does not explain what the "error in expression" is. So there's plenty of room for improvement.
Scanner scn = new Scanner( System.in );
Pattern pat = Pattern.compile( "\\s*(\\d+)\\s*([-+*/])\\s*(\\d+)\\s*" );
while( scn.hasNextLine() ){
String line = scn.nextLine();
Matcher mat = pat.matcher( line );
if( mat.matches() ){
int op1 = Integer.parseInt( mat.group(1) );
char od = mat.group(2).charAt(0);
int op2 = Integer.parseInt( mat.group(3) );
System.out.println( op1 + " " + od + " " + op2 );
} else {
System.out.println( "error in expression" );
}
}
This is a simpler version. Similar caveats apply here, too. Moreover, it throws an exception on invalid numbers and accepts almost anything as an operator.
Scanner scn = new Scanner( System.in );
scn.useDelimiter( "\\b|\\s+" );
while( scn.hasNextLine() ){
int op1 = scn.nextInt();
char od = scn.next().charAt(0);
int op2 = scn.nextInt();
System.out.println( op1 + " " + od + " " + op2 );
scn.nextLine();
}
Try using 3 scanner?
Scanner scn = new Scanner(System.in);
int operand1, operand2;
String operator;
operand1 = Integer.parseInt(scn.next());
operator = scn.next();
operand2 = Integer.parseInt(scn.next());
OP changes his question I left.
I was away just now after I posted this solution. Didn't have time to improve it. Now I give you a better and simple solution:
I supposed you do not expect user to input things like "12+45*67/20" right? Assuming there will be two operands.
1) Receive input as 1 whole string
2) Trim all the spaces from the input
3) Split string into tokens of integers
Scanner scn = new Scanner(System.in);
String[] token = new String[12];
System.out.print("Enter equation:");
String input = scn.nextLine().trim();
String operator = "";
double answer=0, operand1=0, operand2=0;
if (input.indexOf("+") != -1){
token = input.split("\\+");
operator = "+";
}
else if (input.indexOf("-") != -1){
token = input.split("-");
operator = "-";
}
else if (input.indexOf("*") != -1){
token = input.split("\\*");
operator = "*";
}
else if (input.indexOf("/") != -1){
token = input.split("/");
operator = "/";
}
else
System.out.println("Invalid equation!");
if(token[0].matches("[0-9]+") && token[1].matches("[0-9+]"))
{
operand1 = Double.parseDouble(token[0]);
operand2 = Double.parseDouble(token[1]);
switch (operator)
{
case "+": answer = operand1 + operand2;
break;
case "-": answer = operand1 - operand2;
break;
case "*": answer = operand1 * operand2;
break;
case "/": answer = operand1 / operand2;
break;
}
}
System.out.println(answer);
Just copy and paste the whole thing to test it, it will work.
You can do it like this:
Scanner scn = new Scanner(System.in);
Integer operand1, operand2;
char operator;
System.out.println("Enter first operand: ");
operand1 = scn.nextInt();
System.out.println("Enter operator: ");
operator = scn.next().charAt(0);
System.out.println("Enter second operand: ");
operand2 = scn.nextInt();

Categories