So I've been trying to make a simple calculator program in Java myself and I seem to have encountered a problem. The code doesn't seem to have an error (none showing in Eclipse or in Command Prompt), but when I run it it ends after you input the operation. Here's the example of my code:
public class vjezba1
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
Scanner text=new Scanner(System.in);
String opr;
int x;
int y;
int sum;
System.out.println("This is a simple calculator program.");
System.out.println("Input first number: ");
x = input.nextInt();
System.out.println("Input second number: ");
y = input.nextInt();
System.out.println("Choose an operation (+,-,*,/): ");
opr = text.nextLine();
if(opr == "+"){
sum = x + y;
System.out.println("Result is: " + sum);
}else if(opr == "-"){
sum = x - y;
System.out.println("Result is: " + sum);
}else if(opr == "*"){
sum = x * y;
System.out.println("Result is: " + sum);
}else if(opr == "/"){
sum = x / y;
System.out.println("Result is: " + sum);
}
}
}
Any and all insight is appreciated.
Use method
string.equals("string")
when comparing two strings in Java
Also start names of your classes with an upper case letter, that is a programming convention.
http://www.oracle.com/technetwork/java/codeconventions-135099.html
import java.io.*;
import java.util.Scanner;
public class Vjezba1
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
Scanner text=new Scanner(System.in);
String opr;
int x;
int y;
int sum;
System.out.println("This is a simple calculator program.");
System.out.println("Input first number: ");
x = input.nextInt();
System.out.println("Input second number: ");
y = input.nextInt();
System.out.println("Choose an operation (+,-,*,/): ");
opr = text.nextLine();
System.out.print(opr);
if(opr.equals("+")){
sum = x + y;
System.out.println("Result is: " + sum);
}else if(opr.equals("-")){
sum = x - y;
System.out.println("Result is: " + sum);
}else if(opr.equals("*")){
sum = x * y;
System.out.println("Result is: " + sum);
}else if(opr.equals("/")){
sum = x / y;
System.out.println("Result is: " + sum);
}
}
}
Related
import java.util.Scanner;
public class FirstJava {
public static void main(String args[]) {
final int NUMBER_OF_QUESTIONS = 5;
int correctCount = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.print("What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
while (number1 - number2 != answer) {
System.out.println("Wrong, try again.");
System.out.println("What is " + number1 + " - " + number2 + "? ");
}
System.out.println("Correct!");
count++;
correctCount++;
}
System.out.println("You got " + correctCount + " correct!");
}
}
I think there is something wrong with the second while loop but I can't figure out what. The goal is to ask subtraction question until the user gets it right. Can someone help me with this?
The problem is that the inner loop never returns once entered since the condition never changes. You can ask for the user input directly inside the condition:
System.out.print("What is " + number1 + " - " + number2 + "? ");
while (input.nextInt() != number1 - number2) {
System.out.println("Wrong, try again.");
System.out.print("What is " + number1 + " - " + number2 + "? ");
}
A few side-notes for the rest of the code:
Instead of (int) (Math.random() * 10), I suggest to use Random#nextInt().
The outer while-loop can be replaced by an easier to read for-loop.
Use camelCase for the variable NUMBER_OF_QUESTIONS or move it to the class as a static member.
Use Java notation (String[] args) for the argument array of the main method instead of C-style (String args[]).
By the way... correctCount will always be the same and might be removed if not used.
Here is the adapted class with above suggestions:
import java.util.Random;
import java.util.Scanner;
public class SubtractionQuiz {
private static final int NUMBER_OF_QUESTIONS = 5;
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
final Random random = new Random();
int correctCount = 0;
for (int count = 0; count < NUMBER_OF_QUESTIONS; count++) {
int number1 = random.nextInt(10);
int number2 = random.nextInt(10);
// order numbers
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.print("What is " + number1 + " - " + number2 + "? ");
while (input.nextInt() != number1 - number2) {
System.out.println("Wrong, try again.");
System.out.print("What is " + number1 + " - " + number2 + "? ");
}
System.out.println("Correct!");
correctCount++;
}
System.out.println("You got " + correctCount + " correct!");
}
}
I need to print the common divisors between two positive integers that were entered. They need to be printed in ascending order. If they are relatively prime, "1" needs to be printed. The code I have here is nowhere near correct. I'm really confused on how to use the loops properly while keeping it in ascending order.
Sample input:
Integer a: 8 Integer b: 12
Sample Output:
Common divisors of 8 and 12:
1
2
4
8 and 12 are not relatively prime.
Alternate Input:
Integer a: 8 Integer b: 9
Common divisors of 8 and 9:
1
8 and 9 are relatively prime.
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1 = scnr.nextInt();
int num2 = scnr.nextInt();
System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
int div1 = 0;
int div2 = 0;
int same = 0;
for (int i=1;i<=num1;i++) {
while (div1 <= num1) {
div1 = num1/i;
}
while (div2 <= num2) {
div2 = num2/i;
}
if (div1 == div2) {
div1 += same;
System.out.println(same);
System.out.println(num1 + " and " + num2 + " are not relatively prime.");
}
if (div1 != div2) {
System.out.println(1);
System.out.println(num1 + " and " + num2 + " are relatively prime.");
}
}
}
}
You can try something simple like the below:
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1 = scnr.nextInt();
int num2 = scnr.nextInt();
System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
for(int i = 1; i<= Math.min(num1,num2); i++){
if(num1%i==0 && num2%i==0) {
System.out.println(i);
}
}
}
}
Scanner input = new Scanner (System.in);
num1 = input.nextInt();
num2 = input.nextInt();
List<Integer> list = new ArrayList<>();
for(int i=0; i<=Math.min(num1,num2);i++){
if(num1%i==0 && num2%i==0){
list.add(i);
}
}
System.out.println("Divisors:");
for(int a : list){
System.out.println(a); }
if(list.size()<2){
System.out.print("Not Relatively Prime"); }
else { System.out.print("Relatively Prime");}
I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!
I have this assignment I have to do.. and I don't know how to fix the problem so that my program will work.
import java.util.Scanner;
public class Work6{
public static void main (String[] args){
String x;
String y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextLine();
System.out.println("Number 2: ");
y = in.nextLine();
if (x > y){
System.out.println("Bigger number: " + x);
}
else if (y > x){
System.out.println("Bigger number: " + y);
}
}
}
Basically I have to write a program that asks for two numbers and then tells me which one is bigger. Can you just please tell me what am I doing wrong?
Thanks, Eva
change x and y to int:
import java.util.Scanner;
public class Work6{
public static void main (String[] args){
int x;
int y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextInt();
in.nextLine();
System.out.println("Number 2: ");
y = in.nextInt();
in.nextLine();
if (x > y){
System.out.println("Bigger number: " + x);`
}
else if (y > x){
System.out.println("Bigger number: " + y);
}
}
}
Just use in.nextInt() instead of in.nextLine(). It will return an int instead of a string!
You are scanning strings and then you compare its memory locations, to see which one is larger...
What you need to do is, to scan numbers not strings, and it will work:
import java.util.Scanner;
public class Work6{
public static void main (String[] args){
int x;
int y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextInt();
System.out.println("Number 2: ");
y = in.nextInt();
if (x > y){
System.out.println("Bigger number: " + x);`
}
else if (y > x){
System.out.println("Bigger number: " + y);
}
}
}
You should read more about primitives and objects and how to compare them.
EDIT
It can also be shorter:
public static void main (String[] args){
int x;
Integer y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextInt();
System.out.println("Number 2: ");
y = in.nextInt();
System.out.println(x > y ? "Bigger number: " + x :
x == y ? "They are equal" : "Bigger number: " + y);
}
EDIT 2:
You can still use strings if you want, but you need to create Integer out of it:
String x;
String y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextLine();
System.out.println("Number 2: ");
y = in.nextLine();
int xInt = new Integer(x);
int yInt = new Integer(y);
System.out.println(xInt > yInt ? "Bigger number: " + x : x == y ? "They are equal" : "Bigger number: " + y);
What this code does, it reads lines and then you try to create Integer from it. If its not a valid Integer, Exception will be thrown here, so be careful with this. Also, its unboxed to int, I would recommend you to read more about it.
I seem have been able to figure out the first par at with the multiplication but my logic is a tad confused when trying to figure out the remainder. When i run it i just get a negative number instead of it looking like division- any help will be greatly appreciated!
Main Java Class
import java.util.Scanner;
public class assignment4 {
public static void main(String args[]) {
Scanner inputReader = new Scanner(System.in);
int multiplicand, multiplier;
int dividend, divisor;
int total=0, total2 = 0, countMult, countDiv;
System.out.print("Enter a multiplican: ");
multiplicand = inputReader.nextInt();
System.out.print("Enter a multiplier: ");
multiplier = inputReader.nextInt();
countMult = multiplier;
while(multiplier > 0) {
total = total + multiplicand;
multiplier--;
}
System.out.println(multiplicand + " times " + countMult + " equals " + total );
System.out.print("Enter a dividend: ");
dividend = inputReader.nextInt();
System.out.print("Enter a divisor: ");
divisor = inputReader.nextInt();
countDiv = divisor;
while(divisor > 0) {
total2 = total2 - dividend;
divisor--;
}
System.out.print(dividend + " divided by " + countDiv + " equals " + total2 );
}
}