import java.util.Scanner;
public class Exercise5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt(5);
System.out.print("Input second number: ");
int num2 = in.nextInt(25);
System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
}
}
**Here is my java code, the expect output should be like this:
Input first number: 25
Input second number: 5
25 x 5 = 125
After I plug in my code and run it, the output is too different with the answer
Here is the output:
Input first number: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)
How can I fix my code?
"5" in in.nextInt(5); means radix. Do you need it? Does the program work if you use nextInt() method with no parameters?
Also, for some reason both of versions work for me with no error:
// output of nextInt(radix) version
java Excercise5
Input first number: 32
Input second number: 23
17 x 53 = 901
// output of nextInt() version
java Excercise5
Input first number: 5
Input second number: 25
5 x 25 = 125
There are 2 nextInt() methods:
nextInt() alone allows you to read an int in base 10 number
nextInt(radix) reads the next number in base N where N is 5, or 25 in your case
So, call the first one and you're done
You shouldn't put 5 and 25 inside brackets of in.nextInt, you will write value inside console line and scanner will read it.
So instead
int num1 = in.nextInt(5);
it should look like
int num1 = in.nextInt();
No need to specify the radix to nextInt.
Just use the no args version of nextInt.
Replace
int num1 = in.nextInt(5);
with
int num1 = in.nextInt();
And
int num2 = in.nextInt(25);
with
int num2 = in.nextInt();
FIXED CODE
import java.util.Scanner;
public class Exercise5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
total = num1*num2
System.out.println(num1 + " x " + num2 + " = " + total);
}
}
Your nextInt() will catch the user input so there is no need to put in values. You will manually put them in when prompted on the output window in your IDE.
I would also put the num1 and num2 into separate variables (Ex. int total = num1*num2) then print out the total in the println :)
EDIT: Didn't even notice you were supplying an argument to nextInt(). As the other mentioned, this is not what you want to do.
Also, the new line character is still in the buffer after you call nextInt(). You'll need to fix this as well before your program will operate as you intend.
Understanding Scanner's nextLine(), next(), and nextInt() methods
Related
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;
I'm trying to get familiarized with for loops right now for school and and learning the syntax right now. I have a couple questions. If I am going to initialize variables in the loop how can I ask the user for them to input the variable values before they are in the for loop? Here is the code I have written for it so far.
Also my scanner won't work for me in this code. I've been working on it for little bit so I figure it might need a second look.
import java.util.Scanner;
public class forloop
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter your first of two numbers:");
num1 = input.nextInt();
System.out.print("Enter the second number:");
num2 = input.nextInt();
for(int num1 ; counter <= num2; counter ++)
System.out.println("There are " + counter + " numbers between " +
num1 + " and " + num2);
}
}
Thanks in advance for any help
You could assign the user's input into temporary variables and then inside your loops initialize the user's inputs to be those temporary variables.
import java.util.Scanner;
public class forloop
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter your first of two numbers:");
int temp1 = input.nextInt();
System.out.print("Enter the second number:");
int num2 = input.nextInt();
for(int num1 = temp1; counter <= num2; counter ++)
System.out.println("There are " + counter + " numbers between " +
num1 + " and " + num2);
}
}
I think this is the simplest possible solution:
public class forloop
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter your first of two numbers:");
num1 = input.nextInt();
System.out.print("Enter the second number:");
num2 = input.nextInt();
for(int x = num1 ; counter <= num2; counter ++)
System.out.println("There are " + counter + " numbers between " +
num1 + " and " + num2);
}
}
In the first expression in a for loop, you need to declare the variable that is controlling the loop and assign it a value - num1 in your case. In the second expression, you need to put the condition on which the loop keeps iterating - I am not really sure what you meant by counter. The problem is that this variable has not been declared. You need to declare it before you can use it. What do you want your program to do?
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");
}
}
}
I am trying to write a method that will subtract multiple numbers instead of using just 2 input numbers.
So far I have...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
double difference = 0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
double valueTwo = in.nextInt();
difference = value - valueTwo;
}
System.out.println("Difference: " + difference);
}
this currently only works with 2 inputs, but my end goal is to be able to continue subtracting multiple numbers.
Instead of continually subtracting from value, instead subtract from difference
Change difference = value - valueTwo; to difference -= valueTwo
This will be equivalent to doing ((A - B) - C) - ..., A being the first input, B the second input, C the third input...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double difference = in.nextDouble();
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
This should work fine
#include <stdio.h>
int main()
{
int result=0, n,number,i;
printf("How many numbers you want to use?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d", &number);
if(i ==0 ){
result=number;
}
else{
result -= number;
}
}
printf("Answer is= %d ", result);
return 0;
}
Output:
How many numbers you want to use?
4
55
34
1
3
Answer is= 17
This solution doesn't hang after the first input. It is more user friendly.
public static void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the next number: ");
double difference = 0.0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
Why have two variables? Anyway, the following is simpler and prompts correctly:
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
while (true) {
in.nextLine(); // Silently discard rest of line
System.out.print("Please enter the next number, or . to stop: ");
if (! in.hasNextDouble())
break;
value -= in.nextDouble();
}
System.out.println("Difference: " + value);
Test
Please enter the number: 10
Please enter the next number, or . to stop: 1
Please enter the next number, or . to stop: 2
Please enter the next number, or . to stop: 3
Please enter the next number, or . to stop: .
Difference: 4.0
I can't get this to work properly. It functions as it is supposed to, and does the math, but then it loops once, and ends. I need it to either loop until the users decides to end it, or only run once.
import java.util.Scanner;
public class java {
public static void main(String args[]) {
System.out.println("Welcome to the simple Calculator program");
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
Scanner input = new Scanner(System.in);
int math = input.nextInt();
if (math == 1) {
Scanner a = new Scanner(System.in);
int a1;
int a2;
int asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.print("The sum is: " + asum + "Thank You for using this program");
}
Scanner number = new Scanner(System.in);
int number1;
int number2;
int sum;
System.out.print("Enter first number: ");
number1 = number.nextInt();
System.out.print("Enter Second number: ");
number2 = number.nextInt();
sum = number1 + number2;
System.out.printf("Sum is %d\n", sum);
}
}
Use
do{
// do something.
} while(some condition);
And reapeat the same scanner to get input. You can also add one more option to your menu for repeating and evaluate that with while condition.
It is working as it should.
If you want it to loop as per some user input,you must use any looping construct like while.
Instead of if (math == 1) use
`while (math != exit)`
Make a new entry for exit like 0
Try using while loop. Give the user an option to quit the program.
import java.util.Scanner;
public class java
{
public static void main(String args[])
{
Scanner a = new Scanner(System.in);
System.out.println("Welcome to the simple Calculator program");
while(true)
{
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
System.out.println("6=Quit"); // added an option to quit the program
int math = a.nextInt();
if (math == 1)
{
int a1,a2,asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.println("The sum is: " + asum + "Thank You for using this program");
}
// Include actions for math = 2 to 5
if(math == 6)
{
System.out.println("Thank You for using this program");
System.exit(0);
}
}
}
}
The options are displayed again and again after each calculation until the user wants to exit the program by entering 6.
If you want the program to run only once, you should leave out the outer while loop. Everything else remains the same.
PS - You don't need to reopen Scanner again and again (at least not in this problem).
That is because you are only reading the input from the console once..you need to keep the console up with something like while(true) {} or monitor the console for an exit conditon like (" 0 = exit ") .
Also, I don''t think you will need to read two numbers again and again like you are doing right now.
1) You can use a do-while loop with a condition till which you wish to execute.
2) Use a switch case and perform the math operations inside the switch case with different operators. As of now you are trying to perform only addition. So you a switch case where you can perform all the operations.
3) In the switch case have an option which calls the exit(0) method. So that you can run the program until the user wish to exit.
4) By using a switch case you can make the user to choose his own option.
Your entire program is correct dude.
Just add
System.exit(0);
In every if(math==1) ,if(math==2)...before their statement ending.
like if(math==1)
{
...
System.exit(0);
}
You can fix your error...
Like me if your error is fixed. If not tell me the error