I'm getting the prompt to enter an integer but nothing after that. Can someone tell me why my results are not printing?
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
if (x == z && y == y && z == x)
System.out.println(answer + " is a palindrome! ");
else
System.out.println(answer + " is not a palindrome");
}
}
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
Your code is waiting for 4 different inputs. If you input all 4, it will run - but something is clearly wrong with your logic.
As others mentioned, you are a) working with doubles and b) trying to read too many numbers:
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
// Read an int
int answer = 0;
try {
answer = input.nextInt();
}
catch (InputMismatchException ex) {
// Handle error
}
// Make sure it's 3 digits
if (answer < 100 || answer >= 1000) {
// Do something with bad input
}
else {
// Just need to check if first and third digits are equal.
// Get those values using integer math
int digit1 = answer / 100;
int digit3 = answer % 10;
if (digit1 == digit3) {
System.out.println(answer + " is a palindrome! ");
}
else {
System.out.println(answer + " is not a palindrome");
}
}
}
}
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
/*
OUTPUT:
Enter a string : MADAM
Entered string is a palindrome.
Enter a string : 15351
Entered string is a palindrome.
*/
You are using wrong logic here.If you want to check for palindrome, you should not use double.Hope this code helps!
Related
I was asked to write a simple calculator that could run many times as long as the user inputs 'yes' when asked "would you like to perform another operation".
so I did it using a separate method that would be used in a loop in the main method, the problem is it wont run more than twice if the answer is yes
import java.util.Scanner;
public class Calc2 {
// method to be called
static String calcmethod() {
#SuppressWarnings("resource")
Scanner Operation = new Scanner(System.in);
System.out.println("choose operation to perform");
float x, y, sum, sub, mul, div;
String g;
g = Operation.nextLine();
if (g.equals("addition")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sum = x + y;
System.out.print(sum + "\n");
} else if (g.equals("subtraction")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sub = x - y;
System.out.print(sub);
} else if (g.equals("multiplication")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
mul = x * y;
System.out.print(mul);
} else if (g.equals("division")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
div = x / y;
System.out.print(div);
} else {
System.out.println("invalid input \n");
}
System.out.println("would you like to peform another operation \n");
Scanner Flow = new Scanner(System.in);
String w;
w = Flow.nextLine();
return w;
}
public static void main(String[] args) {
String z = calcmethod();
if (z.equals("yes")) {
calcmethod();
} else {
System.out.println("end of program");
}
}
}
Use do-while loop as shown in below example:
public static void main(String[] args) {
String z = "";
do {
z = calcmethod();
} while(z.equals("yes"));
System.out.println("end of program");
}
I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}
I know this question has been asked several times already. Feel free to mark it as a duplicate. Anyway, I'd rather ask the community since I am still uncertain.
I should convert this while loop in a do-while loop.
Any thoughts?
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
int number = input.nextInt();
while (number != 0) {
sum += number;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
}
}
}
You cant just simple convert any while loop to do while loop , the main difference between them is in do while loop you have an iteration that will happen regardless of the condition.
public class DoWhile {
public static void main(String[] args) {
int number=0;
Scanner input = new Scanner(System.in); int sum = 0;
do{ System.out.println("Enter an integer " +"(the input ends if it is 0)");
number = input.nextInt();
sum += number;
}while (number != 0) ;
}
}
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int number = 0;
do {
System.out.println("Enter an integer " +
"(the input ends if it is 0)");
number = input.nextInt();
sum += number;
} while(number != 0)
}
}
You have to tell the program to continue doing something in the "do" block. In your own case you have to tell the program to keep doing this"
System.out.println("Enter an integer " + "(the input ends if it is 0)"); number = input.nextInt();
sum += number;". Then in the "while" block you will have to provide the terminating statement, in your own case "number != 0"
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int number;
do {
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
sum += number;
} while (number != 0);
}
}
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); int sum = 0;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
int number = input.nextInt();
//You need this if statement to check if the 1st input is 0
if(number != 0)
{
do
{
sum+=number;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
}while(number != 0);
}
}
}
classInfoClass
{
public void setinfo()
{
int userage;
do
{ Console.Write("Please enter your age: ");
} while (!int.TryParse(Console.ReadLine(),out userage));
So I am taking Java as part of math degree requirements and have stumbled on a problem with this code. Essentially the code is supposed to take in numbers from the user until they type a zero. It works fine as long as only numbers are entered. However if the user enters a letter or symbol the program gets an exception. Is there a simple way I can validate user input as a number without getting an exception?
import java.util.Scanner;
public class SamsAdder
{
public static void main(String[] args)
{
double userInput = 1;
double sum = 0;
Scanner in = new Scanner (System.in);
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
}
System.out.println("The sum of the numbers is " + sum + ".");
}
}
So I've tried the try/catch as you showed it. I'm still getting an exception with non numbers though. Entered the code as follows:
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
try{
userInput = in.nextDouble();
}
catch(NumberFormatException nfe){
System.out.println("Invalid Number");
}
sum = sum + userInput;
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class SamsAdder {
public static void main(String[] args) {
double userInput = 1;
double sum = 0;
Scanner in = new Scanner(System.in);
while (userInput != 0) {
try {
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
} catch (InputMismatchException nfe) {
System.out.println("Invalid Number");
in.next();
}
}
in.close();
System.out.println("The sum of the numbers is " + sum + ".");
}
}
I have an assignment to break an integer into it's individual digits, report them back to the user, and add them. I can do that, but I'm struggling with supporting negative integers. Here's my code, which works exactly the way I want it to, but only for positive integers:
import java.util.*;
public class Module4e
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i]);
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I've found plenty of hints for getting this to work with positive integers, but none for negatives.
Use RegExp
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestDigits {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Validate Input
String number = console.nextLine();
Pattern p = Pattern.compile("(-?[0-9]{1})+");
Matcher m = p.matcher(number);
if (!m.matches()) {
throw new IllegalArgumentException("Invalid Numbers");
}
// Calculate
p = Pattern.compile("-?[0-9]{1}+");
m = p.matcher(number);
int result = 0;
System.out.print("The digits of the number are: ");
while (m.find()) {
System.out.print(m.group() + " ");
result += Integer.valueOf(m.group());
}
System.out.println("");
System.out.println("Result " + result);
}
}
// I think you can use this code //also you can multiply the number by -1
int positive = 0;
//positive give you information about the number introduced by the user
if (myNum.charAt(0)=='-'){
positive=1;
}else{
positive=0;
for (int i=positive; i<myNum.length(); i++){
//be carefull with index out of bound exception
if ((i+1)<myNum.length()){
upNum[i]=myNum.substring(i,i+1);
}
}
Change the statement String myNum=console.nextLine() to String myNum = String.valueOf(Math.abs(Integer.valueOf(console.nextLine())));
You do not have to use String to solve this problem. Here's my thought.
import java.util.*;
public class Module4e throws IllegalArgumentException {
static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
if (!console.hasNextInt()) throw new IllegalArgumentException();
int myNum=console.nextInt();
myNum = Math.abs(myNum);
int sum=0;
System.out.println("\n");
System.out.print("The digits of the number are: ");
While (myNum > 10) {
System.out.print(myNum % 10);
System.out.print(" ");
sum += myNum % 10;
myNum /= 10;
}
System.out.println(myNum);
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
Try this. I gave -51 as input and got -6 as output. This is what you are looking for?
import java.util.*;
public class LoggingApp
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
int multiple = 1;
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
Integer myNumInt = Integer.parseInt(myNum);
if (myNumInt < 1){
multiple = -1;
myNum = Integer.toString(myNumInt*-1);
}
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i])*multiple;
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}