reference to println is ambiguous error - java

i have code a very basic program than when i do type System.out.println, i get thes error: "reference to println is ambiguous" and the occured randomly it use to work and did not have a erroe but now it does and i cant figure this error occurs, so how do i fix this ,than you.
package blue.light;
//name is: slash
import java.util.*;
public class BlueLight {
public static void main(String[] args) throws InterruptedException {
Scanner scan = new Scanner(System.in);
String name;
int age;
String a;
String yes;
String no;
double num1;
double num2;
double ans;
System.out.println("hello, my name is Slash");
System.out.println("What is your name?");
name = scan.nextLine();
System.out.println("Hello " + name);
Thread.sleep(1000);
System.out.println("How old are you?");
age = scan.nextInt();
if(age < 18)
{
System.out.println("ur young af");
}
else if (age == 21)
{
System.out.println("Shots, shots, shots");
}
else if (age == 69)
{
System.out.println("ohhh yea");
}
System.out.println("you to calculate any thing?");
a = scan.nextLine();
if(a==("yes")){
System.out.println("What would u like to do?(multiply,or add)");
a = scan.nextLine();
if(a == "add"){
System.out.println("Enter number 1");
num1 = scan.nextDouble();
System.out.println("Enter number 2");
num2 = scan.nextDouble();
ans = num1+num2;
}
}
}
}

First, nextInt() doesn't consume the new line after the age (so your nextLine is then empty). You compare Object values with a call to .equals() because == tests reference identity (and with a String I'd use String.equalsIgnoreCase(String)). Finally, I'd declare the variables with minimum visibility in Java; as close to their first use as possible. Something like,
public static void main(String[] args) throws InterruptedException {
Scanner scan = new Scanner(System.in);
System.out.println("hello, my name is Slash");
System.out.println("What is your name?");
String name = scan.nextLine();
System.out.println("Hello " + name);
Thread.sleep(1000);
System.out.println("How old are you?");
int age = scan.nextInt();
if (age < 18) {
System.out.println("ur young af");
} else if (age == 21) {
System.out.println("Shots, shots, shots");
} else if (age == 69) {
System.out.println("ohhh yea");
}
System.out.println("you to calculate any thing?");
scan.nextLine(); // <-- nextInt leaves a trailing new line.
String a = scan.nextLine();
if (a.equalsIgnoreCase("yes")) { // <-- compare string for equality in
// Java
System.out.println("What would u like to do?(multiply,or add)");
a = scan.nextLine();
if (a.equalsIgnoreCase("add")) {// <-- compare string for equality
// in Java
System.out.println("Enter number 1");
double num1 = scan.nextDouble();
System.out.println("Enter number 2");
double num2 = scan.nextDouble();
double ans = num1 + num2;
System.out.println(ans); // <-- display answer
}
}
}

Related

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

How to print error message when user enters anything that is not a double?

I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}

Not sure how to do a while loop in this situation

I am writing a program to take the input for a sequence
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
This should be a usable implementation:
public class Menu {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
boolean orderCompleted = false;
while(!orderCompleted) {
printMenu();
String orderString = a.nextLine();
int order = Integer.parseInt(orderString);
int total = 0;
if(order == 1) {
} else if(order == 2) {
} else if(order == 3) {
} else if(order == 4) {
} else if(order == 5) {
}
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
orderString = a.nextLine();
if(orderString.equals("n")){
orderCompleted = true;
}
}
}
private static void printMenu() {
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println("");
System.out.print("Please enter your order selection:");
}
}
I pulled the menu printing to a separate method, and re-used scanner a as well as re-using the orderString. The while loop checks a completedOrder boolean flag, so that it can be used to do completion tasks prior to exiting the order loop if need be.
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
A while loop does whatever is in the block as long as the condition is true, in your case, you are simply repeating order = b.nextInt() until something other than 'y' is given as input
while (continuePlay= b.nextLine().equalsIgnoreCase ("y")) {
order = b.nextInt(); // This is inside the block
}
you should use a do while loop instead, like so:
do{
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println(" ");
System.out.print("Please enter your order selection:");
Scanner a = new Scanner(System.in);
int order = a.nextInt();
int total = 0;
boolean continuePlay = true;
if (order == 1 ) {
} else if (order == 2) {
} else if (order == 3) {
} else if (order == 4) {
} else if (order == 5) {
}
Scanner b = new Scanner(System.in);
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
} while (continuePlay= b.nextLine().equalsIgnoreCase ("y"));
Also I'd recommend reading some basic programming books or tutorials instead of going directly to Stack Overflow.

Saving results into csv

Here is a copy of my code,
i expected to save the results of the below code into a csv, and also ask the user do you want to review the results? if yes then display the contents of csv saved.
import java.io.*;
import java.util.Scanner;
public class TestMathOP {
public static void main(String [] args) {
float num1;
float num2;
Scanner input = new Scanner (System.in);
char choice;
do
{
System.out.print ("Enter the first number:");
num1 = input.nextFloat();
System.out.print ("Enter the second number:");
num2 = input.nextFloat();
System.out.println();
System.out.println("The sum of the numbers is " + (num1 + num2));
System.out.println("The subtract of the two numbers is " + + (num1 - num2));
System.out.print("Do you want to exit? Y/N ");
choice = input.next().charAt(0);
}
while ((choice == 'n') || (choice == 'n'));
System.out.print("Thanks for using our system");
if ((choice == 'y') || (choice == 'y'));
}
}
This should work. I think like #AlexZam said, try to go step by step.
public static void main(String[]args) throws IOException{
//creates file
File file = new File("file.csv");
//Change to strings
String num1;
String num2;
Scanner input = new Scanner (System.in);
//your choice
boolean isNo = false;
boolean isYes = false;
do
{
//enables writing to file
FileWriter fileWriter = new FileWriter("file.csv");
Scanner scanner = new Scanner(file);
System.out.print ("Enter the first number:");
float calc1;
calc1 = input.nextFloat();
String firstNumber = calc1 + "";
//WRITES TO FILE
fileWriter.write(firstNumber+"\n");
System.out.print ("Enter the second number:");
float calc2;
calc2 = input.nextFloat();
String secondNumber = calc2+"";
//WRITES TO FILE
fileWriter.write(secondNumber +"\n");
String message = "The sum of the numbers is " + (calc1 + calc2) + "\nThe subtract of the two numbers is " + (calc1 - calc2);
System.out.println(message);
fileWriter.write(message);
//close filewriting
fileWriter.close();
String question = ("Do you want to exit? Y/N ");
System.out.print(question);
String answer = input.next();
if(answer.equals("y")) {
isYes = true;
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
}else if(answer.equals("n")) {
isNo = true;
System.out.println("Thanks for using our systems!");
}
} while (!isNo&&!isYes);
}

java calculator loop not working properly

For some reason my calculator won't wait for user input to finish the do while loop. I'm very new to java coding (currently only been doing it for a few hours). I want the user to be able to do more math before the program closes instead of having to reopen it every time they want to use it (obviously I don't mean anything serious by this I just want to learn and I think this will help.
heres my code
import java.util.Scanner;
public class calculator {
public static void main(String[] args){
double Answer;
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
while (yesorno = true){
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
} while (yesorno = true);
}
}
please ignore the akward formatting at the beggining and end of this code.
1) while(yesorno = true ) you are doing assignation
change to
while(yesorno == true) to prevent this thing you can use yoda style while(true = yesorno) then a compile error would throw cause you can't assign something to a value.
Or even more simpler just use while(yesorno)
2) Follow Java Code Convention , variable names are in lower case.
3)if this block get executed while (yesorno = true); you will have an infinite loop.
4) If you are using java 7 , you can do switch over strings
switch(op){
case "+":answer = num1 + num2;break;
case "-":answer = num1 - num2;break;
case "*":answer = num1 * num2;break;
case "/":answer = num1 / num2;break;
default: throw new IllegalArgumentException("Invalid operation "+ op);
}
System.out.println(answer);
You are assigning, not testing for equality in while (yesorno = true){. You should use while (yesorno == true){, since the double equals (==) tests for equality.
There were many errors, I have fixed it and commented it for you. Hope it helps:
import java.util.Scanner;
// KK: by general convention class names should always start with an upper case letter
public class calculator {
public static void main(String[] args) {
double Answer; //KK: local variable should be lower case
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
//KK: for comparing you need the double-equals
//KK: the loop will be executed as long as the expression is true, so for a boolean you don't need it at all
//KK: you can use either of the following:
// while (yesorno == true)
// while (yesorno)
while (yesorno) {
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
//KK: you need to call nextLine twice because you printed 2 lines here
//KK: otherwise again will be empty, so yesorno will always be true and you have an endless loop
again = input.nextLine();
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
}
// KK: the following line was an empty loop, that didn't do anything, so I commented it
// while (yesorno = true);
}
} //KK: this one was missing at the end too ;)
(I started my comments with KK, so you see them and can remove them later.)
Try this....
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean status = true;
while(status){
String answer = "";
String choise = "";
System.out.println("\"WELCOME TO JAVA CALCULATOR\"");
Scanner scn = new Scanner(System.in);
Scanner cal = new Scanner(System.in);
Scanner cho = new Scanner(System.in);
System.out.println("Enter the numers one by one that you want to calculate..");
int numA = scn.nextInt();
int numB = scn.nextInt();
int result = 0;
System.out.println("What you want to calculate...?");
answer = cal.nextLine();
if(answer.equals("+")){
result = numA+numB;}
if(answer.equals("-")){
result = numA-numB;}
if(answer.equals("*")){
result = numA*numB;}
if(answer.equals("/")){
result = numA/numB;}
System.out.println( "The result of " + numA + " and " + numB + " is : " + result);
System.out.println("Do you want to continue.....(y) or (n)?");
choise = cho.nextLine();
if(choise.equalsIgnoreCase("y")){
System.out.println("Welcome back.....:)\n\"Make By Saikat Halder\"");
status = true;}
if(choise.equalsIgnoreCase("n")){
System.out.println("Good bye....Thanks for useing java Calculator......:)");
System.exit(0);
}
}
}
}

Categories

Resources