javax.swing.JComponent cannot be resolved - java

I'm a beginner at Java programming. I encountered an error -
javax.swing.JComponent cannot be resolved whenever I execute the following program.
import javax.swing.JOptionPane;
class apples
{
public static void main(String args[])
{
String a = JOptionPane .showInputDialog("Enter a number");
String b = JOptionPane.showInputDialog("Enter another number");
int num1 = Integer.parseInt(a);
int num2 = Integer.parseInt(b);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null,"Sum is "+sum, Answer,JOptionPane.PLANE_MESSAGE);
}
}
Can anyone please suggest a solution?

public static void main(String[] args) {
String a = JOptionPane .showInputDialog("Enter a number");
String b = JOptionPane.showInputDialog("Enter another number");
int num1 = Integer.parseInt(a);
int num2 = Integer.parseInt(b);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null,"Sum is "+sum, "Answer",JOptionPane.PLAIN_MESSAGE);
}
You were using incorrect JOptionPane. You need to use PLAIN_MESSAGE instead of PLANE_MESSAGE. Also the Answer field which is the title needs to be a string
I suggest using an IDE like eclipse or netbeans so that you can avoid such issues.

Related

How to modify JOptionPane method in Java

Please, I need your help. Whenever I tried to run the below program, it will say incompatible types, String cannot be converted to Integer.
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
String num1 = (Integer)JOptionPane.showInputDialog("Enter num1");
String num2 = (Integer)JOptionPane.showInputDialog("Enter num2");
String sum =
(Integer)String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
}
}
To expound on the other answers and show the code, here is what you need to make it work:
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
int num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter num1"));
int num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter num2"));
String sum = String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
}
}
You want to take the input from the JOptionPanes as an ints then add them and put the result in a string, not cast a string to an int.
NOTE: I wrote this on my mobile, so I’ll compile and run it when I get home, but above is the general idea.
Your best bet is to take an int in the first place.
int num1 = Integer.parseInt(JOptionPane...
And you can either do the same with the output, or parse it again.
Its because your typecasting a String to an Integer and trying to store it in a String.
Remove (Integer) from the statement to get rid of that error.
Try this
int num1 = Integer.valueOf(JOptionPane.showInputDialog("Enter num1"));
int num2 = Integer.valueOf(JOptionPane.showInputDialog("Enter num2"));
String sum = String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
It's seems you want, something like this:
public static void main(String[] args) {
Integer num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter num1"));
Integer num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter num2"));
String sum = String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
}

How do I use a function involving integers?

We have an assignment in class to create a greatest common divider (gcd) program using functions. I missed out on the lesson where we learned how to properly use them. I finished the part that actually does the division but I don't know how to separate it into a function and have it work. I'd like to have the input in the main class and the process in function.
This is what I have, it does not work when I run it
package gcd.function.java.program;
import java.util.Scanner;
/**
*
* #author sarah_000
*/
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
int div;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
System.out.printf("The GCD is %d ", div);
}
public static void GCDFunction() {
if(num1 > num2)
div = num2;
else div = num1;
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
}
}
Any tips or help you can give to me will be greatly appreciated, I'm very new
You declare two parameters and modify the return type in your GCDFunction like this:
public static int GCDFunction(int num1, int num2)
You are currently trying to access the variables in the main method but are out of scope.
Also, you never actually call your GCDFunction
Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do
public static void GCDFunction(int num1, int num2)
That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.
So once you have that function set up to receive the variables and output after processing, you call the function in the main with a
GCDFunction(num1, num2);
Where num1 and num2 are the variables that have your integers stored in.
The end result after a little rearranging looks like this.
import java.util.Scanner;
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
GCDFunction(num1, num2);
}
public static void GCDFunction(int num1, int num2) {
int div;
if(num1 > num2){
div = num2;
}
else{ div = num1;}
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
System.out.printf("The GCD is %d ", div);
}
Trying to give you a example of how the code should be to take in variable number of parameters.
public int gcd(Integer... numbers) {
int gcd = 1;
int miNNumber=Collections.min(Arrays.asList(numbers));
boolean isDivisible;
for(int i=2; i<=miNNumber;i++) {
isDivisible=true;
for(Integer eachNumber : numbers) {
if(eachNumber%i!=0) {
isDivisible=false;
break;
}
}
if(isDivisible) {
gcd=i;
}
}
return gcd;
}
You can call it
gcd(10, 200, 400);
or
gcd(10, 200, 400, 4000, 40);

JAVA Greatest common divisor recursion

I can't get this to run.There is a tester program and a method below. it says error identifier expected.Thanks in advance
public class 121tester{
public static void main(String[]args){
Scanner input= new Scanner(System.in)
System.out.println("Enter first number");
int num1=input.nextInt();
System.out.println("Enter second number");
int num2=input.nextInt();
System.out.println("The Greatest common factor of "+num1+" "+num2+" is "+GCD(num1,num2));
}
}
private static int GCD(int num1, int num2){
if(num2==0){
return num1;
}
return(GCD(num2, num1%num2);
}
Class name can't start with number. Change from
class 121tester
to
class Tester121
Another thing your GCD method should declare into inside class. It is better to use some IDE at initial stage of programming to remove compiler error.
Try the following:
import java.util.Scanner;
public class GCDTester{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int num1 = input.nextInt();
System.out.println("Enter second number");
int num2 = input.nextInt();
System.out.println("The greatest common factor of " + num1 + " " + num2 + " is " + gcd(num1,num2));
}
private static int gcd(int num1, int num2){
if (num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
}
But #Masud is correct, you should place the gcd method in a class of its own so that it can be used as an object in its own right.

Java fraction calculator, global variables?

This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}

Basic Java: How to call a method?

I'm trying to create a program that includes a menu and will execute whatever choice the user chooses. I completed the methods and got them to compile, but am lost on how to call the classes. Here is the code in screenshots so they're easier to read:
Geek Class: (Contains all the methods)
public class Geek{
private String name;
private int numberofQuestions=0;
public Geek (String name){
this.name = name;
numberofQuestions = 0;
}
public String getName(){
return name;
}
public int getnumberofQuestions(){
return numberofQuestions;
}
public boolean allTheSame(int num1, int num2, int num3){
numberofQuestions++;
if(num1 == num2 && num2 == num3 && num1 == num3){
return true;}
else return false;
}
public int sum (int num1, int num2){
numberofQuestions++;
int largest = Math.max(num1, num2);
int smallest = Math.min(num1, num2);
int result =0;
for (int i=smallest; i <= largest;i++){
result = result + i;}
return result;
}
public String repeat(String str, int n){
numberofQuestions++;
String repetition = "";
for (int j=0; j < n; j++){
repetition = repetition + str;}
return repetition;
}
public boolean isPalindrome(String str){
numberofQuestions++;
int n = str.length();
for( int i = 0; i < n/2; i++ )
if (str.charAt(i) != str.charAt(n-i-1)) return false;
return true;
}
}
Main:
http://i.imgur.com/DvJ0LU5.png
EDIT: Im getting a cannot find symbol error in this section of code:
case "d":
myGeek.sum(num1, num2, num3);
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
System.out.println("Enter the third number");
int num3 = scan.nextInt();
break;
Classes aren't called, they are blueprints for creating objects.
You need a program entry point, in this case inside your class like so
public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
}
you can then call the methods on your created object
public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
String geekName = myGeekObject.getName();
}
In Java (and any other languages I know), you can only call methods/functions, but not classes (except you count <clinit>). So you could write:
Geek geek = new Geek("Me");
int i = geek.sum(1, 2);
System.out.println(String.valueOf(i));
Assuming the file Geek.java, you can then call/run the class using:
javac Geek.java
java Geek
from the commandline.
Note that this will only succeed if Geek.java contains a main method. Read about them here.
You need to create instance of object and then you can use it
For example:
Geek g = new Geek("Geek");
g.getName();
You need to instantiate an instance of the class in order to use it.
For example, in your main method you may want to define an instance of the object like so:
Geek myGeek = new Geek("user2943817");
You can than access all instance methods on the object using the variable name like so:
myGeek.getName();
I hope this helps!
EDIT :
As for your new issue, simply call the method after you obtain the values from the user. Like this:
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
System.out.println("Enter the third number");
int num3 = scan.nextInt();
myGeek.sum(num1, num2, num3);
break;
You cant use non-static class like that.
Imagine that Geek is definition of Geek. You want to create several geeks, each one is standalone instance.
Geek g1 = new Geek("Andrew");
Geek g2 = new Geek("John");
These lines create two instances g1 and g2 of type Geek with name Andrew and John
Then you access them like this :
g1.repeat("myString", 10)

Categories

Resources