I'm writing a program for my class where I have to use a for loop to takes two numbers from the keyboard. The program should then raise the first number to the power of the second number. Use a for loop to do the calculation. I'm getting the error that inum3 is not being initialized (I understand because the loop may never enter) but I cannot figure out how to make this work. Line 25 and 28 to be specific.
import javax.swing.*;
public class Loop2
{
public static void main(String[] args)
{
int inum1, inum2, inum3, count;
String str;
str = JOptionPane.showInputDialog("Please Enter a Numer");
inum1 = Integer.parseInt(str);
str = JOptionPane.showInputDialog("Please Enter a Numer");
inum2 = Integer.parseInt(str);
for (count = 1; count == inum2; count+=1)
{
inum3 = inum3 * inum1;
}
JOptionPane.showMessageDialog(null, String.format ("%s to the power of %s = %s", inum1,inum2, inum3), "The Odd numbers up to" + inum1,JOptionPane.INFORMATION_MESSAGE);
}//main
}// public
you need to initialize the variable inum3. As it stands right now, when your program tries to execute
inum3 = inum3 * inum1;
inum3 has no value, so it can't do the multiplication.
I think you want it to be 1 in this case.
So instead of
int inum1, inum2, inum3, count;
you can do
int inum1, inum2, inum3 = 1, count;
initialize num3 to one because you cand use something to define itself.
num3 = one;
import javax.swing.JOptionPane;
public class Loop2 {
public static void main(String[] args) {
int base, exp, result = 1;
String str;
str = JOptionPane.showInputDialog("Please Enter a Number");
base = Integer.parseInt(str);
str = JOptionPane.showInputDialog("Please Enter an Exponent");
exp = Integer.parseInt(str);
for (int count = 0; count < exp; count++) {
result *= base;
}
JOptionPane.showMessageDialog(null, String.format("%s to the power of %s = %s", base, exp, result),
"The Odd numbers up to" + base, JOptionPane.INFORMATION_MESSAGE);
}
}
Related
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
My Java code should let the user enter a number and then calculate the factorial of that number and I need to use "for loop" When I enter number 5 it tells me the factorial is 6 when it should be 120. I have tried to watch tutorials with factoring loop but they wont work, i think its because i have "do" command that gets values from calling
Here is the code:
static Scanner kboard = new Scanner(System.in); //variable to read in values
public static void main(String[] args) {
int choice = 0;
String dummy = "";
String forename = "";
String surname = "";
int number = 0;
do {
System.out.println("1. display the user name, 2. calculate factorial, 3. exit");
choice = kboard.nextInt();
dummy = kboard.nextLine(); //strips out the return
if (choice == 1) {
forename = getforename();
surname = getsurname();
displaydetails(forename, surname);
}
if (choice == 2) {
number = getnumber();
calcfactorial(number);
}
if (choice == 3) {
System.out.println("bye");
}
} while (choice != 3);
}
public static String getforename() {
String newforename = "";
System.out.println("Please enter your forename ?");
newforename = kboard.next();
return (newforename);
} // end getforename
public static String getsurname() {
/*
Code to prompt the user to enter a surname
*/
String newsurname = "";
System.out.println("Please enter your surname ?");
newsurname = kboard.next();
return (newsurname);
} // end getsurname
public static void displaydetails(String displayforename, String displaysurname) {
/*
Code will carry out prescribed changes and display the result
*/
char displayinitial;
String displayusername = "";
displaysurname = displaysurname.toUpperCase();
displayinitial = displayforename.charAt(0);
displayusername = displayinitial + displaysurname;
System.out.println("Your username is " + displayusername);
}
public static int getnumber() {
System.out.println("What numbers factorial do you want to know?");
int newnumber = kboard.nextInt();
return newnumber;
}
public static void calcfactorial(int newnumber) {
int count = 0;
int factorial = 1;
if (newnumber > 0) {
for (count = 1; count <= newnumber; count++); {
factorial = factorial * count;
System.out.println("Factorial of " + newnumber + " is: " + factorial);
}
} else {
System.out.println("Number must be positive");
}
}
If you had used a debugger, then you could tell that it's only executing the multiplication in the calcfactorial method once, and count is already 6 at this point. Reasons:
First, remove the semicolon at the end of the for condition loop. It is acting as the body of the for loop. This makes count equal to newnumber + 1, or 6.
Second, move your print statement after the end of the for loop, but still within the if block. Otherwise you'll get newnumber lines of printouts.
I am not going to fully give away the answer...user azurefrog posted a helpful link on debugging code.
However, your for loop is doing something you don't intend:
public static void calcfactorial(int newnumber)
{
int count = 0;
int factorial = 1;
if (newnumber > 0)
{
for (count=1;count<=newnumber;count++);
{
factorial = factorial * count; System.out.println("Factorial of "+newnumber+" is: "+factorial);
}
}
else
{
System.out.println("Number must be positive");
}
}
Reading through this, the line factorial = factorial * count; is just going to do 1*1, 1*2, 1*3, 1*4, 1*5, etc. for whatever is entered to be calculated for factorial. This is not the correct logic.
I recommend thinking through the logic of the for loop a bit more carefully. You should be using the number entered (i.e. 5 for the example you've given) somewhere in that loop.
I am trying to build a math Calculator in Java but I am having problems with it, I want to build it with methods and not just int.
I am having problems with how to print the return value (rishon+sheni) and also how to check if the in.nextLine() that the console wrote equal to plus like that:
package mehadash;
import java.util.Scanner;
public class lilmod {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String plus = null;
String minus = null;
String math;
int sum = 0;
System.out.println("What kind of math you want to do?");
math = in.nextLine();
if(math = plus)
{
System.out.println("Enter the two numbers you would like to check");
SumNumbers(in.nextInt(),in.nextInt());
System.out.println("The answer is :" +SumNumbers());
}
minusNumbers(in.nextInt(),in.nextInt());
}
public static int SumNumbers(int rishon , int sheni)
{
return rishon + sheni;
}
public static int minusNumbers(int rishon , int sheni)
{
return rishon - sheni;
}
}
You can always just define more variables.
int numberA = in.nextInt();
int numberB = in.nextInt();
int result = SumNumbers(numberA, numberB);
System.out.println("The result: " + result);
how to print the return value (rishon+sheni)
Try this way:
System.out.println("The answer is :" +SumNumbers(in.nextInt(),in.nextInt()));
instead of
SumNumbers(in.nextInt(),in.nextInt());
System.out.println("The answer is :" +SumNumbers());
also how to check if the in.nextLine(); that the console wrote equal
to plus
Try
if(math.equals("+"))
instead of
if(math = plus)
I have a program which should generate the factorial of any given number n.
When the user enters a number, the output is the factorial for every number entered after that into the calculator.
The code compiles fine but the calculator will not calculate any factorial except for the first.
As i can't use recursion for solving this problem please post only answers without using recursion.
Here's the code:
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
}
while(number1 != 1);
}
}
This code
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
needs to be repeated for each input.
I suggest that your GF put this into a method that can be called and the method will return the result.
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
factorial = 1;
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
}
while(number1 != 1);
}
}
You have to reset the number and the factorial to get the right factorial.
Also i would consider to use a head-controlled loop. Because it's easier to understand what is going on. Also maybe don't put the Inputdialog and the Parsing of the string to int into one line, it makes it a lot easier to handle wrong user-inputs, what you also should be doing.
Here my solution:
import javax.swing.JOptionPane;
class Assignment7 {
public static void main(String[] args) {
int number1 = 0;
int factorial = 1;
String message;
while (number1 != 1) {
String positiveInteger = JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ");
// You could check if there was a user-input and also later check if it's a number.
if (positiveInteger.length() > 0) {
number1 = Integer.parseInt(positiveInteger);
}
for (int i = 1; i <= number1; i++) {
factorial = factorial * i;
}
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
//Reset everything
number1 = 0;
factorial = 1;
message = "";
}
}
}
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
}
This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}
A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary
You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}
You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}