import java.util.*;
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int kvadratek, a, b;
a = sc.nextInt();
b = sc.nextInt();
--a;
--b;
if(a>b) {
kvadratek=b;
b=a;
a=kvadratek;
System.out.println((a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b));
}
else {
System.out.println(a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b);
}
}
}
i am new to java coding and i have a question if i can write this part
kvadratek=b;
b=a;
a=kvadratek;
differently so that it will give me the same result as the else part. Is it possible to do it with if, while sentences? I actually don't need the else part of the code if I insert
kvadratek=b;
b=a;
a=kvadratek;
but is there a way to change that part?
First thing, to avoid repeating code, is to extract it to a method:
private static int compute(int a, int b) {
return (a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b);
}
Now you want b to be the biggest of the two numbers, and a to be the other one. Instead of swapping them, you could use Math.max and Math.min:
a = sc.nextInt() - 1;
b = sc.nextInt() - 1;
System.out.println(compute(Math.min(a, b), Math.max(a, b));
You can use this:
int k = Math.max(a, b)
a = Math.min(a, b);
b = k
After this piece of code, b will be the greater between the original a and b, while a will be the smaller, thus removing the need for the if/else.
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
I have the following code:
public class Main {
static void swap (Integer x, Integer y) {
Integer t = x;
x = y;
y = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
swap(a, b);
System.out.println("a=" + a + " b=" + b);
}
}
I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?
This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )
To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)
Thing tmp = a;
a = b;
b = tmp;
Everything in Java is passed by value and the values of variables are always primitives or references to object.
If you want to implement a swap method for Integer objects, you have to wrap the values into an array (or ArrayList) and swap inside the array. Here's an adaptation of your code:
public class Main {
static void swap (Integer[] values) {
if ((values == null) || (values.length != 2)) {
throw new IllegalArgumentException("Requires an array with exact two values");
}
Integer t = values[0];
values[0] = values[1];
values[1] = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] integers= new Integer[]{a,b};
swap(integers);
System.out.println("a=" + integers[0] + " b=" + integers[1]);
}
}
(Just added this answer because Svish mentioned, that "You can't really make a swap method in Java" fg)
As Svish and others pointed out it it's call by value, not by reference in Java. Since you have no pointers in Java you need some kind of holder object to really swap values this way. For example:
static void swap(AtomicReference<Integer> a, AtomicReference<Integer> b) {
Integer c = a.get();
a.set(b.get());
b.set(c);
}
public static void main(String[] args) {
AtomicReference<Integer> a = new AtomicReference<Integer>(1);
AtomicReference<Integer> b = new AtomicReference<Integer>(2);
System.out.println("a = " + a);
System.out.println("b = " + b);
swap(a, b);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
You would need to pass the parameters by reference, which it's not possible in java. Also Integers are inmutables, so you cannot exchange the values as you don't have a setValue method.
Integer are immutable - you can't change their values. The swapping that occurs inside the swap function is to the references, not the values.
You would need to return both references in an array to achieve what you want
static Integer[] swap(Integer a, Integer b) {
return new Integer[]{b, a};
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] intArray = swap(a, b);
a = intArray[0];
b = intArray[1];
System.out.println("a=" + a + " b=" + b);
}
If Integer had a setValue method, you could do something like this.
static void swap(Integer a, Integer b) {
int temp = a.intValue();
a.setValue(b.intValue());
b.setValue(temp);
}
But it doesn't - so to achieve what you want, return an array.
Using the XOR operator is a very bad idea:
First, it is far less readable. Second, there were times when this was faster but nowadays the opposite is the case. See
Wikipedia
for reference.
As all the guys mentioned its a Pass-By-Value thing.
Just liked to add: you can use this method of swapping GLOBAL integers.
private void swap (){
a ^= b;
b ^= a;
a ^= b;
}
It eliminates the use of another variable, and its just cooler :)
Java code:
class swap {
int n1;
int n2;
int n3;
void valueSwap() {
n3 = n1;
n1 = n2;
n2 = n3;
}
public static void main(String[] arguments) {
Swap trial = new Swap();
trial.n1 = 2;
trial.n2 = 3;
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
trial.valueSwap();
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
}
}
Output:
trial.n1 = 2
trial.n2 = 3
trial.n1 = 3
trial.n2 = 2
Using Scanner:
import java.util.*;
public class Swap {
public static void main(String[] args){
int i,temp,Num1,Num2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Number1 and Number2");
Num1=sc.nextInt();
Num2=sc.nextInt();
System.out.println("Before Swapping Num1="+Num1+" Num2="+Num2);
temp=Num1;
Num1=Num2;
Num2=temp;
System.out.println("After Swapping Num1="+Num1+" Num2="+Num2);
}
}
This is one of the practice questions of a test:
Write a method which accepts two integer values as input parameters and returns the boolean result true if the sum of the inputs is greater than or equal to 10 (and falseotherwise)
My answer is below but I don't think it looks correct. Can anyone give me a pointer?
public class Bruh{
public static void main (String [] arg){
int a;
int b;
boolean sum = true;
if ( a+b > 10)
System.out.println ("yo");
else{
sum = false;
}
}
}
You only wrote some code in the main method but you did not create one.
In order to do that you need to actually create a method in your Bruh class like:
public static boolean isSumGreaterThan9(int a, int b){
return (a + b) > 9;
}
Than call it from the main method:
public static void main (String [] arg){
int a = 4; // or whatever
int b = 7; // or whatever
System.out.println(isSumGreaterThan9(a, b));
}
You need to put your logic into a method and change your comparison to >= as per the requirement:
public static boolean isSumGreaterThanOrEqualToTen(int a, int b) {
return (a + b) >= 10;
}
final int a, b;
if (condition1) {
a = get(dynamicValues);
b = get(dynamicValues);
}
if (condition2) {
int c = b + a;
display(c);
}
In this type of code the compiler is asking to intialize a and b, which I can't do until the condition1 is met. and a and b being final is mandatory as the values of hours and minutes keep changing.
The above written code is very generalized just to give you an idea of my problem.
UPDATE: The problem here is condition2 is one of the else conditions of condition1. So can't use else statements too.
Dynamic values here are the values like "hrs and mins" which always change. when condition1 is met a and b are intialised with hrs and mins, condition2 will definitely happen after condition1 at some point of time. So the time difference between condition2 and condition1 needs to be calculated.
if condition1 is false a and b remain not initialized. That's why the compiler is complaining. Add the else branch and it will compile correctly
if(condition1)
{
a=cal.get(Calendar.HOUR);
b=cal.get(Calendar.MINUTE);
} else {
a = 0;
b = 0;
}
Forgive me if I have not understood your problem correctly :). It seems to me that perhaps it's easier to wrap up your 'final' variables into an immutable class. Then create an instance of such a class in 'condition1'. Here's what I mean...
import java.util.Scanner;
import java.util.Calendar;
public class ImmutableHourMinute {
private final int a;
private final int b;
public ImmutableHourMinute(final int $a, final int $b){
this.a = $a;
this.b = $b;
}
public int getA() {
return a ;
}
public int getB() {
return b;
}
public static void main(String... args){
// Requirements:
// 1. Hour and minute are set at condition == 1;
// 2. Hour and minutes must never be changed.
System.out.println("Please type 'start':");
Scanner scanner = new Scanner(System.in);
ImmutableHourMinute hourAndMinute = null; // Can be initialized properly later
while(!scanner.nextLine().equals("quit")){
System.out.println("Please enter condition (1 or 2):");
int condition = scanner.nextInt();
if(condition == 1){
Calendar rightNow = Calendar.getInstance();
int a = rightNow.get(Calendar.HOUR);
int b = rightNow.get(Calendar.MINUTE);
System.out.println(String.format("(Creating ImmutableHourMinute(a=%1$d, b=%2$d)", a, b));
hourAndMinute = new ImmutableHourMinute(a, b);
}else if (condition == 2){
display(hourAndMinute.getA() + hourAndMinute.getB());
}
System.out.println("Please enter condition (1 or 2):");
}
}
private static void display(final int displayValue){
System.out.println(String.format("Displaying the time set in condition 1 :%1$d", displayValue));
}
}
And here is a sample of the output:
$ java ImmutableHourMinute
Please type 'start':
start
Please enter condition (1 or 2):
1
(Creating ImmutableHourMinute(a=9, b=56)
Please enter condition (1 or 2):
Please enter condition (1 or 2):
2
Displaying the time set in condition 1 :65
note : such and immutable class already exists(if you're using Java SE 8)...
java.time.LocalDateTime
public class time{
private int a=0;
private int b=0;
public int get()
{
return a+b;
}
public void set()
{
this.a = cal.get(Calendar.HOUR);
this.b = cal.get(Calendar.MINUTE);
}
}
In your main class, call the time class method(out of main method, at very begining),
public final Time t = new Time();
In main method:
if(condition1)
{
t.set();
}
if(condition2)
{
display(t.get());
}
import java.util.Scanner;
class pyth{
public static void main(String[] args) {
System.out.println("enter n");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
{
for(int a=1;a>n;a++) {
for(int b=a+1;b>n;b++) {
int c=n-a-b ;
}
if(c*c=a*a+b*b) {
System.out.println(a+','+b+','+c+',');
}
}
}
}
}
I'm new to programming, so I can't really figure out the problem. This is the error:
pyth.java:15: error: cannot find symbol
if(cc=aa+b*b)
^ symbol: variable c
location: class pyth
Firstly, syntax is very important. Maintain indents. Makes the code easier to read and understand and also helps in maintenance.
The errors in your code :
int c=n-a-b ; c is being used in the if comparison. So needs to be declared beforehand. Similarly, int b also has to be declared before hand for use in the if statement.
if(c*c=a*a+b*b) = is an assignment operator. Use == to make comparisons. And use more brackets to get rid of ambiguity.
Additionally :
System.out.println(a+','+b+','+c+','); this isnt a mistake as such, but its better to use ",".
This should workd :
import java.util.Scanner;
class pyth{
public static void main(String[] args){
System.out.println("enter n");
Scanner in=new Scanner(System.in);
int b,c;
int n=in.nextInt();
for(int a=1;a>n;a++) {
for(b=a+1;b>n;b++) {
c=n-a-b ;
}
if(c*c==(a*a+b*b)) {
System.out.println(a+","+b+","+c+",");
}
}
}
}
if(c*c=a*a+b*b) {
^--- assignment
You cannot assign the result of one expression to another expression. It should be ==
ok, the issue of your compilation errors is scoping of variables.
you defined int c = n-a-b inside a for block and it is not accessible outside that block.
similarly the variable b is not accessible outside the block
for (int b = a + 1; b > n; b++) {
c = n - a - b;
}
as it's scope ends at the end of loop.
Also where you are checking for equality, you should use == instead of = , which is for assignment.
I am not sure what you want to do through your code, but the code should be something as follows :
import java.util.Scanner;
public class pyth {
public static void main(String[] args) {
System.out.println("enter n");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c = 0, a=0, b=0;
for (a = 1; a > n; a++) {
for (b = a + 1; b > n; b++) {
c = n - a - b;
}
if ((c * c) == (a * a) + (b * b))
System.out.println(a + ',' + b + ',' + c + ',');
}
}
}
Hope that helps. Please accept this answer if it helped you.
I have been given a piece of code (the class QuestionTwo).
I am asked to state the values of a, b, and c after method mQ2 is invoked on a newly created object of class Q2.
My main.java file
package openuniversity;
public class Main
{
public static void main(String[] args)
{
QuestionTwo qt = new QuestionTwo();
qt.mQ2();
}
}
My QuestionTwo.java class file:
package openuniversity;
public class QuestionTwo
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
}
a++;
}
}
I arrived at:
a: 1
b: 1
c: 3
Note I can also select 'undefined' as an answer?
So would it be 1, 1, undefined as c does not exist outside of the codeblock?
The question:
Study the following code and then select the options from the drop-down lists below that are correct about the values of a, b and c after the method mQ2 is invoked once on a newly created object of class Q2. Note that the answers you choose for a, b and c may or may not be different from each other.
public class Q2
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
System.out.println("c: " + c); //correct place?
}
a++;
}
System.out.println("a: " + a + "b: " + b); // correct place?
}
Since this is homework, I'll restrict my answer to a couple of pointers.
You can verify your solution by printing out the variables after calling mQ2() (hint: you could use System.println() for that).
This is either a trick question or is partially ill-defined (hint: think about which a, b and especially c you're being asked about).
I'd suggest you first print out all the values using System.out.println() after calling mQ2, then step through the code in your mind to try to work out why the values are what they are. Remember that any variable declared is only visible within the scope ({...}s for simplicity), but these variables can have the same name as other variables so they might look like the same even if they're not.
I'd like to particularly point out that c does not exist outside that method.