I want to take a String input to continue a conditional branch - java

I want to take a string input from keyboard. But when I ran this program there are no option to take string input. I don't know what my fault is.
Here my code is:
import java.util.Scanner;
public class Input_Program {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int a,b;
System.out.println("Enter the first number :");
a=in.nextInt();
System.out.println("Enter the second number :");
b=in.nextInt();
System.out.println("Value of first number:"+a);
System.out.println("Value of second number:"+b);
System.out.println("Do you want Add two numbers");
System.out.println("To Continue: Type Yes");
String S=in.nextLine();
if("Yes".equals(S)||"yes".equals(S))
{
int sum=a+b;
System.out.println("Summation :"+sum);
}
}
}
I want to take an input from this code. But it's not working.
String S=in.nextLine();
if("Yes".equals(S)||"yes".equals(S))
{
int sum=a+b;
System.out.println("Summation :"+sum);
}
And the result of this code is :
run:
Enter the first number :
2
Enter the second number :
3
Value of second number:3
Do you want the Summation of two numbers
To Continue: Type Yes
BUILD SUCCESSFUL (total time: 9 seconds)

1) nextLine() according to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html "Advances this scanner past the current line and returns the input that was skipped" which is not the behavior you are looking for.
2) It seems that you are new to java, and there are naming conventions. Please do not start variable names with uppercase letters
3) I fixed your indentation, and also generalized the input to take in anything that starts with y. In the future make sure you write your code this way since it's easier to tell which lines of code are in if statements, and loops and such.
import java.util.Scanner;
public class Input_Program {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the first number :");
int a = in.nextInt();
System.out.println("Enter the second number :");
int b = in.nextInt();
System.out.println("Value of first number:" + a);
System.out.println("Value of second number:" + b);
System.out.println("Do you want Add two numbers");
System.out.println("To Continue: Type Yes");
String s = in.next();
if(s.toLowerCase().contains("y")){
int sum=a+b;
System.out.println("Summation :"+sum);
}
}
}

Related

Exiting from while loop not working in java

I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "N".
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}
I didnt know where I made the mistake? Is there any other way?
First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.
Second of all, you could optimize your code the next way:
I suggest getting rid of a and kkw to make your code cleaner and shorter.
Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.
Here's an optimized and working version of your code:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}

Not Able to Use the Scanner Object on changing the position where I create it

I just started learning java on my own and I'm facing a problem with this simple calculator program that I wrote.
In the first code, I get the expected output, if I input integers with nextInt() (operands for arithmetic operations) before taking the string input through nextLine() (the arithmetic operations, ADD, SUB, MUL).
That is, in total I take 3 inputs.
It checks for the conditions and operates according to the condition which is true.
But if I change the position, i.e., first take the String input (the operations) and then the integer input (the numbers), it does not take any input for the String (operations). It also doesn't check for any conditions.
That is, in this case, I am able to input only the 2 integers and not the operation string.
What's wrong with the code? I have run it in Eclipse and Netbeans and the result is same.
The one which gives right output
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
float fnum, snum, result;
Scanner input= new Scanner(System.in);
System.out.println("What Operation do you want to perform?");
System.out.println("Enter The Choice \n\"ADD\" -For Addition");
System.out.println("\"SUB\"- For Subtraction");
System.out.println("\"MUL\"- For Multiplication");
System.out.println("\"DIV\"- For Division");
/**/String a= input.nextLine(); // on changing its position in the 2nd one
System.out.print("Enter the First Number:");
fnum=input.nextInt();
System.out.println("The First Number Entered is : "+fnum);
System.out.print("Enter the Second Number:");
snum=input.nextInt();
System.out.println("The Second Number Entered is: "+snum);
if(a.equals("ADD"))
{
result= fnum+snum;
System.out.print("The Result After ADDITION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("SUB"))
{
result=fnum-snum;
System.out.print("The Result After SUBSTRACTION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("MUL"))
{
result=fnum*snum;
System.out.print("The Result After MULTIPLICATION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("DIV"))
{
result=fnum/snum;
System.out.print("The Result After DIVISION of the Two Numbers Is:");
System.out.println(result);
}
else
{
System.out.println("Invalid Case");
}
}
}
The Second one which has the problem
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
float fnum, snum, result;
Scanner input= new Scanner(System.in);
System.out.print("Enter the First Number:");
fnum=input.nextInt();
System.out.println("The First Number Entered is : "+fnum);
System.out.print("Enter the Second Number:");
snum=input.nextInt();
System.out.println("The Second Number Entered is: "+snum);
System.out.println("What Operation do you want to perform?");
System.out.println("Enter The Choice \n\"ADD\" -For Addition");
System.out.println("\"SUB\"- For Subtraction");
System.out.println("\"MUL\"- For Multiplication");
System.out.println("\"DIV\"- For Division");
/**/String a= input.nextLine();// on changing the place of this, goes directly to the last else case, takes no input
if(a.equals("ADD"))
{
result= fnum+snum;
System.out.print("The Result After ADDITION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("SUB"))
{
result=fnum-snum;
System.out.print("The Result After SUBSTRACTION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("MUL"))
{
result=fnum*snum;
System.out.print("The Result After MULTIPLICATION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("DIV"))
{
result=fnum/snum;
System.out.print("The Result After DIVISION of the Two Numbers Is:");
System.out.println(result);
}
else
{
System.out.println("Invalid Case");
}
}
}
Basically, you are still on the same line. so calling input.nextLine(); Advances this scanner past the current line and returns the input that was skipped.
Check the documentation for nextLine() method for a detailed explanation.
To achieve what you want you need to call nextLine twice. i.e.
input.nextLine();//to complete the current line
String a = input.nextLine();//To get the user input

Conditionals and Loops evenOdd

I am trying to read an integer from the user, then print even if that number is an even number or odd otherwise. I have been told I can assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
What am I missing? Any ideas on how I can get the desired inputs and expected outputs? Test1[3][Test4]4
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int even = scan.nextInt();
int odd = scan.nextInt();
if ((even%2)==0){
System.out.println("Type a number:"+ even);
}
else {
System.out.println("Type a number:"+ odd);
}
}
}
The problem is that you have all your variables and order of the flow of your program mixed up. In English this is what you are doing
Prompt user for an integer, call that integer "even"
Prompt user for an integer, call that integer "odd"
If the integer called "even" is divisible by 2 without a remainder then print "type a number" and then the value of the integer called "even"
Otherwise print "type a number" and then the value of the integer called "odd"
You only need to read a value from the user once, then decide which message to print based on that value:
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
System.out.println("Type a number:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number%2)==0){
System.out.println("even");
}
else {
System.out.println("odd");
}
}
}
I have pointed out some issues in your code. Please correct them.
import java.util.Scanner;
//follow java naming convention and name class as "EvenOdd"
public class evenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt(); //renamed to number
int odd = scan.nextInt(); //do not need this variable
if ((number %2)==0){
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
}
Ask the user the question first so that he knows he has to input a number
System.out.println("Type a number: ");
You can simply just get 1 input from the user and store on the same variable
int input = scan.nextInt();
Then you would just check that 1 input with the if/else and display the correct output
if ((input%2)==0){
System.out.println(input + " is even.");
}
else {
System.out.println(input + " is odd.");
}

Scanner needs entry to be entered twice

I did see other questions like mine but my program was quite different so I couldn't figure out the problem. Basically, when I'm asked to enter code using this program, it needs to be entered twice. I can't figure out why.
Anyone know what I'm doing wrong? I'm sure it's something simple I'm missing.
package prac4;
import java.util.Scanner;
public class PrintNums {
public static void main(String[] args) {
int number=1;
Scanner sc = new Scanner(System.in);
System.out.println("What number should I count to?");
while (sc.nextInt()<0){
System.out.println("Please enter a positive integer: ");
if(sc.nextInt()>0){
number = sc.nextInt();
}
}
number = sc.nextInt();
sc.close();
System.out.println(number);
}
}
you are asking input 2 times (sc.nextInt()), so if you want to get the value once you should call sc.nextInt() once. you can change the snippet like below.
package prac4;
import java.util.Scanner;
public class PrintNums {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number=sc.nextInt();
System.out.println("What number should I count to?");
while (number<0){
System.out.println("Please enter a positive integer: ");
number = sc.nextInt();
}
sc.close();
System.out.println(number);
}
}
Every time you call sc.nextInt() program hangs and waits for your input. You need to call sc.nextInt() only once and assign number only once per cycle and then check your condition:
while ((number = sc.nextInt()) < 0) {
System.out.println("Please enter a positive integer: ");
}
System.out.println(number);

Conversion from one base to another

I already try to make a program it works as well but the problem is, that is not the same output what i want.
Note **
That is what i want..
enter starting base: it should be binary or octal or hexa
enter end base: it should be decimal
enter number: if 2 is entered as the starting base only 1s and 0s can be entered. If 16 is entered as the starting base 0-9 and A-F can be used.
and what i make :(
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
String binaryNumber = scanner.nextLine();
System.out.println("Enter a end base: ");
String octalNumber = scanner.nextLine();
System.out.println("Enter a number: ");
String decimalNumber = scanner.nextLine();
int myInt = Integer.parseInt(binaryNumber, 2);
int myInt2 = Integer.parseInt(octalNumber, 8);
int x = myInt;
System.out.println(
binaryNumber + " in Binary, is "
+ Integer.toString(myInt, 8) + " in Octal" + " and "
+ Integer.toString(x, 10) +" in decimal");
This is what you need to do. Figure out the code and understand. You have Scanner#nextInt() method to read integers. You don't have to use nextLine() method for this. And more over, Scanner#nextInt(int radix) accepts the input in specified radix form. It throws an exception if you don't enter the input in that form. You can catch that exception to display the error message to the user.
Your goals startBase,endBase, and the variables used for them binaryNumber is mismatching. Please name your variables which convey the purpose of them.
See the modified version of your code here:
import java.util.*;
public class Tester{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
int startBase = scanner.nextInt();
System.out.println("Enter a end base: ");
int endBase = scanner.nextInt();
int number=0;
try{
System.out.println("Enter a number: ");
number= scanner.nextInt(startBase);
System.out.println("Entered number:"+number+"(base"+startBase+")");
System.out.println("Converted number:"+Integer.toString(number,endBase)+"(enbase"+endBase+")");
}catch(InputMismatchException e){
System.out.println("Invalid input for the given radix");
e.printStackTrace(); //you can comment it if you don't need this.
}
}
}

Categories