import java.util.Scanner;
public class Power1Eng {
public static void main(String[] args) {
double x, prod = 1;
int n;
String s;
Scanner input = new Scanner(System.in);
System.out.print("This program prints x(x is a real number) raised to the power of n(n is an integer).\n");
outer_loop:
while (true) {
System.out.print("Input x and n: ");
x = input.nextDouble();
n = input.nextInt();
for (int i = 1; i <= n; i++) {
prod *= x;
}
System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
s = input.nextLine();
if (s.equals("Y"))
continue;
else if (s.equals("N"))
break;
else {
inner_loop:
while (true) {
System.out.print("Wrong input. Do you want to continue?(Y/N) ");
s = input.nextLine();
if (s.equals("Y"))
continue outer_loop;
else if (s.equals("N"))
break outer_loop;
else
continue inner_loop;
}
}
}
}
}
Look at the Console. In the third line, I expected the program prints until the first 'Do you want to continue?(Y/N)', but it also prints 'Wrong input. Do you want to continue?(Y/N)'. How can I fix this problem?
When you do the nextInt and nextDouble, it doesn't clear the (empty) rest of the line.
You need to call nextLine after reading these values to clear the rest of the line.
System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) \n", x, n, prod);
s = input.next();
That will solve your problem and also do not use labels.
Should I avoid using Java Label Statements?
People who get to maintain that code will find you.
Related
at this program once the exception is caught, the program displays the catch message and program terminates successfully by itself (I need to run the program again manually if want to ask the user input). I dont want the program to finish but automatically it should ask the user to enter a valid number and performs the functions from the beginning, how to write for this?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter a Whole Number to divide: ");
int x = sc.nextInt();
System.out.println("Enter a Whole number to divide by: ");
int y = sc.nextInt();
int z = x / y;
System.out.println("Result is: " + z);
}
catch (Exception e) {
System.out.println("Input a valid number");
}
finally{
sc.close();
}
}
}
Output
Enter a Whole Number to divide:
5
Enter a Whole number to divide by:
a
Input a valid number
Process finished with exit code 0
There are some issues with nextInt that you need to be careful about, You can check out this link: Scanner is skipping nextLine() after using next() or nextFoo()?.
For your program, use a while loop, and you need to be aware of Y could be 0, which would cause an ArithmeticException.
while (true) {
try {
System.out.println("Enter a Whole Number to divide: ");
// use nextLine instead of nextInt
int x = Integer.parseInt(sc.nextLine());
System.out.println("Enter a Whole number to divide by: ");
int y = Integer.parseInt(sc.nextLine());
if (y == 0) {
System.out.println("divisor can not be 0");
continue;
}
double z = ((double) x) / y
System.out.println("Result is: " + z);
break;
}
catch (Exception e) {
System.out.println("Input a valid number");
}
}
sc.close();
i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;
So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
import java.util.Scanner;
class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int testNumber = userInput.nextInt();
do{
System.out.println(newNumber * 2);
newNumber++;
}while( testNumber < 1000000);
}
}
You need to update the number after you multiply it by 2:
newNumber = newNumber * 2;
System.out.println(newNumber);
Also you are using newNumber and testNumber and newNumber doesn't appear to be defined anywhere...
}while( ***testNumber***newNumber*** < 1000000);
You need to pick one because if you are updating newNumber but comparing testNumber in your loop you will have created an infinite loop.
The code you have shown shouldn't compile unless you are leaving something out of your post.
You have the right idea with your loop, but you have multiple problems with your variables.
Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
Your second problem is that you are testing the unchanged variable as your stop condition.
You probably want your loop to be something like:
do {
testNumber = testNumber * 2;
System.out.println(testNumber);
} while(testNumber < 1000000);
You can also make a recursive method for it.
public int reachMillion(int num) {
if(num<=0)
return -1; // indicating it is not possible.
if(num>=1000000) // Base Condition denoting we have reached 1 million
return num;
return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}
class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int newNumber = 0;
do{
System.out.println("Enter a positive number: ");
try{
newNumber = userInput.nextInt();
}catch(Exception ignored){ }
System.out.println("");
}while(newNumber <= 0);
System.out.println("----- " + newNumber + " multiply by 2 ------");
while(newNumber <= 1_000_000){
System.out.print("2 * " + newNumber +" = ");
newNumber <<= 1;//in some compilers left shift is faster than multiply
System.out.println(newNumber);
}
}
#brso05 has done well describing what went wrong here. I'd like to offer a complete example:
import java.util.Scanner;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please input a number: ");
int userInputNumber = userInputScanner.nextInt();
System.out.println();
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
Beware! That code does not handle any bad user input. For instance, if you give it 0, it will loop forever, and if you give it foo, it will crash. In case you want to handle all the edge cases of user input, this will do that:
import java.util.*;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
int userInputNumber;
//
while(true) {
System.out.print("Please input a number: ");
if (userInputScanner.hasNext()) {
// The user gave us something, but we don't know if it's a number
String rawUserInput = userInputScanner.next();
try {
userInputNumber = Integer.parseInt(rawUserInput);
// If that previous line runs, the user has given us an integer!
System.out.println();
if (userInputNumber > 0) {
// The user has given a valid number. Break out of the loop and multiply it!
break;
}
else {
// The user has given a bad number. Tell them why and ask again.
System.out.println("The number has to be greater than 0.");
}
}
catch (NumberFormatException exception) {
// The user has given us something, but it wasn't an integer
System.out.println();
System.out.println("That is not a number: " + exception.getMessage());
}
}
else {
// There is no input, so we can't do anything.
return;
}
}
// Done looping through user input
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
There is a tricky part of do-while loops. In that type of loops, do part is executed firstly. For the example below, although the input is already bigger than 1000000, it prints 1000001.
public void doWhileLoop() {
int num = 1000001;
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
Therefore, it will be a good idea to use some guard-clauses (aka, if-statements) before doing something in do-while loops. Like,
public void doWhileLoop() {
int num = 1000001;
if(num >= 1000000) {
return;
}
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
import java.util.Scanner;
public class Power1Eng {
public static void main(String[] args) {
double x, prod = 1;
int n;
String s;
Scanner input = new Scanner(System.in);
System.out.print("This program prints x(x is a real number) raised to the power of n(n is an integer).\n");
outer_loop:
while (true) {
System.out.print("Input x and n: ");
x = input.nextDouble();
n = input.nextInt();
for (int i = 1; i <= n; i++) {
prod *= x;
}
System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
s = input.nextLine();
if (s.charAt(0) == 'Y')
continue;
else if (s.charAt(0) == 'N')
break;
else {
inner_loop:
while (true) {
System.out.print("Wrong input. Do you want to continue?(Y/N) ");
s = input.nextLine();
if (s.charAt(0) == 'Y')
continue outer_loop;
else if (s.charAt(0) == 'N')
break outer_loop;
else
continue inner_loop;
}
}
}
}
}
There was only trivial logical error when I used just next() method, but when I changed
next() method to nextLine() method, this error shows.
How can I fix this problem?
There are two problems. The first is that your string could be empty, and then fetching the first character will give an exception.
if (s.charAt(0) == 'Y') // This will throw if is empty.
Either test the length of the string to see if there is at least one character, or just use String.startsWith instead of charAt:
if (s.startsWith('Y'))
The second problem is that you entered a new line after your first input, and nextLine reads up to the next new line character only.
You could check for an initial character count, to make sure there are the correct number of characters that you expect. i.e:
while (true)
{
// ... some code ...
if (s.length() < 1)
{
continue;
}
// ... some code ...
}
This way, you wouldn't even have to continue running the rest of the code, which if the code base were larger, would help to optimize performance.
The "red text" that you see in the console is an indication of text being sent to standard error. In this case, it is an indication that your program has crashed.
The main problem you are encountering is with this logic:
System.out.print("Input x and n: ");
x = input.nextDouble();
n = input.nextInt();
for (int i = 1; i <= n; i++) {
prod *= x;
}
System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
s = input.nextLine();
Suppose the user input is:
2.1 4(enter)
input.nextDouble() will take 2.1, leaving 4(enter) on the standard input stream.
input.nextInt() will take 4, leaving (enter) on the standard input stream.
input.nextLine() will take "" (empty string), finally clearing the (enter) from the initial user input of x and n.