Repeating the main method - java

I'm new to java and this forum. I wrote a code for a simple calculator. It's working. But how can I repeat the main method if I (let's say) put "=" instead of "(+, -, *, /)"? Should I use a loop, or something else? Thanks in advance!
import java.util.Scanner;
public class SimCal {
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int mul(int a, int b) {
return a * b;
}
public static int div(int a, int b) {
return a / b;
}
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
System.out.println("What do you want to do (+, -, *, /)? ");
String input1 = scan1.nextLine();
if (!input1.equals("+") && !input1.equals("-") && !input1.equals("*") && !input1.equals("/")) { // if wrong input given
System.out.println("You must Enter a valid operator");
} else {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter first number: ");
int input2 = scan2.nextInt();
Scanner scan3 = new Scanner(System.in);
System.out.println("Enter second number: ");
int input3 = scan3.nextInt();
if (input1.equals("+")) {
System.out.println(add(input2, input3));
} else if (input1.equals("/")) {
System.out.println(div(input2, input3));
} else if (input1.equals("-")) {
System.out.println(sub(input2, input3));
} else {
System.out.println(mul(input2, input3));
}
scan1.close();
scan2.close();
scan3.close();
}
}
}

I am a bit unsure of what you are asking, but I understood it that you want to be able to repeat the calculator without having to run it again. This can be achieved by using a boolean and a while block.
Here is an example:
import java.util.Scanner;
public class SimCal {
public static int add (int a, int b){
return a+b;
}
public static int sub (int a, int b){
return a-b;
}
public static int mul (int a, int b){
return a*b;
}
public static int div (int a, int b){
return a/b;
}
public static boolean done = false;
public static void main(String[] args){
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
Scanner scan3 = new Scanner(System.in);
while (!done) {
System.out.println("What do you want to do (+, -, *, /, quit)? ");
String input1 = scan1.nextLine();
if (!input1.equals("+") && !input1.equals("-") && !input1.equals("*") && !input1.equals("/") && !input1.equals("quit"))
{ //if wrong input given
System.out.println("You must Enter a valid operator");
}
else if (input1.equals("quit"))
{
done = true;
scan1.close();
scan2.close();
scan3.close();
}
else
{
System.out.println("Enter first number: ");
int input2 = scan2.nextInt();
System.out.println("Enter second number: ");
int input3 = scan3.nextInt();
if (input1.equals("+"))
{
System.out.println(add(input2, input3));
}
else if (input1.equals("/"))
{
System.out.println(div(input2, input3));
}
else if (input1.equals("-"))
{
System.out.println(sub(input2, input3));
}
else
{
System.out.println(mul(input2, input3));
}
}
}
}
}
I hope this is helpful. Like Andy Turner mentioned, you should try to not use multiple scanners.
EDIT: I forgot to close 2 scanners. Also, switch cases can be a better way of doing this, like mentioned by Saurav Sahu.

Related

How can I get an int calculation into a if in.equals?

I wanted to write a small quiz with an int calculation, but I can not get it to run.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
String in;
in= scan.nextLine();
System.out.println("What is 4+4?");
if (in.equals (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
You can use scan.nextInt(); to accept int values,
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in= scan.nextInt();
System.out.println("What is 4+4?");
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
First of all why would you add two numbers when you can keep one number in a variable as the expected result. The input expects a String so you can either change it to int or say String.valueOf(expected result)
int in= scan.nextInt();
Scanner scan = new Scanner(System.in);
final int a = 8;
System.out.println("What is 4+4?");
String in= scan.nextLine();
if (in.equals(String.valueOf(a))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
Although others suggest using Scanner#nextInt I wouldn't recommend it. It has some kind of nonintuitive behavior and causes harm when used by programmers who are new to Java when trying to read first number, the operator and the second number.
As the OP is already familiar with Scanner#nextLine I would suggest the following approach:
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = sc.nextLine();
int first = Integer.parseInt(a);
int second = Integer.parseInt(b);
int result = first+second;
To design such quiz, I would suggest going a bit further:
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
int a = random.nextInt(100);
int b = random.nextInt(100);
System.out.println(String.format("What is the result of %d + %d", a, b));
String answer = sc.nextLine();
try {
int result = Integer.parseInt(answer);
if (result == a+b) {
System.out.println("Correct");
} else {
System.out.println("Wrong");
}
} catch (NumberFormatException e) {
System.out.println(answer + " - is not a valid number");
}
}
You need to convert the String value of the the scanner to an int, you can use scan.nextInt() as well but this can lead to problems later with the scanner not progressing to the next line after the int. You also need to order it correctly otherwise it'll ask for input before the question is asked. See below, hope it helps.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in;
System.out.println("What is 4+4?");
in = Integer.valueOf(scan.nextLine());
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
String in = scan.nextLine();
if (in.equals(String.valueOf(a+b))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
Or use Integer.toString(a+b) or "" + (a + b)
Or change Integer in = scan.nextInt()

Why won't my program loop correctly?

I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.

How do I use the interface for this number reverse program, instead of using the program entry itself? (JAVA)

I need to know how to add the input as the number to be reversed. This questions answer should help anyone who has the need to make an input go into a program and come out modified.
import java.util.Scanner;
public class NumberReverse {
public int reverseNumber(int number){
System.out.print("Enter a number: "); <------ input
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Where I want the input to go / or you can put a number here inside of the program, instead of using the interface.));
}
}
I think best way to handle input in the main method and then trigger to reverseNumber with input value;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
try {
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Integer.valueOf(input)));
} catch (NumberFormatException nme) {
System.err.println("You entered not numeric value...!");
}
}
}
You can pass the number as the argument of the main:
public static void main(String a[]) {
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+ nr.reverseNumber(Integer.parseInt(a[0])));
}
If you don't want interface, then remove Scanner statements and pass number as argument like below
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
reverseNumber nr = new reverseNumber();
System.out.println("Result: " +nr.reverseNumber(52)); //pass the number you wish to reverse
}

Recursive methods which exclude each other?

I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;

Java Programming String Array Trouble

import java.util.Scanner;
public class GradePointAverage {
public static void main(String[] args) {
Scanner peace = new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int a=peace.nextInt();
String[] b = new String[a];
for(int i=0;i<a;i++) {
b[i]="";
System.out.print("Enter Subject No "+(i+1)+" ");
String c=peace.next();
}
for(i=0;i<b.length;i++) {
System.out.print(b[i]);
}
}
}
Greetings. :)
We have a programming experiment and well I was stuck in this part. I need to ask the user how many subjects he wants to enter and ask the user to input the subjects. I think I already entered the subjects on the array but when i want to see the content of the array it won't give me my desired output, the subjects i entered won't appear. Please help, I'm new here on this site and it's my first time to ask a question on a forum like this. Hoping that someone would reply. Thanks.
You never put the subject into the array.
import java.util.Scanner;
public class GradePointAverage
{
public static void main(String[] args)
{
int i;
Scanner peace=new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int a=peace.nextInt();
String []b=new String [a];
for(i=0;i<a;i++)
{
System.out.print("Enter Subject No "+(i+1)+" ");
b[i]=peace.next();
}
for(i=0;i<b.length;i++)
{
System.out.print(b[i]);
}
}
}
You never assign the Strings to the array.
Change
String c=peace.next();
to
b[i] = peace.next();
In addition, you should probably add some separator (or new line) when printing the array :
public static void main(String[] args)
{
Scanner peace = new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int a = peace.nextInt();
String[] b = new String[a];
for(int i = 0; i < a; i++) {
System.out.print("Enter Subject No " + (i + 1) + " ");
b[i] = peace.next();
}
for(i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
import java.util.Scanner;
public class GradePointAverage
{
public static double processAverage(int []SubjectGrades,int SubjectsNumber)
{
double sum=0;
double Ave=0;
for(int i=0;i<SubjectGrades.length;i++)
{
sum=SubjectGrades[i]+sum;
}
Ave=sum/SubjectsNumber;
return Ave;
}
public static int processNumericalValue(double Ave)
{
int Numeral;
if(Ave>=98.0&&Ave<100.0)
{
Numeral=4;
}
else if(Ave>=90.0&&Ave<98.0)
{
Numeral=3;
}
else if(Ave>=80.0&&Ave<90.0)
{
Numeral=2;
}
else if(Ave>=75.0&&Ave<80.0)
{
Numeral=1;
}
else
{
Numeral=0;
}
return Numeral;
}
public static void processLetterGrade(int Numeral)
{
if(Numeral==4)
{
System.out.println("Congratulations!");
}
else if(Numeral==3)
{
System.out.println("Your Letter Grade is B!");
}
else if(Numeral==2)
{
System.out.println("Your Letter Grade is C!");
}
else if(Numeral==1)
{
System.out.println("Your Letter Grade is D!");
}
else
{
System.out.println("You Failed!");
}
}
public static void main(String[] args)
{
double Ave=0;
Scanner peace=new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int SubjectsNumber=peace.nextInt();
int []SubjectGrades=new int [SubjectsNumber];
String []Subjects=new String [SubjectsNumber];
for(int i=0;i<SubjectsNumber;i++)
{
Subjects[i]="";
System.out.print("Enter Subject No "+(i+1)+": ");
Subjects[i]=peace.next();
System.out.println("What is your grade in "+Subjects[i]+": ");
SubjectGrades[i]=peace.nextInt();
}
int Numeral;
Ave=processAverage(SubjectGrades,SubjectsNumber);
System.out.println("Your General Average is: "+Ave);
Numeral=processNumericalValue(Ave);
System.out.println("Numerical Value is: "+Numeral);
processLetterGrade(Numeral);
}
}

Categories