I'd like to ask a question about my code.
I apologize for the inefficiency and the messiness of it, I am still trying to learn java.
System.out.println("Please choose the number corresponding to the operation: ");
System.out.println("1 for add,2 for subtract,3 for multiply, 4 for divide, 5 for print, and 6 for exit: ");
if (sc.nextInt() == 5) {
System.out.println("Your first fraction is: " + num1 + "/" + denom1 + " or in decimal: " + ((float) num1 / denom1));
System.out.println("Your second fraction is: " + num2 + "/" + denom2 + " or in decimal: " + ((float) num2 / denom2));
} else if (sc.nextInt() == 3) {
System.out.println("Multiply: " + (num1 * num2) + "/" + (denom1 * denom2));
} else if (sc.nextInt() == 4) {
System.out.println("Divide: " + (num1 * denom2) + "/" + (denom1 * num1));
} else if (sc.nextInt() == 1) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Addition: " + (n1 + n2) + "/" + d);
} else if (sc.nextInt() == 2) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Subtract: " + (n1 - n2) + "/" + d);
}
else if (sc.nextInt() == 6 ) {
System.exit(0);
}
}
}
When I run the program, the first if statement gets by fine, as I only have to input the number 5 one time. However as you can see from the second else if statement which is the number 3 requires two inputs, I have to enter it two times before the next line comes up. The third else if statement which is the number 4 requires 3 inputs before the next line shows up, and so on with each successive else if statement. I'm sorry if I am not explaining this properly, Does anyone have any idea why this is happening?
Change your code to:
int input = sc.nextInt();
sc.nextLine();
if (input == 5) {
and all other if (sc.nextInt()...)also.
nextInt will consume your input. So if you come to the second if the input is alredy consumed by the first if .
nextLine is nessesary to consume the <ENTER> after the int value.
Try to use switch statement.
package practice;
import java.util.Scanner;
public class Stack{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE 2 NUMBERS");
int num1=sc.nextInt();
int num2=sc.nextInt();
System.out.println("ENTER THE CHOICE");
int choice='0';
while(choice!=6)
{
choice=sc.nextInt();
System.out.println(choice);
switch(choice)
{
case 1:
int add=num1+num2;
System.out.println("Addition:"+add);
break;
case 2:
System.out.println("Subtract:");
break;
case 3:
System.out.println("Multiply:");
break;
case 4:
System.out.println("Divide:");
break;
case 5:
System.out.println("Your first fraction is:");
System.out.println("Your second fraction is:");
break;
case 6:
System.exit(0);
break;
default:
System.out.println("LOSER");
break;
}
}
sc.close();
}
}
Related
I am trying to make a program that solves for all the 2 number combinations of addition and subtraction that equal a target value.
For example, given the array [12,1,9,11,32,19] and the target value twenty, the answers 1+19, 9+11, and 32-12 must be returned. If there are no possible combinations, the System should print that there are no possible combinations. Also, every combination must be two numbers ONLY. Is it possible to do this only in the main class?
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What length (in a whole number) would you like the array to be? ");
int arraySize = sc.nextInt();
int [] arr = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
int remainingNumbers = arraySize - i;
System.out.println("Please enter " + remainingNumbers + " more integers.");
arr[i] = sc.nextInt();
}
System.out.print("Please enter a target value: ");
int target = sc.nextInt();
System.out.println(Arrays.toString(arr));
// Algorithm here.
}
}
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " + " + num2 + " = " +
(num1 + num2));
System.out.println(num1 + " - " + num2 + " = " +
(num1 - num2));
System.out.println(num1 + " x " + num2 + " = " +
(num1 * num2));
System.out.println(num1 + " / " + num2 + " = " +
(num1 / num2));
System.out.println(num1 + " mod " + num2 + " = " +
(num1 % num2));
}
}
enter code here
''' Input first number: 32 Input second number: 12 19 + 1 = 20 32 - 12 = 20 9+11= 20'
Yes, it is possible to do it only in the main class. It is even possible to do it only in the main method (despite doing it an own method is better, easier to understand). Just two nested for loops; one for the first value, one for the second value. Inside the inner loop just test if the sum of both values result in the expected result, same for subtraction. Set a boolean to indicate that at least one case was found. At the end print the negative message if the boolean is not set.
Sample:
private static boolean findCombinations(int target, int[] values) { // or ,int... values) {
boolean found = false;
for (int i = 0; i < values.length; i++) {
// second loop
// tests and print
}
return found;
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am a beginner, and I would like to know on how do I get this program out of bugs-
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.next().charAt(0);
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
System.out.println("Continue? Type Y to continue or N to end: ");
String st = sc.nextLine();
if(st.equals("n")) {
stop = true;
}
else {
stop = false;
}
} while(!stop);
}
}
There are no errors at all, these are my wrong-doings in the program. After all the calculations are done, it puts me through a loop, and I don't seem to quite figure it out, on how to get the user input. It comes back to the start.
This is all I can put up, since I really don't have much to tell, if anything, I will edit this questions as users ask questions.
Thanks:)
Replace String st = sc.nextLine() by String st = sc.next().
At this point the scanner has a line break in its buffer (remaining from reading the operator).
nextLine() returns whatever is left in the buffer, it does not wait for additional user input.
By calling next() instead you tell the scanner that you want to read another token. The line break is less than a token, so Scanner waits for additional user input.
You should put a nextLine(); after every nextFoo(); to consume the new line character
Also change to sc.nextLine().charAt(0); as suggested in the comments
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.nextLine().charAt(0);//change
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
// better check
String st ="";
do {
System.out.println("Continue? Type Y to continue or N to end: ");
st = sc.nextLine();
}while (!st.equals("N") || !st.equals("Y"));
if(st.equals("N")) {
stop = true;
}
else if (st.equals("Y")) {
stop = false;
}
} while(!stop);
}
}
Note that you didn't do a very good check to see if user wants to continue
I just suggest using something like this
More info about your problem
I'm writing a simple calculator program, the user inputs two integers and a symbol (+ - * etc) which represents the operation (add, subtract, multiply, etc) to be applied to the integers and the program calculates what they asked.
I have a do-while loop to continually ask for input if the input does not match the given symbols.
I've tried comparing them but I'm unsuccessful and very uncertain on what to do
CODE:
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String a, b, c, userInput;
char choice, plus, minus, times;
System.out.print(First Integer: --> ");
num1 = scan.nextInt();
System.out.print(Second Integer: --> ");
num2 = scan.nextInt();
a = "+";
b = "-";
c = "*";
plus = a.charAt(0);
minus = b.charAt(0);
times = c.charAt(0);
do {
System.out.print("Choose + - or *");
userInput = scan.Next();
choice = userInput.charAt(0);
} while(choice != '+' || choice != '-' || choice != '*');
switch(choice) {
case 1:
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case 2:
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case 3:
product = num1 ' num2;
System.out.println("Product is " + product);
break;
}
There were some errors in your code, I have tried to rectify them.
Take a look,
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String userInput;
char choice, plus, minus, times;
System.out.println("First Integer: --> ") ;
num1 = scan.nextInt();
System.out.println("Second Integer: --> ") ;
num2 = scan.nextInt();
plus = '+';
minus = '-';
times = '*';
do {
System.out.println("Choose + - or *") ;
userInput = scan.next();
choice = userInput.charAt(0);
}while(choice != '+' && choice != '-' && choice != '*');
switch(choice) {
case '+':
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case '-':
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case '*':
product = num1 * num2;
System.out.println("Product is " + product);
break;
default :
System.out.println("Wrong Choice!");
break;
}
}
}
I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".
When the following Java program is compiled, the following error occurs:
method exit in class System cannot be applied to given types;
I have 2 classes, MainClass and MathQuiz.
MainClass:
class MainClass {
public static void main(String args[]) {
MathQuiz mq = new MathQuiz(); //whenever "mq" is written, this refers to class "MathQuiz"
mq.initialiseVars(); //initialise variables (from MathQuiz)
byte exitChoice = 0;
//ask user for choice
mq.showOprMenu(); //show operation menu (from MathQuiz)
byte oprChoice = Keyboard.readByte(); //ask for user input
//if input is out of range (smaller than 0 or greater than 4), ask again
while(oprChoice < 0 || oprChoice > 4) {
System.out.print("Invalid choice! Enter your choice again (1, 2, 3, 4 or 0): ");
oprChoice = Keyboard.readByte();
}//while
mq.showDiffMenu(); //show difficulty menu (from MathQuiz)
byte diffChoice = Keyboard.readByte(); //ask for user input
//if input is out of range (smaller than 0 or greater than 3), ask again
while(diffChoice < 0 || diffChoice > 3) {
System.out.print("Invalid choice! Enter your choice again (1, 2, 3 or 0): ");
diffChoice = Keyboard.readByte(); //ask for user input
}//while
mq.generateRandNums(); //generate random numbers (from MathQuiz)
switch (exitChoice) {
case 0: {
while (exitChoice != 1 || exitChoice != 2); {
System.out.print("Are you sure you want to exit? (1 = Yes, 2 = No) ");
exitChoice = Keyboard.readByte(); //ask for user input
if (exitChoice == 1) {
System.out.println("Exiting program.");
**System.exit(); //quit program**
}//if exitChoice is 1
else if (exitChoice == 2) {
System.out.println("Returning to menu.");
mq.showOprMenu();
}//if exitChoice is 2
}//while exitChoice is neither 1 nor 2
}//case 0 ("Exit" chosen)
case 1: {
System.out.println("You will be tested on addition.");
mq.showAddQuestion(); //show addition question (from MathQuiz)
mq.checkAns(); //check answer (from MathQuiz)
break;
}//case 1 ("Addition" chosen)
case 2: {
System.out.println("You will be tested on subtraction.");
mq.showSubQuestion(); //show subtraction question (from MathQuiz)
mq.checkAns(); //check answer (from MathQuiz)
break;
}//case 2 ("Subtraction" chosen)
case 3: {
System.out.println("You will be tested on multiplication.");
mq.showMultQuestion(); //show multiplication question (from MathQuiz)
mq.checkAns(); //check answer (from MathQuiz)
break;
}//case 3 ("Multiplication" chosen)
case 4: {
System.out.println("You will be tested on division.");
mq.showDivQuestion(); //show division question (from MathQuiz)
mq.checkDivAns(); //check answer and remainder (from MathQuiz)
break;
}//case 4 ("Division" chosen)
}//switch (exitChoice)
}//main
}//class
MathQuiz:
class MathQuiz {
//properties
byte diffChoice, oprChoice, exitChoice;
int num1, num2, userAns, correctAns, userRem, correctRem, score, numOfQuestions;
//methods
public void showOprMenu() {
System.out.println("-------------------");
System.out.println("Mathematical Quiz");
System.out.println(); //skip a line
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("-------------------");
System.out.print("Enter your choice (1, 2, 3, 4 or 0): ");
}//show operation menu
public void showDiffMenu() {
System.out.println("-------------------");
System.out.println("Difficulty Settings");
System.out.println();
System.out.println("1. Easy");
System.out.println("2. Medium");
System.out.println("3. Hard");
System.out.println("0. Go back to Operation Menu");
System.out.println("-------------------");
System.out.print("Enter your choice (1, 2, 3 or 0): ");
}//showDiffMenu();
//initialise variables
public void initialiseVars() {
userAns = 0;
correctAns = 0;
userRem = 0;
correctRem = 0;
score = 0;
numOfQuestions = 0;
diffChoice = 0;
exitChoice = 0;
oprChoice = 0;
}//initialiseVars();
//generate random values for num1 and num2
public void generateRandNums() {
switch (diffChoice) {
case 0: showOprMenu(); break; //case 0 (back to operation menu)
case 1: {
//generate random values for num1 and num2 (between 1 and 10)
num1 = (int) (Math.random() * (10));
num2 = (int) (Math.random() * (10));
break;
}//case 1 (easy)
case 2: {
//generate random values for num1 and num2 (between 1 and 100)
num1 = (int) (Math.random() * (100));
num2 = (int) (Math.random() * (100));
break;
}//case 2 (medium)
case 3: {
//generate random values for num1 and num2 (between 1 and 1000)
num1 = (int) (Math.random() * (1000));
num2 = (int) (Math.random() * (1000));
break;
}//case 3 (hard)
}//switch (diffChoice)
}//generateRandNums();
//show addition question
public void showAddQuestion() {
System.out.print(num1 + " + " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 + num2;
}//showAddQuestion();
//show subtraction question
public void showSubQuestion() {
System.out.print(num1 + " - " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 - num2;
}//showSubQuestion();
//show multiplication question
public void showMultQuestion() {
System.out.print(num1 + " * " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 * num2;
}//showMultQuestion();
//show division question
public void showDivQuestion() {
System.out.print(num1 + " / " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 / num2;
System.out.print("Remainder: ");
userRem = Keyboard.readInt();
correctRem = num1 % num2;
}//showDivQuestion();
//check if inputted answer is correct (addition/subtraction/multiplication)
public void checkAns() {
if(userAns == correctAns) {
System.out.println("Correct!");
score++;
}//if answer is correct
else System.out.println("Incorrect."); //if answer is incorrect
numOfQuestions++; //increases the question "counter" by 1 (both if correct or incorrect)
}//checkAns();
//check if inputted answer and remainder is correct (division)
public void checkDivAns() {
if(userAns == correctAns) System.out.println("Correct!"); //if answer is correct
else System.out.println("Incorrect."); //if answer is incorrect
if(userRem == correctRem) System.out.println("Correct!"); //if remainder is correct
else System.out.println("Incorrect."); //if remainder is incorrect
if((userAns == correctAns) && (userRem == correctRem)) score++; //if both answer and remainder are correct
numOfQuestions++; //increases the question "counter" by 1 (both if correct or incorrect)
}//checkDivAns();
}//class
System.exit takes one argument and you should pass an exit status to it, e.g:
System.exit(0); // zero exit status usually means that program did its job without errors.
Or you can simply do:
return; // in the main method return basically has the same effect as System.exit(0)
System.exit(int status), has an int parameter.
Instead use:.
System.exit(0);