Saving results into csv - java

Here is a copy of my code,
i expected to save the results of the below code into a csv, and also ask the user do you want to review the results? if yes then display the contents of csv saved.
import java.io.*;
import java.util.Scanner;
public class TestMathOP {
public static void main(String [] args) {
float num1;
float num2;
Scanner input = new Scanner (System.in);
char choice;
do
{
System.out.print ("Enter the first number:");
num1 = input.nextFloat();
System.out.print ("Enter the second number:");
num2 = input.nextFloat();
System.out.println();
System.out.println("The sum of the numbers is " + (num1 + num2));
System.out.println("The subtract of the two numbers is " + + (num1 - num2));
System.out.print("Do you want to exit? Y/N ");
choice = input.next().charAt(0);
}
while ((choice == 'n') || (choice == 'n'));
System.out.print("Thanks for using our system");
if ((choice == 'y') || (choice == 'y'));
}
}

This should work. I think like #AlexZam said, try to go step by step.
public static void main(String[]args) throws IOException{
//creates file
File file = new File("file.csv");
//Change to strings
String num1;
String num2;
Scanner input = new Scanner (System.in);
//your choice
boolean isNo = false;
boolean isYes = false;
do
{
//enables writing to file
FileWriter fileWriter = new FileWriter("file.csv");
Scanner scanner = new Scanner(file);
System.out.print ("Enter the first number:");
float calc1;
calc1 = input.nextFloat();
String firstNumber = calc1 + "";
//WRITES TO FILE
fileWriter.write(firstNumber+"\n");
System.out.print ("Enter the second number:");
float calc2;
calc2 = input.nextFloat();
String secondNumber = calc2+"";
//WRITES TO FILE
fileWriter.write(secondNumber +"\n");
String message = "The sum of the numbers is " + (calc1 + calc2) + "\nThe subtract of the two numbers is " + (calc1 - calc2);
System.out.println(message);
fileWriter.write(message);
//close filewriting
fileWriter.close();
String question = ("Do you want to exit? Y/N ");
System.out.print(question);
String answer = input.next();
if(answer.equals("y")) {
isYes = true;
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
}else if(answer.equals("n")) {
isNo = true;
System.out.println("Thanks for using our systems!");
}
} while (!isNo&&!isYes);
}

Related

Calling a method to try and rerun through a block of code

I'm trying to compare the cost of a user's phone usage under plans from three
different providers. I can get as far as entering the usage details but once entered I try to call the method to rerun from the if statement but it just displays the main menu again and stops. I want it to run through the entire if statement from the start again
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel ;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel >4){
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection >6){
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
System.out.println("Hello World!");
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
} else {
mainMenuSelection(); // go back to main menu
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
}
mainMenuSelection = mainMenuSelection();
}
}
Codes run from top to bottom. Therefore, after the int mainMenuSelection = mainMenuSelection(); and the if-else statement is run, the code would run once again for the mainMenuSelection = mainMenuSelection() and ends, as there is nothing left in the block.
A fairly simple solution would be using a while or do-while loop with a boolean checking if the user entered the number 6 to exit the system.
You can try this example:
public static void main(String[] args) {
/*
* Your variables here
*/
boolean isExit = false;
while(!isExit) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
// menuSel codes here
} else if (mainMenuSelection == 2) {
// Display cost under provider 1
} else if (mainMenuSelection == 3) {
// Display cost under provider 2
} else if (mainMenuSelection == 4) {
// Display cost under provider 3
} else if (mainMenuSelection == 5) {
// Clear usage details
} else {
System.out.println("Exiting System");
isExit = true;
}
}
Hopes this answer helps you well.
It looks like you need a loop. Your main method has an exit condition so you can essentially loop forever by wrapping the code in your main method with a while loop:
public static void main(String[] args) {
while(true) {
// your main method code in here
}
}
By the way, you need to edit your code above in good formatting.
I have added a while loop in your main. Also, whenever any unwanted number the loop will exit using a break; and that in turn stops the program.
mainMenuSelection = mainMenuSelection();
I have deleted the above line from the code so you just need to call it once at the beginning of the code.
Let me know if you need sth else!
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel > 4) {
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection > 6) {
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
while (true) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
break;
}
}
}
}

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

Exception in thread "main" java.lang.NumberFormatException: For input string: "Roll"

Okay, so I am pretty new to programming and I am exploring what I can do so far. I wrote a code for what looks like the start of a game. My goal is to have the computer ask 3 different users their name and ask them to type in the word "Roll" to have a random number assigned to them. Then I want the computer to check which number is the highest to see who will go first and so on. When I run the code, the code works up until the point where it's supposed to check which number is the highest. I have written this so far:
import java.util.Scanner;
import java.util.Random;
class apples{
public static void main(String args[]){
Scanner name = new Scanner(System.in);
Random order = new Random();
String n1;
String n2;
String n3;
String a1;
String a2;
String a3;
System.out.println("Enter the name of the first player: ");
n1 = name.nextLine();
System.out.println("Enter the name of the second player: ");
n2 = name.nextLine();
System.out.println("Enter the name of the third player: ");
n3 = name.nextLine();
System.out.println(n1+ " type 'Roll' for your number: ");
a1 = name.nextLine();
if(a1.equals("Roll")){
String player1 =String.valueOf(1+order.nextInt(10));
System.out.println(player1);
}else{
System.out.println("Please type in Roll.");
}
System.out.println(n2+ " type 'Roll' for your number: ");
a2 = name.nextLine();
if(a2.equals("Roll")){
String player2 =String.valueOf(1+order.nextInt(10));
System.out.println(player2);
}else{
System.out.println("Please type in Roll.");
}
System.out.println(n3+ " type 'Roll' for your number: ");
a3 = name.nextLine();
if(a3.equals("Roll")){
String player3 =String.valueOf(1+order.nextInt(10));
System.out.println(player3);
}else{
System.out.println("Please type in Roll.");
}
int num1 = Integer.parseInt(a1);
int num2 = Integer.parseInt(a2);
int num3 = Integer.parseInt(a3);
if(num1>num2 && num1>num3){
System.out.println(n1+" You will go first.");
}else{
if(num2>num1 && num2>num3){
System.out.println(n2+" You will go first.");
}else{
if(num3>num1 && num3>num2){
System.out.println(n3+" You will go first");
}
}
}
}
The error message I am receiving is this:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Roll"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at apples.main(apples.java:44)
I have tried to change the strings a1,a2,a3 to player1,player2,player3 and see if that works but then it says that player1 cannot be resolved to a variable.
Thank you for any help in advance!
Your Problem is triggered by the following sequence:
int num1 = Integer.parseInt(a1);
int num2 = Integer.parseInt(a2);
int num3 = Integer.parseInt(a3);
You are trying to convert a String to an Integer, which isnt possible, except your String contains only numbers.
In your case, your Strings look like this:
a1 = "Roll"
a2 = "Roll"
a3 = "Roll"
I think that this arent the correct values you want to work with. You want to work with the input you get via:
player1 = String.valueOf(1 + order.nextInt(10));
import java.util.Scanner;
import java.util.Random;
class apples {
public static void main(String args[]) {
Scanner name = new Scanner(System.in);
Random order = new Random();
String player1 = null;
String player2 = null;
String player3 = null;
System.out.println("Enter the name of the first player: ");
String n1 = name.nextLine();
System.out.println("Enter the name of the second player: ");
String n2 = name.nextLine();
System.out.println("Enter the name of the third player: ");
String n3 = name.nextLine();
System.out.println(n1 + " type 'Roll' for your number: ");
String a1 = name.nextLine();
if (a1.equals("Roll")) {
player1 = String.valueOf(1 + order.nextInt(10));
System.out.println(player1);
} else {
System.out.println("Please type in Roll.");
player1 = "0";
}
System.out.println(n2 + " type 'Roll' for your number: ");
String a2 = name.nextLine();
if (a2.equals("Roll")) {
player2 = String.valueOf(1 + order.nextInt(10));
System.out.println(player2);
} else {
System.out.println("Please type in Roll.");
player2 = "0";
}
System.out.println(n3 + " type 'Roll' for your number: ");
String a3 = name.nextLine();
if (a3.equals("Roll")) {
player3 = String.valueOf(1 + order.nextInt(10));
System.out.println(player3);
} else {
System.out.println("Please type in Roll.");
player3 = "0";
}
int num1 = Integer.parseInt(player1);
int num2 = Integer.parseInt(player2);
int num3 = Integer.parseInt(player3);
if (num1 > num2 && num1 > num3) {
System.out.println(n1 + " You will go first.");
} else {
if (num2 > num1 && num2 > num3) {
System.out.println(n2 + " You will go first.");
} else {
if (num3 > num1 && num3 > num2) {
System.out.println(n3 + " You will go first");
}
}
}
}
}
Just a little tip: To avoid converting your generated numbers from a String to an Integer, cast them as Integers directly, like:
int numberPlayerOne;
.......
.......
numberPlayerOne = 1 + order.nextInt(10);
When you want to parse the generated numbers directly to Integers, use this code:
import java.util.Scanner;
import java.util.Random;
class apples {
public static void main(String args[]) {
Scanner name = new Scanner(System.in);
Random order = new Random();
int numberPlayerOne = 0;
int numberPlayerTwo = 0;
int numberPlayerThree = 0;
System.out.println("Enter the name of the first player: ");
String n1 = name.nextLine();
System.out.println("Enter the name of the second player: ");
String n2 = name.nextLine();
System.out.println("Enter the name of the third player: ");
String n3 = name.nextLine();
System.out.println(n1 + " type 'Roll' for your number: ");
String a1 = name.nextLine();
if (a1.equals("Roll")) {
numberPlayerOne = 1 + order.nextInt(10);
System.out.println(numberPlayerOne);
} else {
System.out.println("Please type in Roll.");
}
System.out.println(n2 + " type 'Roll' for your number: ");
String a2 = name.nextLine();
if (a2.equals("Roll")) {
numberPlayerTwo = 1 + order.nextInt(10);
System.out.println(numberPlayerTwo);
} else {
System.out.println("Please type in Roll.");
}
System.out.println(n3 + " type 'Roll' for your number: ");
String a3 = name.nextLine();
if (a3.equals("Roll")) {
numberPlayerThree = 1 + order.nextInt(10);
System.out.println(numberPlayerThree);
} else {
System.out.println("Please type in Roll.");
}
if (numberPlayerOne > numberPlayerTwo && numberPlayerOne > numberPlayerThree) {
System.out.println(n1 + " You will go first.");
} else {
if (numberPlayerTwo > numberPlayerOne && numberPlayerTwo > numberPlayerThree) {
System.out.println(n2 + " You will go first.");
} else {
if (numberPlayerThree > numberPlayerOne && numberPlayerThree > numberPlayerTwo) {
System.out.println(n3 + " You will go first");
}
}
}
}
}

reference to println is ambiguous error

i have code a very basic program than when i do type System.out.println, i get thes error: "reference to println is ambiguous" and the occured randomly it use to work and did not have a erroe but now it does and i cant figure this error occurs, so how do i fix this ,than you.
package blue.light;
//name is: slash
import java.util.*;
public class BlueLight {
public static void main(String[] args) throws InterruptedException {
Scanner scan = new Scanner(System.in);
String name;
int age;
String a;
String yes;
String no;
double num1;
double num2;
double ans;
System.out.println("hello, my name is Slash");
System.out.println("What is your name?");
name = scan.nextLine();
System.out.println("Hello " + name);
Thread.sleep(1000);
System.out.println("How old are you?");
age = scan.nextInt();
if(age < 18)
{
System.out.println("ur young af");
}
else if (age == 21)
{
System.out.println("Shots, shots, shots");
}
else if (age == 69)
{
System.out.println("ohhh yea");
}
System.out.println("you to calculate any thing?");
a = scan.nextLine();
if(a==("yes")){
System.out.println("What would u like to do?(multiply,or add)");
a = scan.nextLine();
if(a == "add"){
System.out.println("Enter number 1");
num1 = scan.nextDouble();
System.out.println("Enter number 2");
num2 = scan.nextDouble();
ans = num1+num2;
}
}
}
}
First, nextInt() doesn't consume the new line after the age (so your nextLine is then empty). You compare Object values with a call to .equals() because == tests reference identity (and with a String I'd use String.equalsIgnoreCase(String)). Finally, I'd declare the variables with minimum visibility in Java; as close to their first use as possible. Something like,
public static void main(String[] args) throws InterruptedException {
Scanner scan = new Scanner(System.in);
System.out.println("hello, my name is Slash");
System.out.println("What is your name?");
String name = scan.nextLine();
System.out.println("Hello " + name);
Thread.sleep(1000);
System.out.println("How old are you?");
int age = scan.nextInt();
if (age < 18) {
System.out.println("ur young af");
} else if (age == 21) {
System.out.println("Shots, shots, shots");
} else if (age == 69) {
System.out.println("ohhh yea");
}
System.out.println("you to calculate any thing?");
scan.nextLine(); // <-- nextInt leaves a trailing new line.
String a = scan.nextLine();
if (a.equalsIgnoreCase("yes")) { // <-- compare string for equality in
// Java
System.out.println("What would u like to do?(multiply,or add)");
a = scan.nextLine();
if (a.equalsIgnoreCase("add")) {// <-- compare string for equality
// in Java
System.out.println("Enter number 1");
double num1 = scan.nextDouble();
System.out.println("Enter number 2");
double num2 = scan.nextDouble();
double ans = num1 + num2;
System.out.println(ans); // <-- display answer
}
}
}

Basic calculator in Java

I'm trying to create a basic calculator in Java. I'm quite new to programming so I'm trying to get used to it.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation == "+");
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation == "-");
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation == "/");
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation == "*")
{
System.out.println("your answer is" + (num1 * num2));
}
}
}
This is my code. It prompts for the numbers and operation, but displays the answers all together ?
Remove the semi-colons from your if statements, otherwise the code that follows will be free standing and will always execute:
if (operation == "+");
^
Also use .equals for Strings, == compares Object references:
if (operation.equals("+")) {
Here is simple code for calculator so you can consider this
import java.util.*;
import java.util.Scanner;
public class Hello {
public static void main(String[] args)
{
System.out.println("Enter first and second number:");
Scanner inp= new Scanner(System.in);
int num1,num2;
num1 = inp.nextInt();
num2 = inp.nextInt();
int ans;
System.out.println("Enter your selection: 1 for Addition, 2 for substraction 3 for Multiplication and 4 for division:");
int choose;
choose = inp.nextInt();
switch (choose){
case 1:
System.out.println(add( num1,num2));
break;
case 2:
System.out.println(sub( num1,num2));
break;
case 3:
System.out.println(mult( num1,num2));
break;
case 4:
System.out.println(div( num1,num2));
break;
default:
System.out.println("Illigal Operation");
}
}
public static int add(int x, int y)
{
int result = x + y;
return result;
}
public static int sub(int x, int y)
{
int result = x-y;
return result;
}
public static int mult(int x, int y)
{
int result = x*y;
return result;
}
public static int div(int x, int y)
{
int result = x/y;
return result;
}
}
CompareStrings with equals(..) not with ==
if (operation.equals("+")
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
System.out.println("your answer is" + (num1 * num2));
}
And the ; after the conditions was an empty statement so the conditon had no effect at all.
If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]
import java.util.Scanner;
public class AdditionGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter The First Number");
num1 = input.nextInt();
System.out.println("Please Enter The Second Number");
num2 = input.nextInt();
Scanner op = new Scanner (System.in);
System.out.println("Please Enter The Operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("Your Answer is "+(num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("Your Answer is "+(num1 - num2));
}
else if (operation.equals("*"))
{
System.out.println("Your Answer is "+(num1 * num2));
}
else if (operation.equals("/"))
{
System.out.println("Your Answer is "+(num1 / num2));
}
}
}
Java program example for making a simple Calculator:
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
float a, b, res;
char select, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("(1) Addition\n");
System.out.print("(2) Subtraction\n");
System.out.print("(3) Multiplication\n");
System.out.print("(4) Division\n");
System.out.print("(5) Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(select)
{
case '1' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' : System.exit(0);
break;
default : System.out.print("Wrong Choice!!!");
}
}while(choice != 5);
}
}
maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
public class SwitchExample {
public static void main(String[] args) throws Exception {
System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
System.out.println("\n\n");
System.out.println("1. Addition");
System.out.println("2. Multiplication");
System.out.println("3. Substraction");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("\n");
System.out.println("Enter Your Choice ::::::: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int usrChoice = Integer.parseInt(str);
switch (usrChoice) {
case 1:
doAddition();
break;
case 2:
doMultiplication();
break;
case 3:
doSubstraction();
break;
case 4:
doDivision();
break;
case 0:
System.out.println("Thank you.....");
break;
default:
System.out.println("Invalid Value");
}
System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}
public static void doAddition() throws Exception {
System.out.println("******* Enter in Addition Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Addition : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Addition : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 + no2;
System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doSubstraction() throws Exception {
System.out.println("******* Enter in Substraction Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Substraction : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Substraction : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 - no2;
System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doMultiplication() throws Exception {
System.out.println("******* Enter in Multiplication Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Multiplication : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Multiplication : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 * no2;
System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doDivision() throws Exception {
System.out.println("******* Enter in Dividion Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Dividion : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Dividion : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
float result = no1 / no2;
System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}
}
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
int x,
int y;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number 1");
x=input.nextInt();
System.out.println("Enter Number 2");
y=input.nextInt();
System.out.println("Please enter operation + - / or *");
Scanner op=new Scanner(System.in);
String operation = op.next();
if (operation.equals("+")){
System.out.println("Your Answer: " + (x+y));
}
if (operation.equals("-")){
System.out.println("Your Answer: "+ (x-y));
}
if (operation.equals("/")){
System.out.println("Your Answer: "+ (x/y));
}
if (operation.equals("*")){
System.out.println("Your Answer: "+ (x*y));
}
}
}

Categories

Resources