import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int a = sc.nextInt();
boolean aValid = sc.hasNextInt();
System.out.println(aValid);
System.out.println("Enter Second number");
int b = sc.nextInt();
boolean bValid = sc.hasNextInt();
System.out.println(bValid);
if(aValid && bValid){
System.out.println("Sum of number is "+(a+b));
}
else{
System.out.println("Enter integer number");
}
}
}
I try to get input of a and b and validate that a and b are integers. But it takes three input. It gives the sum of the first two numbers and gives the validity of the last two.
you need to place check integer statements before taking input
boolean aValid = sc.hasNextInt();
int a = sc.nextInt();
boolean bValid = sc.hasNextInt();
int b = sc.nextInt();
Running this code makes the error fairly obvious. Some additional debug statements, running the code in debug or testing would also make it clear.
Scanner.nextInt() will throw an exception if it gets a non integer.
Scanner.hasNextInt() on the other hand returns a boolean value to warn you in advance whether it has an integer or not - it does not take the value from the Scanner.
This code has a couple of tiny corrections that will achieve the outcome you stated.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
} else {
sc.next(); //Discard the non-integer input.fr
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}
Related
I need help making it so that the entire script will loop from the beginning if the user types y at the end and the script ends if the user types n at the end. Thanks for any help.
package test123;
import java.util.Scanner;
public class test321 {
public static void main(String[] args) {
int n = 1;
int c;
String playAgain;
do {
System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if ( n < 0 )
System.out.println("Number cant be a negative.");
else
{
int x=n*(n-1)*(n-2);
System.out.println("Factorial= "+x);
System.out.println("Do you want to continue? (y/n):");
playAgain = scanner.nextLine();
}while (!playAgain.equals("y"));
}
}
}
package test123;
import java.util.Scanner;
public class test321 {
public static void main(String[] args) {
int n = 1;
int c;
String playAgain;
do {
System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if ( n < 0 )
System.out.println("Number cant be a negative.");
else
{
int x=n*(n-1)*(n-2);
System.out.println("Factorial= "+x);
System.out.println("Do you want to continue? (y/n):");
playAgain = scanner.nextLine();
} // end else
} // end do
while (playAgain.equals("y"));
}// end main
} // end class
Change
while (!playAgain.equals("y"));
to
while (!playAgain.equals("n"));
I want to display the statement inside the else whenever the user type a negative number, I know this while loop will be infinite loop but I don't know how to break it. I try to type in "break", but it shows error:
need a return statement.
Should I use only if-statement or am I writing the right code?
import java.util.Scanner;
class number{
public static void main(String[] args){
workers();
int numEmployee;
}
public static int workers(){
System.out.println("How many employees do you have?");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
int numEmployee;
while(true){
if(number >= 0){
numEmployee = number;
return numEmployee;
}else{
System.out.println("Please enter a positive number");
}
}
}
}
Suggested changes:
import java.util.Scanner;
// Always capitalize your public class name (and the corresponding source file)
public class Number{
public static void main(String[] args){
// Get #/employees
int numEmployee = Number.workers();
System.out.println ("#/employees=" + numEmployee);
}
public static int workers(){
// Loop until we get a valid number
int number;
do {
System.out.println("How many employees do you have?");
Scanner input = new Scanner(System.in);
number = input.nextInt();
} while (number <= 0)
// Return the final value
return number;
}
}
First thing you want is to ask for input every loop. Also, you should have a return in your method for every condition. A compiler doesn't know your loop is infinite so it expects a return:
import java.util.Scanner;
class Number{
public static void main(String[] args){
int numEmployee = workers();
System.out.println("Number of empoyees: " + numEmployee);
}
public static int workers(){
int number = 0;
System.out.println("How many employees do you have?");
Scanner input = new Scanner(System.in);
while(true){
number = input.nextInt();
if(number >= 0){
return number;
}else{
System.out.println("Please enter a positive number");
}
}
return 0; //Added this
}
}
Your method should be:
public static int workers() {
System.out.println("How many employees do you have?");
Scanner input = new Scanner(System.in);
int number;
boolean isValid = false;
int numEmployee = 0;
while (!isValid) {
number = input.nextInt();
if (number >= 0) {
numEmployee = number;
isValid = true;
} else {
System.out.println("Please enter a positive number");
}
}
return numEmployee;
}
I have to write a java program that computes the greatest common divisor of two positive integers. Program has to check for the positive integers only. My problem is that when I enter a negative integer and then a non-numeric string, my program stops running. Bellow is my code:
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
System.out.print("Enter a positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
a = sc.nextInt();
while (a <= 0){
System.out.print("Please enter a positive integer: ");
a = sc.nextInt();
}
System.out.print("Enter another positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
b = sc.nextInt();
while (b <=0){
System.out.print("Please enter a positive integer: ");
b = sc.nextInt();
}
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
}
Try this:
import java.util.Scanner;
public class A {
public static void main (String[] args){
int a, b, m, n, remainder;
a = validInput();
b = validInput();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
static int validInput() {
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("Please enter a positive integer: ");
String tmp = sc.next();
if (tmp.matches("^\\d+$")) {
return Integer.parseInt(tmp);
}
}
}
}
I suggest you to make your programs more modular, as you can see it's benefits in a simple program like this.
/* prompt a */
String a = sc.next();
/* prompt b */
String b = sc.next();
if (isValid(a) && isValid(b)) {
int ia = Integer.parseInt(a);
int ia = Integer.parseInt(b);
/* calculations and such */
}
boolean isValid(String num) {
try {
int i = Integer.parseInt(num);
if (i < 0) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
return true;
}
It shound work, even if i don't try it. I have just 2 advise as you look new in coding :
-When you make code, try to use function. Normally, you should never copy/paste.
-Try to put full name to your variable, particulary if you share your code on a forum, it would be more simple to people to understand what you did, and help you :)
import java.util.regex.Pattern;
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
a=askInt();
b=askInt();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
private int askInt(){
System.out.print("Enter a positive integer: ");
String tampon = sc.nextLine();
while(!Pattern.matches("\p{Digit}",tampon)){
System.out.print("Please enter a positive integer: ");
String tampon = sc.nextLine();
}
return Integer.valueOf(tampon);
}
}
In your first while you call next(), but in your second you use nextInt(). If you enter at the first time a negative Integer, you ll step to the next while with the nextInt(). So you ll get an exception if the user is entering a String with something else than numbers, because the scanner cant get the value of keys or something else. A smarter way would be to catch the exception and use it for a endless while like this:
while(true)
System.out.print("Please enter a positive Number: ");
try{
a = sc.nextInt();
if(a>-1){
break;
}
}catch(Exception ignore){
}
}
This code will run until the user enters a positive number. If he enters something else than numbers, the exception will come and will be ignored and the while will go on, if the number was not positive (bigger than -1 in this case) the while will not break.
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++;}
}}
I want to take input of two variable as integer and than do addition with the two variables.
The ans will stored in another variable. The program will repeat after every addition end and will ask for user input of varibles and will do addition again.
My qus is taht how can i add all aditions ans again:
Exm:
Input a= 5
Input b=5
ans=10
Agin program will ask for
Input a= 6
Input b= 6
ans=12
now how can i take all " ans " value with program and do additions of all "ans"
Final Ans=10+12=22
code:
import java.io.*;
import java.util.Scanner;
public class math{
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
System.out.println("\nans is :"+c);
math ob_m=new math();
ob_m.add();
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
}
}
The code just do addition one after another but i want that it will do one more task that ....
It all add all aditions reasuts also. how can i do it?
import java.io.*;
import java.util.Scanner;
public class Test {
int a;
int b;
int sum = 0;
public void add() {
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
sum = sum + (a + b);
System.out.println("\nans is :" + (a + b));
}
public static void main(String args[]) {
Test ob_main = new Test();
while (true) {
ob_main.add();
}
}
}
Just keep adding the intermediate sums to another variable, so at the end you get the final total.
Another alternative (though not preferable when simple solution is available) is to put these sums in a list and at the end iterate through the list and calculate the final total.
Also, do not use ob_m.add(); - just call add();
Store every answer in an additional variable. Then when you're done, sum all the answer variables
You can use a loop for repeating your action, and store each addition in a total sum?
Change
public void add() {
Scanner keyboard = new Scanner(System.in);
int a;
int b;
int total = 0;
for(int i = 0; i < 2; i++) {
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c = a+b;
total += c;
}
System.out.println("\nans is :"+total);
}
Have a total variable which you just keep adding c to.
I also changed your unneeded recursion into a while-loop.
public class math
{
public static void main(String args[])
{
int total = 0;
Scanner keyboard = new Scanner(System.in);
while (true)
{
System.out.print("\nEnter a (-999 to quit): ");
int a = keyboard.nextInt();
// terminating condition, modify appropriately
if (a == -999)
break; // break out of the while-loop
System.out.print("Enter b: ");
int b = keyboard.nextInt();
int c = a + b;
total += c;
System.out.println("\nans is: " + c);
}
System.out.println("total is: " + total);
}
}
have a field GrandSUM,
GrandSum = 0;
and after every addition, add ans to it.
GrandSum += ans;
at the end , GrandSum will have result you want.
Edit:
import java.io.*;
import java.util.Scanner;
public class math{
int GrandSum = 0;//added
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
GrandSum += c;//added
System.out.println("\nans is :"+c);
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
//.....repeat as many times you want
ob_main.add();
System.out.println("grandsum: " + ob_main.GrandSum);
}
}
package farzi;
import java.util.ArrayList;
import java.util.Scanner;
public class dummy {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> sum = new ArrayList<Integer>();
String choice = "";
do{
System.out.println("enter the first number");
int a = keyboard.nextInt();
System.out.println("enter the second number");
int b = keyboard.nextInt();
int tempSum = a+b;
list1.add(a);
list2.add(b);
sum.add(tempSum);
System.out.println("Do you want to continue : type yes or no");
choice = keyboard.next();
}while(choice.toLowerCase().charAt(0)=='y');
System.out.println("here are the inputs with theri sum");
System.out.println("num1\t num2\t sum");
for(int i=0;i<list1.size();i++)
{
System.out.println(list1.get(i)+"\t"+list2.get(i)+"\t"+sum.get(i));
}
}
}