Use of Private static - java

Can you find the source of error in this?
package calc;
import java.util.Scanner;
public class Calc {
Scanner scan = new Scanner(System.in);
public void add() {
System.out.println("Enter 1st number");
int s1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int s2 = scan.nextInt();
scan.nextLine();
int sum = s1 + s2;
System.out.println("The sum is: " + sum);
}
public void diff() {
System.out.println("Enter 1st number");
int d1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int d2 = scan.nextInt();
scan.nextLine();
int diff = d1 - d2;
System.out.println("The difference is: " + diff);
}
public void prod() {
System.out.println("Enter 1st number");
int p1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int p2 = scan.nextInt();
scan.nextLine();
int prod = p1 + p2;
System.out.println("The product is: " + prod);
}
public void quo() {
System.out.println("Enter 1st number");
int q1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int q2 = scan.nextInt();
scan.nextLine();
int quo = q1 + q2;
System.out.println("The quotient is: " + quo);
}
public static void main(String[] args) {
do {
Calc op = new Calc();
Scanner scan = new Scanner(System.in);
char ans = 0;
System.out.println("Calculator");
System.out.println("1.Addition\n" + "2.Subtraction\n" + "3.Multiplication\n" + "4.Division\n" + "Enter operation number:");
int n1 = scan.nextInt();
scan.nextLine();
switch (n1) {
case 1:
op.add();
break;
case 2:
op.diff();
break;
case 3:
op.prod();
break;
case 4:
op.quo();
break;
default:
System.out.println("Invalid input");
break;
}
System.out.println("Try again? [Y/N]");
ans = scan.nextLine().charAt(0);
} while (ans == 'Y' || ans == 'y');
}
}
and then netbeans has this auto correct that resulted into this:
package calc;
import java.util.Scanner;
public class Calc {
private static char ans;
it added a "private static char ans;" and I would like to understand more how did that fix my code. Thanks

ans is defined within the do{ ... } while() loop but it must be defined outside, to make it available for condition in the while.
So do:
char ans = 0;
do {
Calc op = new Calc();
Scanner scan = new Scanner(System.in);
ans = 0;

Related

Java program skips an input?

Hello,
I was trying to build a simple calculator using basic Java code and understand OOP better, so, I wrote this:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr;
opr = input.nextLine();
if(opr == "+") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
} else if (opr == "-") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
} else if (opr == "*") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
} else if (opr == "/") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
} else {
System.out.println("Please, Enter a valid operation!");
}
}
}
and another Class for math operations:
import java.util.Scanner;
public class Operation {
static int Num1;
static int Num2;
Scanner input = new Scanner(System.in);
public Operation(int x, int y) {
x = Num1;
y = Num2;
}
public void addition() {
System.out.println(Num1 + Num2);
}
public void subtraction() {
System.out.println(Num1 - Num2);
}
public void multiplication() {
System.out.println(Num1 * Num2);
}
public void division() {
System.out.println(Num1 / Num2);
}
}
but it doesn't take input for the operation, and it goes straight to the next line of code, like so:
Enter a number:
4
Enter an operation:
Please, Enter a valid operation!
Could anyone, please point my mistake?
Note: I'm a newbie in Java and programming in general. so, please don't mind me if my code isn't the best, I'm still learning.
Hello you had a couple of problems. The nextLine() will return an empty line the first time since nextInt consumes the integer only after receiving a new line char but leaves the new line char in the buffer. Additionally the equals comparison needs to be using opr.equals("+") or a switch statement. And finally your Operation class constructor had the variable assignment backwards. I have also modified the Operation private member variables to follow standard naming conventions and scoping practices. You generally want to make member variables private since if not explicitly defined they will be protected. I would recommend using a good IDE since it can catch a lot of those errors for you, try using the free IntelliJ. Here is an updated version of your code.
public class Operation {
private final int num1;
private final int num2;
public Operation(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public void addition() {
System.out.println(num1 + num2);
}
public void subtraction() {
System.out.println(num1 - num2);
}
public void multiplication() {
System.out.println(num1 * num2);
}
public void division() {
System.out.println(num1 / num2);
}
}
And your main class
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr = null;
while(opr == null || opr.length() == 0){
opr = input.nextLine();
}
switch (opr) {
case "+": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
break;
}
case "-": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
break;
}
case "*": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
break;
}
case "/": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
break;
}
default:
System.out.println("Please, Enter a valid operation!");
break;
}
}
}
Use
input.next
rather than
input.nextLine
as nextInt accepts a number and the new line character \n.
In the switch ts checking for the new line character.

How do you declare n consecutive variables using a scanner and while loop?

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc != 0)
{
System.out.println("first number: ");
int firstNum = sc.nextInt();
System.out.println("second number: ");
int secondNum = sc.nextInt();
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
}
}
}
So my intended goal is to have a script that will allow me to add two integers (chosen by user input with a scanner) and once those two are added i can then start a new sum. I'd also like to break from my while loop when the user inputs 0.
I think my error is that i can't use the != operator on the Scanner type Could someone explain the flaw in my code? (I'm used to python which is probably why I'm making this mistake)
You need to declare the variable out of while scope and update it until condition is not met
Try this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int firstNum = 1;
int secondNum = 1;
while(firstNum !=0 && secondNum != 0)
{
System.out.println("first number: ");
firstNum = sc.nextInt();
System.out.println("second number: ");
secondNum = sc.nextInt();
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
}
}
}
You should have some kind of an "infinite" loop like so:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("first number: ");
int firstNum = sc.nextInt();
if (firstNum == 0) {
break;
}
System.out.println("second number: ");
int secondNum = sc.nextInt();
if (secondNum == 0) {
break;
}
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
}
}
}
Hi just remove the while block since it has no sence to use it
Here the corrected code
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("first number: ");
int firstNum = sc.nextInt();
System.out.println("second number: ");
int secondNum = sc.nextInt();
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
}
}
You cannot compare the Object sc with an integer value 0. You can do the below code.
public static void main(String[] args)
{
try (Scanner sc = new Scanner(System.in)) {
System.out.println("first number: ");
int firstNum = sc.nextInt();
while(firstNum != 0)
{
System.out.println("second number: ");
int secondNum = sc.nextInt();
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
System.out.println("first number: ");
firstNum = sc.nextInt();
}
}
}
or
public static void main(String[] args)
{
try (Scanner sc = new Scanner(System.in)) {
while(true)
{
System.out.println("first number: ");
int firstNum = sc.nextInt();
if(firstNum == 0) {
break;
}
System.out.println("second number: ");
int secondNum = sc.nextInt();
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
System.out.println("first number: ");
firstNum = sc.nextInt();
}
}
}
It's ugly af but it will let you understand the process
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean continueRunning = true;
while (continueRunning) {
System.out.println("first number: ");
int firstNum = sc.nextInt();
System.out.println("second number: ");
int secondNum = sc.nextInt();
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
continueRunning = firstNum != 0 && secondNum != 0;
}
}
}
also ugly but i will sleep better tonight.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
requestNumbersAndSum(scanner);
}
private static void requestNumbersAndSum(Scanner scanner) {
int firstNum = requestANum(scanner, "first number: ");
int secondNum = requestANum(scanner, "second number: ");
System.out.println("The sum of your numbers: " + (firstNum + secondNum));
requestNumbersAndSum(scanner);
}
private static int requestANum(Scanner scanner, String messageToUser) {
System.out.println(messageToUser);
int requestedNumber = scanner.nextInt();
if(requestedNumber == 0){
System.exit(0);
}
return requestedNumber;
}
}

the program is not executing as it should be?

this is my code
"the full code"
import java.util.Scanner;
import java.util.ArrayList;
public class RestTestGhada {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
RestGhada obj2 = new RestGhada("null",0,0,"null");
RestGhada obj3 = new RestGhada();
RestGhada obj4 = new RestGhada();
DateGhada obj5 = new DateGhada(19,8,1998);
DateGhada obj6 = new DateGhada(19,8,2011);
WorkerGhada obj7 = new WorkerGhada("Ghada","Alghamdi",obj5,obj6,"Female");
RestGhada obj8 = new RestGhada(12,"null",20,obj7);
obj2.setID(123456789);
System.out.print("Enter the number of employee: ");
int noemp=input.nextInt();
String empname[] = new String[5];
System.out.print("Enter the employee names: ");
for(int i=0;i<empname.length;i++)
empname[i]=input.nextLine();
obj2.setEmployeeName(empname);
System.out.print("**Menu** \n"
+ "1.Create three objects of restaurant.\n"
+ "2.Display all restaurants information.\n"
+ "3.Display the checkRestaurant result. \n"
+ "4.Exit.\n"
+ "Your choice is: ");
int choice =input.nextInt();
while(choice!=4){
switch(choice){
case 1: obj3.setName("null");obj3.setID(choice);obj4.setNoEmployee(noemp); break;
case 2: obj2.lastprint(); break;
case 3: obj2.CheckRestaurant(noemp); break;
}
System.out.print("\n Your choice: ");
choice=input.nextInt();
}
CorporateGhada[] ArrGroups=new CorporateGhada[4];
RestGhada obj1 = new RestGhada("KFC");
ArrayList<RestGhada>ALRestaurant=new ArrayList();
System.out.println("do you want to enter information?");
String c = input.nextLine();
while (true){
if(c.equals("no")||c.equals("No"))
break;
System.out.print("Menu\n"
+ "1.enter ID,name,number of employee,owner\n"
+ "2.enter ID,adress,name,owner,number of employee\n"
+ "your choice : ");
int choice1 =input.nextInt();
if(choice1 == 1){
System.out.println("Enter ID") ;
int ID=input.nextInt();
System.out.println("Enter name ") ;
String name=input.next();
System.out.println("nbemployee:") ;
int nbemployee =input.nextInt();
System.out.println("Enter owner:") ;
String owner=input.next();
ALRestaurant.add(new RestGhada(name,ID,nbemployee,owner));
}
else if (choice1 == 2){
System.out.println("Enter ID:");
int ID=input.nextInt();
System.out.println("Enter adrees:") ;
String adrees=input.next();
System.out.println("Enter name :");
String name=input.next();
System.out.println("Enter owner:") ;
String owner=input.next();
System.out.println("Enter nbemployee:");
int nbemployee=input.nextInt();
ALRestaurant.add(new RestGhada(ID,adrees,name,owner,nbemployee));
}
else
ALRestaurant.add(new RestGhada());
}
ALRestaurant.remove(1);
for(int i=0; i<ALRestaurant.size();i++ ){
System.out.print(ALRestaurant.get(i));}
System.out.print(ALRestaurant.contains(obj1));
}
}
when i try to run the first quistion doesn't take an answer and it get into the while loop directly.. i already take an information from the user before and it worked but now it's now..
when i run it it turns out like this :
do you want to enter information?
Menu
1.enter ID,name,number of employee,owner
2.enter ID,adress,name,owner,number of employee
your choice :
Did you type anything in the input before the first question was asked?
When I just run this (tried to turn your code into a working example) it waits for me to input:
public static void main(String[] args) {
ArrayList<RestGhada> ALRestaurant = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("do you want to enter information?");
String c = input.nextLine();
while (true) {
if (c.equals("no") || c.equals("No"))
break;
System.out.print("Menu\n"
+ "1.enter ID,name,number of employee,owner\n"
+ "2.enter ID,adress,name,owner,number of employee\n"
+ "your choice : ");
int choice1 = input.nextInt();
if (choice1 == 1) {
System.out.println("Enter ID");
int ID = input.nextInt();
System.out.println("Enter name ");
String name = input.next();
System.out.println("nbemployee:");
int nbemployee = input.nextInt();
System.out.println("Enter owner:");
String owner = input.next();
ALRestaurant.add(new RestGhada(name, ID, nbemployee, owner));
} else if (choice1 == 2) {
System.out.println("Enter ID:");
int ID = input.nextInt();
System.out.println("Enter adrees:");
String adrees = input.next();
System.out.println("Enter name :");
String name = input.next();
System.out.println("Enter owner:");
String owner = input.next();
System.out.println("Enter nbemployee:");
int nbemployee = input.nextInt();
ALRestaurant.add(new RestGhada(ID, adrees, name, owner, nbemployee));
} else
ALRestaurant.add(new RestGhada());
}
}
private static class RestGhada {
public RestGhada(int id, String adrees, String name, String owner, int nbemployee) {
}
public RestGhada() {
}
public RestGhada(String name, int id, int nbemployee, String owner) {
}
}
In your code you haven't included your initialisation of the input object.
If you add the line
Scanner input = new Scanner(System.in);
In the beginning of your program it should work.
I ran your program with that line added and it worked.
Besides that you should really look up on correct indentation.
change to this code.
System.out.println("do you want to enter information (yse/no) ? :");
String c = input.nextLine();
while (true) {
if (c.equals("no") || c.equals("No")){
break;
}
else{
System.out.println("Enter Your Choice(1 or 2) :");
int choice1 = input.nextInt();
if (choice1 == 1) {
System.out.println("Enter ID");
int ID = input.nextInt();
System.out.println("Enter name ");
String name = input.next();
System.out.println("nbemployee:");
int nbemployee = input.nextInt();
System.out.println("Enter owner:");
String owner = input.next();
ALRestaurant.add(new RestGhada(name, ID, nbemployee, owner));
} else if (choice1 == 2) {
System.out.println("Enter ID:");
int ID = input.nextInt();
System.out.println("Enter adrees:");
String adrees = input.next();
System.out.println("Enter name :");
String name = input.next();
System.out.println("Enter owner:");
String owner = input.next();
System.out.println("Enter nbemployee:");
int nbemployee = input.nextInt();
ALRestaurant.add(new RestGhada(ID, adrees, name, owner, nbemployee));
} else{
ALRestaurant.add(new RestGhada());
}
}
}

Program error cannot end program

Main Class
import java.util.Scanner;
class Calculator
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Addition objecta = new Addition ();
Multiplacation objectmu = new Multiplacation();
Division objectd = new Division();
Minus objectmi = new Minus();
System.out.println("Enter operation");
System.out.println("1.Addition");
System.out.println("2.Multiplacation");
System.out.println("3.Division");
System.out.println("4.Subtraction");
input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
if (test1 == 1)
{
Addition plus = new Addition();
plus.add();
}
if (test2 == 2)
{
Multiplacation multi = new Multiplacation();
multi.multiply();
}
if (test3 == 3)
{
Division div = new Division();
div.divide();
}
if (test4 == 4)
{
Minus mi = new Minus();
mi.subtract();
}
}
}
Classes
import java.util.Scanner;
class Addition
{
public static void add()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Multiplacation
{
public static void multiply()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum * snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Division
{
public static void divide()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum / snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Minus
{
public static void subtract()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum - snum;
System.out.println(answer);
}
}
Question
I am making a calculator and I am new to computer programming. I got the program to work but the only problem is that I cannot get the program to stop. It answers one problem then starts another one continuously. Any ideas how to stop it please comment.
I think you need to understand how to accept input from the user.
In your code, this is wrong:
input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
Because later on, you check whether test1 is 1, test2 is 2 etc. Since you did not change the values of these variables, your conditions will always evaluate to true.
The correct way to do it is this:
int userInput = input.nextInt();
and then check the userInput variable:
if (userInput == 1) {
...
}
if (userInput == 2) {
...
}
etc
Tip: in this situation you should use else ifs:
if (userInput == 1) {
...
} else if (userInput == 2) {
...
} else if (userInput == 3) {
...
} else if (userInput == 4) {
...
}
Other improvements:
You should not create multiple scanners, one is enough.
You can declare a scanner in the Calculator class:
class Calculator {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
...
}
}
In your other classes, use Calculator.input instead of creating a new scanner. I'll give you an example:
class Addition
{
public static void add()
{
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = Calculator.input.nextDouble();
System.out.println("Eneter Second Number");
snum = Calculator.input.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
This logic
if (test1 == 1)
and
if (test2 == 2)
is always going to be true.
You should be comparing
int test = input.nextInt();
if (test == test1) { // etc
You need to check the input given by the user, and since that is only one
if/if-else is the best approach to do...
if (userInput == 1) {
Addition plus = new Addition();
plus.add();
} else if (userInput == 2) {
...your code
} else if (userInput == 3) {
......your code
} else if (userInput == 4) {
......your code
}
here when math is done, you should ask again the user for another input...
and one scanner object is more than ok, you dont need to define multiple ones....
You can change your calculator class like this mentioned below so that it asks for an option when it completes execution. In similar situations you can use switch case instead of if conditions. Add an exit option to list of options to terminate program when ever user required it.
class Calculator
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Addition objecta = new Addition ();
Multiplacation objectmu = new Multiplacation();
Division objectd = new Division();
Minus objectmi = new Minus();
while(true){
System.out.println("Enter operation");
System.out.println("1.Addition");
System.out.println("2.Multiplacation");
System.out.println("3.Division");
System.out.println("4.Subtraction");
System.out.println("5.Exit");
switch(input.nextLine()){
case "1":
Addition plus = new Addition();
plus.add();
break;
case "2":
Multiplacation multi = new Multiplacation();
multi.multiply();
break;
case "3":
Division div = new Division();
div.divide();
break;
case "4":
Minus mi = new Minus();
mi.subtract();
break;
case "5":
System.exit(0);
default:
System.out.println("Please enter valid option");
}
}
/*input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
if (test1 == 1)
{
Addition plus = new Addition();
plus.add();
}
if (test2 == 2)
{
Multiplacation multi = new Multiplacation();
multi.multiply();
}
if (test3 == 3)
{
Division div = new Division();
div.divide();
}
if (test4 == 4)
{
Minus mi = new Minus();
mi.subtract();
}*/
}
}

java.lang.Integer.parseInt(Unknown Source)

line "int yes = Integer.parseInt(sc.nextLine());" is causing me problems in my calculator. im quite new at eclipse so any suggestions on correcting the code will be great.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
int yes = Integer.parseInt(sc.nextLine());
int ans =0;
int j = 0;
int reset =j;
java.lang.String anvin = sc.nextLine();
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
System.out.println(ans);
}
if(anvin.equalsIgnoreCase("yes")) {
return;
}
}
}
Try replacing one of these lines where you enter a number.
String anvin = sc.nextLine();
with
int anvinNumbers = sc.nextInt(); //for example
It may not answer why your parsing of text isnt working but is hopefully a solution.
Refactored code
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
int ans = 0;
//Inputs
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
}
}
}

Categories