I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!
Related
Hello
I'm new to java and need someone to answer a problem I'm having. I have recently started a project to make a calculator in Java. However i'm having a problem with one prat of my code. Basically i can't call a string off from an method. Ive tried varoius other attemps to fix the problem but to no avail. Here is the code:
package CalculatorCore;
import java.util.Scanner;
public class calculations {
static void firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
String n1 = firstNum.next(); //You can see, i put the string in a method
}
static void secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
String n2 = secondNum.next(); //Here too
}
public static void main(String[] args) {
System.out.println("Please Choose one of the following equasions: +, -, * or /");
System.out.println("");
System.out.println("");
mathEquasions();
}
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
firstNumber();
System.out.println("");
System.out.println("Now add the second number");
secondNumber();
var plusAnswer = (n1 + n2); /*The problem is situated here, i need to call the
strings from another class*/
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
firstNumber();.n1
}
}
I've already used methods to make the user inputs compact so if theres no other way should i remove the methods?
You need to return the numbers you retrieved in your both methods. Don't forget to parse them as integers, using nextInt:
public class calculations {
static int firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
int n1 = firstNum.nextInt();
return n1;
}
static int secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
int n2 = secondNum.nextInt();
return n2;
}
}
Then, when calling firstNumber or secondNumber, create new variables to store their return values:
public class calculations {
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
int n1 = firstNumber();
System.out.println("");
System.out.println("Now add the second number");
int n2 = secondNumber();
var plusAnswer = (n1 + n2);
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
}
}
}
welcome to SO! When trying something for the first time it's a good practice to make it as simple as you can, and from there gradually use more complex techniques.
In this case everything is in one class already, so as a first step you could try to put all your code back into the main method.
public static void main(String[] args) {
//All your code can come here first in the order they are supposed to to be called.
}
As a second step, when it all works, you can extract the parts where you would duplicate code, into separate methods.
Like here instead of having firstNumber() and secondNumber() you could have just one, with something like:
static int getNumber() {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int number = scanner.nextInt();
return number;
}
and you can call the same method to get both numbers:
public static void main(String[] args) {
//...
System.out.println("Please enter the first number that you want to add");
int n1 = getNumber(); // Using the same method for both
System.out.println("");
System.out.println("Now add the second number");
int n2 = getNumber(); // Using the same method for both
//...
}
Learning by doing and jumping into the thick of it is one of the best ways to learn. There are tons of good quality materials freely available (eg. on yt) and they can really boost your skills. That's also how I started learning, so good luck!
I am trying to change my code to incorporate an int and double parameter for one method name. My end goal is to let the user pick two numbers and if they type one as int and the other as double, I want the code to still be able to account for those different types and print successfully. The code as follows is the basics I have come up with so far and I would like some help on how to change this code to use method overloading.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Select operation:");
System.out.println("1. Divide 2 numbers");
System.out.println("2. Exit");
System.out.print("Enter choice(1/2:");
int choice = input.nextInt();
if (choice == 1){
division();
}
else if (choice == 2){
Exit();
}
input.close();
}
public static void division(){
int nOne, nTwo;
Scanner input = new Scanner(System.in);
System.out.println("Division");
System.out.print("First Number: ");
nOne = input.nextInt();
System.out.print("Second Number: ");
nTwo = input.nextInt();
input.close();
System.out.println("Sum: " + nOne + " / " + nTwo + " = " + (nOne /
nTwo));
}
public static void Exit(){
Scanner input = new Scanner(System.in);
System.out.println("Goodbye");
System.exit(0);
}
}
You need to give the dataype via the parameters. So you then have two methods like this:
public int division(int number1, int number2){
//do division
return result;
}
public double division(double number1, double number2){
//do division
return result;
}
you can then call the method division both with int and double and the according method will be chosen.
How can I limit the input to only integers (no doubles etc)? simple question for someone experienced to answer. if input is anything other than double then display error message, with ability to enter input again
import java.util.Scanner;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int years;
int minutes;
System.out.println("Years to Minutes Converter");
System.out.print("Insert number of years: ");
years = reader.nextInt();
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}
Use Scanner.hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Example code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt())
sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt())
sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt or worry about NumberFormatException. Note that since hasNextXXX methods doesn't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.
Ok I made this:
package reader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System. in );
int years;
int minutes;
String data = null;
System.out.println("Years to Minutes Converter");
boolean test = false;
while (test == false) {
System.out.print("Insert number of years: ");
String regex = "\\d+";
data = reader.next();
test = data.matches(regex);
if (test == false) {
System.out.println("There is a problem try again");
}
}
years = Integer.valueOf(data);
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}
It will say:
Years to Minutes Converter
Insert number of years: dsds
There is a problem try again
Insert number of years: ..
There is a problem try again
Insert number of years: 2
That is 1051200 in minutes.
I'm a beginner in java. But I know that we have some trick for take input since user add input in c++.
while(cin>>x)
{
g++;
}
I want use from this in java ,thanks.
Use either command line arguments or the Scanner class.
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
You can put any loop in here. Search loops in java. And use this to perform what you're asking.
I have to write a java program that computes the greatest common divisor of two positive integers. Program has to check for the positive integers only. My problem is that when I enter a negative integer and then a non-numeric string, my program stops running. Bellow is my code:
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
System.out.print("Enter a positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
a = sc.nextInt();
while (a <= 0){
System.out.print("Please enter a positive integer: ");
a = sc.nextInt();
}
System.out.print("Enter another positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
b = sc.nextInt();
while (b <=0){
System.out.print("Please enter a positive integer: ");
b = sc.nextInt();
}
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
}
Try this:
import java.util.Scanner;
public class A {
public static void main (String[] args){
int a, b, m, n, remainder;
a = validInput();
b = validInput();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
static int validInput() {
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("Please enter a positive integer: ");
String tmp = sc.next();
if (tmp.matches("^\\d+$")) {
return Integer.parseInt(tmp);
}
}
}
}
I suggest you to make your programs more modular, as you can see it's benefits in a simple program like this.
/* prompt a */
String a = sc.next();
/* prompt b */
String b = sc.next();
if (isValid(a) && isValid(b)) {
int ia = Integer.parseInt(a);
int ia = Integer.parseInt(b);
/* calculations and such */
}
boolean isValid(String num) {
try {
int i = Integer.parseInt(num);
if (i < 0) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
return true;
}
It shound work, even if i don't try it. I have just 2 advise as you look new in coding :
-When you make code, try to use function. Normally, you should never copy/paste.
-Try to put full name to your variable, particulary if you share your code on a forum, it would be more simple to people to understand what you did, and help you :)
import java.util.regex.Pattern;
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
a=askInt();
b=askInt();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
private int askInt(){
System.out.print("Enter a positive integer: ");
String tampon = sc.nextLine();
while(!Pattern.matches("\p{Digit}",tampon)){
System.out.print("Please enter a positive integer: ");
String tampon = sc.nextLine();
}
return Integer.valueOf(tampon);
}
}
In your first while you call next(), but in your second you use nextInt(). If you enter at the first time a negative Integer, you ll step to the next while with the nextInt(). So you ll get an exception if the user is entering a String with something else than numbers, because the scanner cant get the value of keys or something else. A smarter way would be to catch the exception and use it for a endless while like this:
while(true)
System.out.print("Please enter a positive Number: ");
try{
a = sc.nextInt();
if(a>-1){
break;
}
}catch(Exception ignore){
}
}
This code will run until the user enters a positive number. If he enters something else than numbers, the exception will come and will be ignored and the while will go on, if the number was not positive (bigger than -1 in this case) the while will not break.