Both probabilities have the same code,but when i want to make addition,the text "enter the first number" is not shown. What did i do false?
import java.util.Scanner;
public class berketurer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int command1;
int number1;
int number2;
int result;
System.out.print("for subtraction,press 1.for addition,press 2.");
command1=input.nextInt();
if (command1==1)
System.out.print("enter the first number:");
number1=input.nextInt();
System.out.print("enter the second number:");
number2=input.nextInt();
result=number1-number2;
System.out.printf("the result is=%d\n",result);
if (command1==2)
System.out.print("enter the first number;"); //here is the problem
number1=input.nextInt();
System.out.print("enter the second number;");
number2=input.nextInt();
result=number1+number2;
System.out.printf("the result is=%d\n",result);
}
}
You're missing the {} braces from your if statement bodies, all you have is the indentation (which doesn't work since Java isn't Python).
import java.util.Scanner;
public class berketurer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int command1;
int number1;
int number2;
int result;
System.out.print("for addition,press 1.for subtraction,press 2.");
command1=input.nextInt();
if (command1==1) { // <-- opening
System.out.print("enter the first number:");
number1=input.nextInt(); // <- your code stops here
System.out.print("enter the second number:");
number2=input.nextInt();
result=number1-number2;
System.out.printf("the result is=%d\n",result);
} // <-- closing
if (command1==2) { // <-- opening
System.out.print("enter the first number;"); //here is the problem
number1=input.nextInt();
System.out.print("enter the second number;");
number2=input.nextInt();
result=number1+number2;
System.out.printf("the result is=%d\n",result);
} // <-- closing
}
}
You forgot the opening and closing of each block. So the first print is not executed and your code stops waiting for input.
Related
I am going to post my code right away and ask the question below it.
System.out.println("Enter your starting integer: ");
firstInt = scnr.nextInt();
System.out.println("Enter your last integer: ");
secondInt = scnr.nextInt();
int i = firstInt;
while (i < secondInt) {
The first input is taken just fine. But when I try to input to secondInt, I hit enter and it wont move onto my while loop it is just stuck in the scanner. I hit enter and i just move down a line to input more. I watn it to move to my while loop. This is probably an easy fix but im pretty new to coding so any help would be appreciated. Thanks in advance!
import java.util.Scanner;
public class Tyler
{
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
// input first int
System.out.print("Enter your starting integer: ");
int firstInt = stdin.nextInt();
//input second int
// consume line
stdin.nextLine();
System.out.print("Enter your last integer: ");
int secondInt = stdin.nextInt();
// output data
// There was no way to break out of your while loop so this should be done with an If/else
if (firstInt <= secondInt)
{
System.out.println("First number is less then second number");
}
else
{
System.out.println("Second number is less then first number");
}
}
}
so I'm kind of new to catching errors and such. Anyways, the program is supposed to ask the user for 2 integers and then add them together. Simple, but if either of the numbers are not integers, than an error is thrown. Currently, if I enter 2 integers, instead of adding them, it just restarts the getAnswer() method and outputs them again. Also, if you enter more than one error, it will simply exit.
package javaapplication1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
Intro();
System.out.println("Your answer: "+getAnswer());
}
private static void Intro() {
System.out.println("Hello this program adds 2 integers together and catches errors.");
getAnswer();
}
private static int getAnswer() throws InputMismatchException {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown");
return 0;
}
}
}
You are calling getAnswer(); totally two times, so you just remove the call from Intro() method which will solve the problem.
private static void Intro() {
System.out.println("Hello this program adds 2
integers together and catches errors.");
}
If you want to prompt the user to reenter the input again, you can call the getAnswer() in the catch block as shown below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown, please reenter values:");
getAnswer();
}
return 0;
}
One more point is that rather than catching the InputMismatchException, the other better way is read the inputs as strings and validate that they contain only numeric values like below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input a number");
String num1 = scanner.nextLine();
System.out.println("Please input a second number");
String num2 = scanner.nextLine();
if(num1.matches("[0-9]+") && num2.matches("[0-9]+")) {
return Integer.parseInt(num1)+ Integer.parseInt(num2);
} else {
System.out.println(" Your inputs contain Invalid characters");
getAnswer();
}
return 0;
}
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!
i need help in logic, i need the program to read an integer from user and then prints all the integers from 1 to num1. here's what i got :
import java.util.Scanner;
public class test
{
public static void main(String []args)
{
Scanner scan = new Scanner(System.in);
int num1;
int num2;
System.out.println("Enter any number:");
num1 = scan.nextInt();
while (num1<=num2) {
System.out.println(num+1);
}
}
}
Try this out:
import java.util.Scanner;
class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Enter any number:");
// Note : The below statement will fail if user does not enter integer value
number = scan.nextInt();
// You can use while loop as well but for loop provides cleaner approach for iteration
for (int i = 1; i <= number; i++) {
// Print numbers sequentially from 1 to number
System.out.println(i);
}
}
}
Program that reads num and prints from 1 to num
Try,
System.out.println("Enter any number:");
num1 = scan.nextInt();
int i=1;
while (i<=num1) {
System.out.println(i);
i++;
}
do like this
int num1=0;
int num2=0;
System.out.println("Enter any number:");
num1 = scan.nextInt();
while (num2 <= num1) {
System.out.println(num2);
num2++;
}
thanks alot guys! its been couple of years since last i coded a java program so im a little rusty! here's my final code :
import java.util.Scanner;
public class test
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int num;
int a=1;
System.out.println("Enter any number:");
num=scan.nextInt();
while (a<=num)
{
System.out.println(a);
a++;}
}}
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
How do I loop a piece of code like the one above until an int is entered instead of giving an error when a non-int is entered?
The Scanner class has a lot of stuff built in so that you don't need to do try-catches unless you are explicitly looking to catch the errors.
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}
This tries to run the scanner, if a input is one that is not expected it will simply restart. You can add a message to it, my code was for brevity.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}