I was wondering when I tried to print the value of recursion in main, the answer was:
Enter the number: 1
2The result is:
How to make the number 2 to the front like,
The result is: 2
import java.util.Scanner;
public class Question4Final {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
System.out.printf("The result is: ", multiplication(a));
}
public static int multiplication(int a) {
if (a == 5) {
int multiply = 10 * 6 * 2;
System.out.print(multiply);
} else if (a == 4) {
int multiply2 = 6 * 2;
System.out.print(multiply2);
} else if (a == 1) {
System.out.print("2");
}
return a;
}
}
To call the method:
System.out.printf("The result is: ", multiplication(a));
first the arguments must be evaluated, so multiplication(a) is executed before System.out.printf("The result is: ", multiplication(a)). Since multiplication(a) prints something, that printing takes place before "The result is:" is printed.
You should change multiplication(a) to simply return the result without printing it. Then use System.out.println("The result is: " + multiplication(a)) to print the result.
Note the you have to change the value returned by multiplication(a), since currently you return a, which is not the value printed by that method.
You have 2 issues in your code.
First is you are printing the value of 'multiply' in your static method :
public static int multiplication(int a){
System.out.print(multiply);
That is a reason why it is printing 2 before the statement :
2The result is:
2nd issue is you are calling the method multiplication in the print statement :
System.out.printf("The result is: ", multiplication(a));
That is not how to print the result by calling the method.
I have taken your example and run the below code. You can check this code.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
int product = multiplication(a);
System.out.println("The result is : " +product);
}
public static int multiplication(int a){
int multiply = 0;
if(a == 5){
multiply = 10 * 6 * 2;
}else if(a == 4){
multiply = 6 * 2;
}else if(a == 1){
multiply = 2;
}
return multiply;
}
}
Below are the outputs on different options :
Enter the number: 4
The result is : 12
Enter the number: 5
The result is : 120
Enter the number: 1
The result is : 2
Related
I have an Assignment that has many questions and the only ones I seem to be having trouble with are the ones with ArrayLists. I need to use a separate main method to enter and print out information.
This is my class
import java.util.ArrayList;
public class HailstoneSequence {
private int n;
public HailstoneSequence(int n) {
this.n = n;
}
public double getn() {
return n;
}
public static ArrayList<Integer> getHailstoneSequence(int n){
ArrayList<Integer> list = new ArrayList<Integer>();
//int i = 0;
while (n != 1);
for (int s : list) {
try {
if(n == 1) break;
if(n % 2 == 0) {
System.out.println(n + " is even, so I take half: " + (n / 2));
}
else
System.out.println(n + " is odd, so I make 3n+1: " + ((n * 3)+1));
// i++;
}
catch (Exception error) {
while (n <= 1) {
System.out.println("You did not enter a valid positive, greater than 1 integer. Please try again: ");
System.out.println();
}
}
}
return list;
}
}
and this is the main class (which does not work)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class TestHailstoneSequence {
#SuppressWarnings("resource")
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("The Hailstone Sequence takes a number and if it odd it multiples it by 3 and adds 1,"
+ "\nit divides it by 2 and carries on until it reaches 1. \nPlease enter a positive number"
+ " (greater than 1) to generate the Hailstone Sequence: ");
int n = input.nextInt();
HailstoneSequence aHailstoneSequence = new HailstoneSequence(n);
System.out.println(Arrays.toString(aHailstoneSequence.list));
}
}
Please help me understand how to print out the results
You declared getHailstoneSequence method as static one you should call it and store to a variable if you need in another operation and printing like this:
ArrayList<Integer> list = HailstoneSequence.getHailstoneSequence(n);
System.out.println(list);
For your current case the main method will look something like this:
import java.util.Scanner;
public class TestHailstoneSequence {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("The Hailstone Sequence takes a number and if it odd it multiples it by 3 and adds 1,"
+ "\nit divides it by 2 and carries on until it reaches 1. \nPlease enter a positive number"
+ " (greater than 1) to generate the Hailstone Sequence: ");
int n = input.nextInt();
input.close(); // do not forget to close the resource
// if you use static method in your HailstoneSequence class you can remove
// field with name "n" from that class and you don't need to create an object in this case
// Also I'd rename the class from HailstoneSequence to something like HailstoneSequenceCalculator
System.out.println(HailstoneSequence.getHailstoneSequence(n));
}
}
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'm making a simple while loop when i can make a subtraction between 2 number in java.
The only task of this exercise is this:
Suppose that user insert 2 number by this method (
Scanner keyboard = number.nextInt();
Scanner keyboard2 = number2.nextInt();
Suppose that user insert these 2 number : 8 and 3
I'm not asking for a program which makes 8 - 3 = 5
The program is able to do only substraction or addiction of 1.
so the five is converted in a substraction of -1 for five time.
So instead of 8 - 3, the program calculate 8 -1 -1 -1 -1 -1 = 3
// 8 - 5
Or :
8 -1 = 7
7 - 1 = 6
// ....
4 - 1 = 3
The exercise don't requires complex method, or for loop, only while
As my point of view, i think that you need your answer like your example. Because of that, i made a program for you. In this program if you only enter large number first, you can except if statement, This is my solution.
import java.util.*;
import java.lang.*;
public class Stack2{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
int num1=sc.nextInt();
int num2=sc.nextInt();
if(num1<num2){
System.out.println("Number 1 is less than number 2");
System.exit(1);
}
int x=num1-num2;
System.out.print(num1+" - "+num2+" --> is equal to "+ num1+" " );
while(num1!=x){
System.out.print("-1 ");
num1--;
}
System.out.println("= "+x);
}
}
i'm not sure if you want some like this
int num1 = 8;
int num2 = 5;
int res = num1- num2;
boolean bandera = Boolean.TRUE;
String salida = "";
while(bandera)
{
if(num2 > 0)
{
salida = salida +"-1";
num2--;
}else
{
bandera = Boolean.FALSE;
}
}
System.out.println(num1 + salida + "=" + res);
Your code needs little correction. You haven't declared Scanner object correct and even numbers. Try this code,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
System.out.print(num1 + " - " + num2 + " --> Is equal to " + num1);
while(num2 > 0) {
System.out.print(" - 1");
num1 -= 1;
num2--;
}
System.out.println(" = " + num1);
sc.close();
}
I have some experience using Python so I've been trying to learn Java by writing the same programs I write in Python for school in Java.
I have this function where I enter two integers and it returns the sum. If the integers are the same, then it returns double the sum. For example, 5 + 5 = 20.
I have the following code for this function.
public class sumDouble
{
public int sumDouble(int a, int b) {
int sum = a + b;
if (a == b) {
sum = sum * 2;
}
return sum;
}
}
Next, I want to write a script where I ask the user to input two integers and the main class calls this function. I have the following code for this. Where did I go wrong?
import java.util.Scanner;
public class GetSumFromUser
{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
int a;
int b;
int sumDouble;
sumDouble sum = new sumDouble();
System.out.println("Please enter an integer.");
a = in.nextInt();
System.out.println("You entered "+a);
System.out.println("Please enter another integer.");
b = in.nextInt();
System.out.println("You entered "+b);
System.out.println("Your sum is "+sum);
}
}
At the last line, the output reads "Your sum is sumDouble#1777aec".
You never actually invoked the sumDouble() method. Rather than print out sum (which is an Object), you should print like this:
System.out.println("Your sum is "+sum.sumDouble(a,b));
Try this:
public class SumDouble
{
public static int sumDouble(int a, int b) {
int sum = a + b;
if (a == b) {
sum = sum * 2;
}
return sum;
}
}
...
System.out.println("Your sum is "+SumDouble.sumDouble(a, b));
If you do print(sum) then you are printing the object...
do instead
System.out.println("Your sum is "+sum.sumDouble(a,b));
You get an object from sumDouble class, but you never invoke it's sumDouble method:
sumDouble sum = new sumDouble();
change this to:
sumDouble sd = new sumDouble();
int sum = sd.sumDouble(a,b);
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.util.Scanner;
class sumDouble
{
public int sumDouble(int a,int b)
{
int sum=a+b; //add the numbers
if(a==b) //check if both numbers are same
sum=sum*2; //double th value if same
return sum; //return sum
}
}
public class GetSumFromUser
{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
sumDouble s=new sumDouble();
int a;
int b;
int sum;
System.out.println("Please enter an integer.");
a = in.nextInt();
System.out.println("You entered "+a);
System.out.println("Please enter another integer.");
b = in.nextInt();
System.out.println("You entered "+b);
sum= s.sumDouble(a, b) ; //call the sum double function
System.out.println("Your sum is "+sum);
}
}
System.out.println("Your sum is "+sum);
Change this to:
System.out.println("Your sum is "+sum.sumDouble(a,b));
You haven't called the method. "Your sum is "+sum -this will call the toString method of sum which is sumDouble#1777aec.
So this code asks to input either a 1 for a pass or a 2 for a fail for ten students and it shows an error if the user inputs an invalid number. The logical error in this is for example all 10 students pass,the output is supposed to be "passed: 10 Failed:0".However, if I enter an error just once by mistake the error message will appear but the output will be"passed:9 failed:0 " even thought all 10 students passed.
import javax.swing.JOptionPane;
public class pass {
public static void main(String[] args) {
int passes = 0;
int failures = 0;
int result;
for (int studentCounter = 1; studentCounter <= 10; studentCounter++) {
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if (result == 1) {
passes = passes + 1;
} else if (result == 2) {
failures = failures + 1;
} else if ((result != 1) && (result != 2)) {
JOptionPane.showMessageDialog(null, "Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null, "Passed:" + passes + "Failed:" + failures);
System.exit(0);
}
}
It is right, as 9 have passed and 0 have failed. The error does not count in none of the groups.
The problem is in your if else logic:
Your For loop increments the integer in the condition else if((result!=1)&&(result!=2)) which means that for example, if you make 10 times a input other than 1 or 2, you'll get a result like 0 passes and 0 failed... but your loop is over....
I suggest you additionally to use the Oracle Java Code Conventions... failures ++; passes++;
You can have try with below code. Decrements student counter on invalid input.
import javax.swing.JOptionPane;
public class pass{
public static void main(String [] args){
int passes=0;
int failures=0;
int result;
for(int studentCounter = 1; studentCounter<=10; studentCounter++){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes++;
}else if(result==2){
failures++;
} else if((result!=1)&&(result!=2)) {
studentCounter--;
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null,"Passed:"+passes+" Failed:"+failures);
System.exit(0);
}
}
You can update your code like below to remove your logical error:
import javax.swing.JOptionPane;
public class pass{
public static void main(String [] args){
int passes=0;
int failures=0;
int result;
for(int studentCounter = 1; studentCounter<=10;){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes = passes + 1;
studentCounter++
}else if(result==2){
failures = failures +1;
studentCounter++
} else {
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null,"Passed:"+passes+"Failed:"+failures);
System.exit(0);
}
}
The loop is executed exactly 10 times. But if an error occurs, your code neither increases passes nor failures, and therefore passes + failures always is the amount of inputs without failures and always <= 10.
If you want to have exactly 10 results you have to make sure that there are exactly 10 correct inputs.
You can achieve this by increasing a results counter on correct inputs until it reaches 10:
int studentCounter = 0;
while(studentCounter < 10 ){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes++;
studentCounter++;
}else if(result==2){
failures++;
studentCounter++;
} else {
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}