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 8 years ago.
Improve this question
I tried doing a loop, but the "{" symbols prevent the all the print lines from repeating I think. I want the loop to redisplay the entire first string after the user finishes entering values for the sequence.
import java.util.Scanner;
public class FtoC{
static Scanner cin = new Scanner (System.in);
public static void main(String[] args)
{
char userInput = ' ';
System.out.print("\nEnter " + "\"F\"" + " or " + "\"f\"" + " for Fahrenheit to Celsius"
+ "\nEnter " + "\"C\"" + " or " + "\"c\"" + " for Celsius to Fahrenheit"
+ "\nEnter something else to quit." +"\n");
userInput = cin.next().charAt(0);
if ((userInput == 'F') || (userInput =='f'))
{print("Enter a temp in Fahrenheit"
+"\n I will tell you temp in Celsius" +"\n");
far2cel();
}
else if ((userInput == 'C') || (userInput =='c')) {
print("Enter a temp in Celsius:"
+"\n I will tell you temp in fahrenheit" +"\n");
cel2far();
} else {
print("Terminating the program" + "\n");
}
}
private static void cel2far() {
Scanner input = new Scanner(System.in);
Double celsius = input.nextDouble();
print(celsius + " celsius is " + ((celsius * 9 / 5.0) + 32)
+ " Fahrenheit");
}
private static void far2cel() {
Scanner input = new Scanner(System.in);
Double Fahrenheit = input.nextDouble();
print(Fahrenheit + " Fahrenheit is " + ((Fahrenheit - 32) * (5 / 9.0))
+ " celsius");
}
private static void print(String string) {
System.out.print("\n" + string);
}
}
I don't think that I get what you want exactly, but this way you can run the program until user enters something different than "F", "f", "C", "C" in the first part of the program.
import java.util.Scanner;
public class FtoC{
static Scanner cin = new Scanner (System.in);
public static void main(String[] args)
{
while(true) {
char userInput = ' ';
System.out.print("\nEnter " + "\"F\"" + " or " + "\"f\"" + " for Fahrenheit to Celsius"
+ "\nEnter " + "\"C\"" + " or " + "\"c\"" + " for Celsius to Fahrenheit"
+ "\nEnter something else to quit." +"\n");
userInput = cin.next().charAt(0);
if ((userInput == 'F') || (userInput =='f'))
{print("Enter a temp in Fahrenheit"
+"\n I will tell you temp in Celsius" +"\n");
far2cel();
}
else if ((userInput == 'C') || (userInput =='c')) {
print("Enter a temp in Celsius:"
+"\n I will tell you temp in fahrenheit" +"\n");
cel2far();
} else {
print("Terminating the program" + "\n");
break;
}
}
}
private static void cel2far() {
Scanner input = new Scanner(System.in);
Double celsius = input.nextDouble();
print(celsius + " celsius is " + ((celsius * 9 / 5.0) + 32)
+ " Fahrenheit");
}
private static void far2cel() {
Scanner input = new Scanner(System.in);
Double Fahrenheit = input.nextDouble();
print(Fahrenheit + " Fahrenheit is " + ((Fahrenheit - 32) * (5 / 9.0))
+ " celsius");
}
private static void print(String string) {
System.out.print("\n" + string);
}
}
I have placed it into while loop and added "break;" in the "Terminating program" part.
Related
I just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have created a counting game and I have tried to create a highscore method.
The problem is the program returns "null" when the "Highscore" menu is chosen. What could be causing this?
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
public class Räknesätt {
public static void main(String[]args) throws IOException {
DecimalFormat df = new DecimalFormat("0.00");
int input = Integer.parseInt(JOptionPane.showInputDialog(null, "-------------------------" + "\n\n" +
"1. Spela" + "\n" +
"2. Highscores" + "\n" +
"3. Avsluta" + "\n\n" +
"-------------------------"));
if(input == 2) {
String highscores = "";
int rader = countline("Highscores");
BufferedReader inström1 = new BufferedReader
(new FileReader("Highscores"));
for(int i = 0; i <= rader; i++) {
highscores = inström1.readLine() + "\n";
}
JOptionPane.showMessageDialog(null, highscores);
}
else if(input == 3) {
System.exit(0);
}
else if(input == 1) {
String namn = JOptionPane.showInputDialog(null, "Skriv in ditt namn");
int counter = 0;
int rätt = 0;
int fel = 0;
while(counter < 10) {
int slump1 = 1 + (int)(Math.random()*100);
int slump2 = 1 + (int)(Math.random()*100);
List<String> räknesätt = new LinkedList<String>(Arrays.asList("+",
"-",
"*",
"/"));
int räknesättRand = (int)(Math.random()*4);
String räknesättStr = räknesätt.get(räknesättRand);
counter++;
switch(räknesättStr) {
case "+":
String svarStr1 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " + " + slump2 + " = ");
int svar1 = Integer.parseInt(svarStr1);
if(svar1 == slump1 + slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "-":
String svarStr2 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " - " + slump2 + " = ");
int svar2 = Integer.parseInt(svarStr2);
if(svar2 == slump1 - slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "*":
String svarStr3 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " * " + slump2 + " = ");
int svar3 = Integer.parseInt(svarStr3);
if(svar3 == slump1 * slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "/":
String svarStr = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " / " + slump2 + " = ");
int svar = Integer.parseInt(svarStr);
if(svar == (double)slump1 / slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
}
}
JOptionPane.showMessageDialog(null, "Resultat för: " + namn + "\n\n" +
"=========================" + "\n" +
"Antal räknade tal: " + counter + "\n" +
"Antal rätt: " + rätt + "\n" +
"Antal fel: " + fel + "\n" +
"Rättprocent: " + (double)100*rätt/(rätt+fel) + "%");
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores")));
utström1.println(namn + ", " + (double)100*rätt/(rätt+fel) + "% rätt");
utström1.close();
}
}
public static int countline (String filnamn)throws IOException {
BufferedReader inström1 = new BufferedReader
(new FileReader(filnamn));
int lines = 0;
while(inström1.readLine() != null) {
++lines;
}
inström1.close();
return lines;
}
}
Code is trying to open a handle to a non-existent file by the name 'Highscores'.
Problem is being caused by the following line of code :
BufferedReader inström1 = new BufferedReader
(new FileReader("Highscores"));
The solution would be to create this file upfront, at the beginning of the program and write default contents into it.
Here is how you can go about doing it.
private static void createHighScoreFile() throws IOException {
PrintWriter printWriter = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores")));
printWriter.write("0\n");
printWriter.close();
}
public static void main(String[] args) throws IOException {
createHighScoreFile();
DecimalFormat df = new DecimalFormat("0.00");
There is also one more issue related to reading the contents of the file.
The condition in the for loop attempts to read an extra line from the file, which turns out to be null always. It needs to be fixed this way.
for (int i = 0; i <= rader; i++) {
to
for (int i = 0; i < rader; i++) {
I am new to programming, first year college of BSIT and we were tasked to code a SimpleArithmetic where it will ask your name first and after that you will be asked to enter the first and the second integer.
After giving what is asked it must show "Hello (the name that was entered)" then what follows next is the sum, difference, product and the mod of the two integers and lastly it will show "Thank You!".
I tried a lot of codes but I will not run, so can someone help me? I would appreciate it really because I really want to learn how would that happen.
This was my code
public class SimpleArithmetic{
public static void main(String[] args){
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
System.out.print("Enter your name: ");
name = in.next(); // <---- HERE
System.out.printf("\nEnter first integer: ");
System.out.printf("\nEnter second integer: ");
System.out.printf("\nnum 1 + num 2");
System.out.printf("\nnum 1 - num 2");
System.out.printf("\nnum 1 * num 2");
System.out.printf("\nnum 1 % num 2");
System.out.print("Hello \n + name");
System.out.println("num 1" + "+" + "is" + "sum");
System.out.println("num 1" + "-" + "is" + "difference");
System.out.println("num 1" + "*" + "is" + "product");
System.out.println("num 1" + "%" + "is" + "mod");
System.out.print("Thank You!");
}
}
The bold one was the error when I tried to compile the java file
Use the class Scanner as below to read input:
Scanner scanner = new Scanner(System.in); // Init scanner
String name = scanner.nextLine(); // Reads a full line
int a = scanner.nextInt(); // Reads one integer
int b = scanner.nextInt(); // Reads another integer
Check documentation here if you like to know more about the class Scanner.
Basically Scanner is a useful class to read input from a stream (System.in) in that case. From javadoc
A simple text scanner which can parse primitive types and strings
using regular expressions.
The following will work for you...
package com.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SimpleArithmetic{
public static void main(String[] args){
try{
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = in.readLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
String str1 = in.readLine();
int number1 = Integer.parseInt(str1);
System.out.printf("\nEnter second integer: ");
String str2 = in.readLine();
int number2 = Integer.parseInt(str2);
System.out.print("Hello \n "+ name);
System.out.println("num 1" + "+" + "is" + (number1 + number2));
System.out.println("num 1" + "-" + "is" + (number1 - number2));
System.out.println("num 1" + "*" + "is" + (number1 * number2));
System.out.println("num 1" + "%" + "is" + (number1 % number2));
System.out.print("Thank You!");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Remove all the double qoutes on variables.
change System.out.print("Hello \n + name"); to
System.out.print("Hello \n + name);
System.out.println("num 1" + "+" + "is" + "sum"); to System.out.println("num 1" + "+" + "is" + sum);
System.out.println("num 1" + "-" + "is" + "difference"); to `System.out.println("num 1" + "-" + "is" + difference);`
System.out.println("num 1" + "*" + "is" + "product"); to System.out.println("num 1" + "*" + "is" + product);
System.out.println("num 1" + "%" + "is" + "mod"); to `System.out.println("num 1" + "%" + "is" + mod);`
Use Scanner and try catch block:
There is no declaration of variables which is listed in assignment comments.
You should have done something similar to this:
import java.util.Scanner;
public class SimpleArithmetic {
int num1 = 0, num2 = 0, sum = 0, difference = 0, product = 0, mod = 0;
String name = null;
Scanner in = null;
public static void main(String[] args) {
SimpleArithmetic sa = new SimpleArithmetic();
try {
sa.doSimpleArithmetic();
} catch (Exception e) {
e.printStackTrace();
}
}
void doSimpleArithmetic() throws Exception {
in = new Scanner(System.in);
System.out.print("Enter your name: ");
name = in.nextLine();
System.out.printf("\nEnter first integer: ");
num1 = Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
num2 = Integer.parseInt(in.nextLine());
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
mod = num1 / num2;
System.out.println("\n" + "Hello " + name + "\n");
System.out.println(num1 + " + " + num2 + " is :" + sum);
System.out.println(num1 + " - " + num2 + " is :" + difference);
System.out.println(num1 + " * " + num2 + " is :" + product);
System.out.println(num1 + " % " + num2 + " is :" + mod);
System.out.println("\n" + "Thank You!");
in.close();
}
}
try {
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
int nnum1=Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
int nnum2=Integer.parseInt(in.nextLine());
System.out.println("Hello \n" + name);
System.out.println("num 1" + "+" + "is " + (nnum1 + nnum2));
System.out.println("num 1" + "-" + "is " + (nnum1 - nnum2));
System.out.println("num 1" + "*" + "is " + (nnum1 * nnum2));
System.out.println("num 1" + "%" + "is " + (nnum1 % nnum2));
System.out.print("Thank You!");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("Please enter valid number");
e.printStackTrace();
}
I am trying to write a program that ask a user for 2 numbers and then ask the user to pick a command from a menu by entering the correspond number to the command.
I can write the program if i take the input as an Int but cannot figure it out for a string, also it has to be a string.
I am having problems when it enters the while loop to validate the user input it does not stop when the statement is false it will stay in the loop I can not figure out what i am doing wrong.
Here is the code i have.
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
System.out.println();
while (!input.equals(1) && !input.equals(2) && !input.equals(3) && !input.equals(4)) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
System.out.println();
if (input.equals(1)) {
System.out.print(L + " * " + R + " = " + (L * R));
} else if (input.equals(2)) {
System.out.print(L + " / " + R + " = " + (L / R));
} else if (input.equals(3)) {
System.out.print(L + " + " + R + " = " + (L + R));
} else {
System.out.print(L + " - " + R + " = " + (L - R));
}
}
stdIn.close();
}
}
Any help would be much appreciated.
Thank you in advanced.
The line input = stdIn.next(); is taking input as String
while your comparison is against integer. So a String never equals Int
You may try changing your while loop condition to:
while (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
note the double quote around the numbers
Is answered, but check this
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
while (true) {
if (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4")) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
} else {
if (input.equals("1")) {
System.out.print(L + " * " + R + " = " + (L * R));
break;
} else if (input.equals("2")) {
System.out.print(L + " / " + R + " = " + (L / R));
break;
} else if (input.equals("3")) {
System.out.print(L + " + " + R + " = " + (L + R));
break;
} else {
System.out.print(L + " - " + R + " = " + (L - R));
break;
}
}
}
stdIn.close();
}
}
I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
next();
}
public static void next() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
next3(expression);
}
public static void next3(String expression) {
while (!expression.equals("quit")) {
next2(expression);
next();
}
}
public static void next2(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static boolean QuitFunction(String expression) {
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return false;
}
else {
return true;
}
}
}
Take a look at this code. I think this might help you in the right direction. It's similar to what you have already written except it eliminates the need for method calls in your while loop.
Scanner input = new Scanner(System.in);
while (!input.hasNext("quit")) {
String expression = input.nextLine(); // gets the next line from the Scanner
next2(expression); // process the input
}
// once the value "quit" has been entered, the while loop terminates
System.out.println("Goodbye");
Writing it this way drastically cleans up your code and prevents a new declaration of Scanner kb = new Scanner(System.in); each time an input is processed.