The following is a simple code that takes in two numbers and adds them in a gui. For some reason the output is not the sum of the two numbers, but is instead a random number. Please tell me what is going on. Here is my code:
import javax.swing.JOptionPane;
public class GUI {
public static void main(String[] args) {
String fn = JOptionPane.showInputDialog("Enter first number");
String sn = JOptionPane.showInputDialog("Enter second number");
int num1 = Integer.parseInt(fn); //Converts a string into an integer, since showInputDialog can only take in a string
int num2 = Integer.parseInt(fn);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "The answer is "+sum, "This is the title", JOptionPane.PLAIN_MESSAGE);
}
}
For example, if I enter the first and second numbers as 5 and 6 respectively, instead of an outcome of 11 I get an outcome of 10. Any help would be appreciated.
It shouldn't be a random number, it should be double the first number because num2 is also fn
int num2 = Integer.parseInt(fn);
This is likely a typo and should be:
int num2 = Integer.parseInt(sn);
Things like this are why you should name variables properly. ie. firstNumber and secondNumber it improves readability vastly and will likely result in it being easier to spot typos like this.
Related
I got this question on exam review "Write psuedocode for a program that reads a sequence of integer values and decides whether or not it is a decreasing sequence. The program will first read in the number of values to process, followed by the values themselves. The output will be “Yes” if the sequence is decreasing, and “No” otherwise."
Here is my code, but it sometimes does not stop,(for example, when you input 3 2 1). Can someone help me to figure out where I was wrong? Thank you!
import java.util.Scanner;
public class DecreasingOrNot {
public static void main(String[] args){
int number1, number2;
boolean decrease = true;
Scanner input = new Scanner(System.in);
System.out.println("Enter a sequence of numbers: ");
number2 = input.nextInt();
while (decrease && input.hasNext()){
number1 = number2;
number2 = input.nextInt();
if (number1 < number2){
decrease = false;
}
}
if (decrease){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
Right now, you have no way of breaking out of the loop if the user keeps adding decreasing numbers (which is why it won't break out of the loop if the user enters something like 3 2 1).
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
My question is - if I have for example two declared variables
int number1=0
int number2=0
And I have the input(assuming I declared the class and method beforehand):
System.out.println("Please enter a number between 0 and 20");
number1 = scanner.nextInt();
How do I make it so that it stores the last 2 values that were made so I can use those? I know that with these two lines of code I can store a value in number1, but I want number1 and number2 to constantly be the last two values that were inputted. Do I use a loop?
I'm still a beginner and trying to understand so perhaps there's something I'm completely missing about how the scanner works.
The required logic here is:
Copy the value from number1 to number2;
Copy the value from scanner.nextInt() to number1.
So your values shift along one position. This can be implemented as follows:
number2 = number1; // Now number1 == number2 temporarily.
number1 = scanner.nextInt();
you can use a temporary value,
int temp= scanner.nextInt();
number2= number1;
number1=temp;
Here ya go:
import java.util.*;
public class WhateverItIsYouWantToDo {
private static int number1;
private static int number2;
private static boolean blank = true;
public static void main(String args[]) {
System.out.println("Please enter a number between 0 and 20");
Scanner console = new Scanner(System.in);
do {
if (blank == true) {
number1 = console.nextInt();
blank = false;
} else {
number2 = number1;
number1 = console.nextInt();
}
} while (true); //note: this means the code will not terminate. you
// might want to make some way to make the code terminate at some point,
// or just do it manually.
}
The contents of the main method ought to do it. If you want to do that in a different method, just copy and paste the contents of the main into said other method.
Im not sure what you mean with
the last 2 values
I thinking about two scenarios:
1.- You want to continue asking the user for new Input until something happens like a special inputvalue than you could do a loop like this:
int number1=0;
int number2=0;
boolean continueAsking = true;
Scanner scan = new Scanner(System.in);
while(continueAsking)
{
System.out.println("Please enter a number between 0 and 20");
number1 = scan.nextInt();
scan.reset();
System.out.println("Please enter a number between 0 and 20");
number2 = scan.nextInt();
scan.reset();
if(/*number1 or number2 is something you want*/)
{
continueAsking = false;
}
}
2.- Another way of what you want to do(I'm sure this more what you want than way 1) could be copy number1 to number2 and than set number 1 the new value.
int input = scanner.nextInt();
number2 = number1;
number1 = input;
I am having difficulties with finding all possible odd numbers for my program. I am required to use a while loop to find all the odd numbers but i am not sure how to print it out. I dont know if im doing anything wrong in this block while((num1+num2)%2==0) because that was just a guess. Outline of the program is to get the user to enter 2 numbers that is an even multiple of the other number. I am not sure how that part either. After finding 2 numbers that is an even multiple of the other number, i am supposed to display all the odd numbers between the two numbers. Thanks alot in advance.
import java.util.Scanner; //imports the java utillity scanner
public class MyPrompter{
public static void main(String[] args){
System.out.println("Odd number display");
Scanner input = new Scanner(System.in); //scans for user input and stores in "input"
int num1,num2; //declares the variables i need for the pgrm
try{ //try statement to check for user input errors
System.out.println("Please enter your first number: ");
num1 = input.nextInt(); //stores input for the first number
System.out.println("Please enter your second number: ");
num2 = input.nextInt(); //stores input for the second number
while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers
System.out.println();
}
}
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid ROUNDED NUMBER!");
}
}
}
How about something like this:
int num1 = 10;
int num2 = 50;
int current = num1;
while (current < num2) {
if (current % 2 != 0) {
System.out.println(current);
}
current++;
}
Set current to equal num1, continue the loop while current is less than num2. For each iteration check if current is odd and output it if it is. Increment current by one.
Im working on an assignment for an intro to java class, and having a difficult time, the problem is given as follows:
"Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same."
I am having trouble getting the input dialog boxes to fit into my code and converting that input to integers that I can use for the calculations. Additionally I am not sure of how to account for the user entering more numbers than two, but Im not gonna go into that right now.
Any help would be appreciated, thanks in advance!
Here is what I have so far:
package findingminandmax;
import javax.swing.JOptionPane;
public class Findingminandmax
{
public static void main(String[] args)
{
int i = 3;
int j = 2;
int k = max(i, j);
JOptionPane.showMessageDialog(null, "The maximum between " + i +
" and " + j + " is " + k);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
For the input, use:
String s = JOptionPane.showInputDialog(message));
If you want to convert it to a integer:
int i = Integer.parseInt(s);
To a float:
float f = Float.parseFloat(s);
Or to a double:
double d = Double.parseDouble(s);
Also, in order to accept more than 1 input, you could use a for loop or a while:
int n = 5; // Number of times the input will be requested
for (int i = 0; i < n; i++) {
...
// Code here to accept the input
String s = JOptionPane.showInputDialog(message));
...
}
If you are going to store many inputs, you may want to store them in an array.
ArrayList