Java Parameters, If-then statements, loops - java

I was given directions to write a method that takes two parameters. If the first parameter is equal to second parameter. Multiply both and print result.
If the first parameter is less than the second parameter, add the two and print the result 10 times.
If the first parameter is greater than the second parameter, subtract the first parameter from the second and print the result 50 times.
This is what I've coded:
public class IfHomeworkRedo {
{
public static void two(int a, int b) {
if (a == b) System.out.println(a*b);
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
public static void main (String[] args)
{
two(3, 3);
two(3, 4);
two(4, 3);
}
}
Can you help me with the errors? Thanks!

Problem #1
public class IfHomeworkRedo {
{
public static void two(int a, int b) {
There are two {{ before the two method declaration, you need to get rid of one
public class IfHomeworkRedo {
public static void two(int a, int b) {
Problem #2
You're missing a closing } after the end of the two method...
public static void two(int a, int b) {
if (a == b) System.out.println(a*b);
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
//??? Add } here
As general advice, it's easier to wrap all logic in a {...}, even it's just one line, as it will make it easier to read and reduce the risk on introducing logic errors, for example...
public static void two(int a, int b) {
if (a == b) {
System.out.println(a * b);
} else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a + b);
}
} else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b - a);
}
}
}

There should be no public on the class (if using ideone), and you had misplaced brackets. Solution: (http://ideone.com/7wBaSF)
class IfHomeworkRedo {
public static void main (String[] args)
{
two(3, 3);
two(3, 4);
two(4, 3);
}
public static void two(int a, int b) {
if (a == b) {System.out.println(a*b);}
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
}
}

Related

Error while trying to compare two elements (Java)!

class BubbleSort<T> extends ArraySort<T>
{
public void iSort(T[] inArray) {
int n = inArray.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (compare(inArray[i], inArray[k])) {
T temp;
temp = inArray[i];
inArray[i] = inArray[k];
inArray[k] = temp;
}
}
}
print(inArray);
}
public static <T extends Comparable<T>> boolean compare(T a, T b) {
if (a.compareTo(b) > 0) {
return true;
} return false;
}
I'm getting (T extends comparable < T >, T extends comparable < T >) in the type bubblesort< T > is not applicable for the arguments (T,T) error!
The quick fix is telling me to change method compare(T,T)< T > to compare(T,T), but that wouldn't resolve my problem. It works perfectly fine when I enter in actual value of elements, for example, compare(3, 5) or compare("hi", "hello") instead of compare(inArray[i], inArray[k]).
I would appreciate it a lot if someone could explain why it's doing that and give me a solution.
You've already defined your class with a generic type T, so there's no point in declaring a separate one for the method:
class BubbleSort<T extends Comparable<T>> extends ArraySort<T> {
public void iSort(T[] inArray) {
int n = inArray.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (compare(inArray[i], inArray[k])) {
T temp;
temp = inArray[i];
inArray[i] = inArray[k];
inArray[k] = temp;
}
}
}
print(inArray);
}
public static boolean compare(T a, T b) {
if (a.compareTo(b) > 0) {
return true;
}
return false;
}
}
Anyway, you should denote T extends Comparable<T> in the class declaration rather than in the method.

Not able to find possible solutions for N-Queens puzzle

I am trying to find all possible solutions for N-Queens puzzle. I have to print single queen on each row, and no two queens should be adjacent to each other like no one or more queens diagonally, no one or more queens in a same row, no one or more queens in a same column.
I have written the algorithm and think that most part of it is correct, but the solutions are not getting printed. I don't understand why. I have spent a lot of time on this.
Any help will be appreciated.
Following is my code:
public class NQueens {
int[] x;
public NQueens(int n) {
x = new int[n];
} // CONSTRUCTOR
public void printQueens(int[] x) {
int N = x.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (x[i] == j) {
System.out.print("Q ");
} else {
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
//Promising method
public boolean canPlaceQueen(int r, int c) {
for (int i = 0; i < r; i++) {
if (x[i] == c || (i - r) == (x[i] - c) ||(i - r) == (c - x[i]))
{
return false;
}
}
return true;
}
//permute method
public void placeNqueens(int r, int n) {
for (int c = 0; c < n; c++) {
if (canPlaceQueen(r, c)) {
x[r] = c;
if (validSol(r,n)) {
printQueens(x);
} else {
placeNqueens(r + 1, n);
}
}
}
}
public boolean validSol(int r, int n){
if(r== n) {
return true;
}
else {
return false;
}
}
public void callplaceNqueens() {
placeNqueens(0, x.length);
}
public static void main(String args[]) {
NQueens Q = new NQueens(8);
Q.callplaceNqueens();
}
}
Your code looks fine. It is only missing a key check in the validSol method.
Change the validSold method to the following and your code should work fine.
public boolean validSol(int r, int n){
if(r== n-1) {
return true;
}
else {
return false;
}
}
Let me know if this works for you.

A simple Java method not working

Hello everyone I am a newbie with the java programming language and have been learning the use of methods, below is a simple method i wrote for adding two numbers but when I run the code, it doe not display any output, please what I am doing wrongly? the code should sum numbers from 2 to 4 in this case
//testing Java methods
public class Methods {
public static void main(String [] args) {
int addition = add (2,4);
System.out.println(addition);
}
//the method for addition
public static int add(int a, int b){
int sum = 0;
for (int i = a; a <= b ; i++)
sum += i;
return sum;
}
}
for (int i = a; a <= b ; i++)
It should be
for (int i = a; i <= b ; i++)
It was actually running into infinite loop.
try this program (change from a <= b to i <= b)
public static void main(String[] args) {
int addition = add(2, 4);
System.out.println(addition);
}
// the method for addition
public static int add(int a, int b) {
int sum = 0;
for (int i = a ; i <= b ; i++) {
sum += i;
}
return sum;
}
output
9
your for loop should be
for (int i = a; i <= b ; i++)
//testing Java methods
public class Methods {
public static void main(String[] args) {
int addition = add(2,4);
System.out.println(addition);
}
//the method for addition
public int add(int a, int b){ // Place this method in the class.
int sum = 0;
for (int i = a; i <= b ; i++){ // "a <= b" Has to be: i <= b
sum += i;
}
return sum;
}
}
I think this is want you want.
The result will be:
2+3+4 = 9

How can I return multiple variables and/or use a private int method?

Here's my code as it stands:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
for(int n = 0; n <= number; n++)
{
int max = number;
for(a = 1; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
return 1;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = greatestCommonFactor(a, b, c);
return output+"\n";
}
}
I need to have it print out the variables a, b, and c but I can not figure out how to make it do so. The error message I'm currently receiving is "a cannot be resolved to a variable
b cannot be resolved to a variable
c cannot be resolved to a variable"
here's a link to the associated labsheet if it helps: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM
UPDATE
here's my updated toString method:
public String toString()
{
int a = 0;
int b = 0;
int c = 0;
String output="";
output += greatestCommonFactor(a, b , c) + "\n";
return output;
}
and while I'm editing, my greatestCommonFactor method:
private int greatestCommonFactor(int a, int b, int c)
{
for(int n = 0; n <= number; n++)
{
int max = number;
for(a = 1; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
return greatestCommonFactor(a, b, c);
}
}
}
}
}
}
}
//return 1;
}
UPDATE #2
Here's (hopefully) a more correct way of writing the code for the greatestCommonFactor and toString methods:
private int greatestCommonFactor(int a, int b, int c)
{
a = 0;
b = 0;
c = 0;
for(int n = 0; n <= number; n++)
{
int max = number;
for(a = 1; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
return a;
}
}
}
}
}
}
}
return greatestCommonFactor(a, b, c);
}
public String toString()
{
String output="";
output += greatestCommonFactor(a, b , c) + "\n";
return output;
}
Runner Class addition
import static java.lang.System.*;
import java.util.Scanner;
public class Lab11j
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String choice="";
do{
out.print("Enter the max number to use : ");
int big = keyboard.nextInt();
//instantiate a TriangleThree object
Triples trip = new Triples( big);
//call the toString method to print the triangle
System.out.println( trip );
System.out.print("Do you want to enter more data? ");
choice=keyboard.next();
}while(choice.equals("Y")||choice.equals("y"));
}
}
You're using variables without declaring and initializing them:
output = greatestCommonFactor(a, b, c); // where are a, b and c decleared in this method?
Moreover, your greatestCommonFactor() method takes arguments, but does nothing else than reinitializing them, so it could very well not take any argument at all:
private int greatestCommonFactor(int a, int b, int c) {
for (int n = 0; n <= number; n++) {
int max = number;
for (a = 1; a <= max; a++)
// here you're setting a to 1. So why pass its value as an argument to the method,
// since you don't care about the passed in value?
EDIT:
instead of having
private int greatestCommonFactor(int a, int b, int c) { // these are arguments
a = 0;
b = 0;
c = 0;
...
}
you should have
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0; // these are local variables
...
}
Instead of having
public String toString() {
String output="";
output += greatestCommonFactor(a, b , c) + "\n";
return output;
}
you should have
// yes, this method name is ugly, but it says what the method does
// I would simply make greatestCommonFactor a public method, and remove this method,
// since it doesn't do anything useful.
public String computeGreatestCommonFactorAndReturnItAsAStringWithANewLine() {
return greatestCommonFactor() + "\n";
}

Avoid printing the last comma

I'm trying to print this loop without the last comma. I've been Googling about this and from what i've seen everything seems overcomplex for such a small problem. Surely there is an easy solution to avoid printing the last comma. Much appreciated if somebody could help me out, this is driving me insane!!!
For example it loops from 1-10 // 1,2,3,4,5,6,7,8,9,10, < do not want this last comma
public static void atob(int a,int b)
{
for(int i = a; i <= + b; i++)
{
System.out.print(i + ",");
}
}
I might get stoned to death for this answer
public static void atob(int a,int b) {
if(a<=b) {
System.out.println(a);
for(int i = a+1;i<=b;i++) {
System.out.println(","+i);
}
}
}
}
Yet another way to do this.
String sep = "";
for(int i = a; i <= b; i++) {
System.out.print(sep + i);
sep = ",";
}
if you are using a StringBuilder
StringBuilder sb = new StringBuilder();
for(int i = a; i <= b; i++)
sb.append(i).append(',');
System.out.println(sb.subString(0, sb.length()-1));
Try this
public static void atob(int a,int b)
{
for(int i = a; i < b; i++)
{
System.out.print(i + ",");
}
System.out.print(b);
}
Java 8:
IntStream.rangeClosed(a, b)
.collect(Collectors.joining(","));
If you want to perform interleaving actions:
Java 8:
IntStream.rangeClosed(a, b)
.peek(System.out::print)
.limit(b - a) // [a:(b-1)]
.forEach(i -> System.out.print(","));
Java 9:
IntStream.rangeClosed(a, b)
.peek(System.out::print)
.takeWhile(i -> i < b) // [a:(b-1)]
.forEach(i -> System.out.print(","));
public static void atob(int a, int b) {
if (a < b) {
System.out.print(a);
while (a < b) {
a++;
System.out.print("," + a);
}
}
}
When called with
atob(0,10);
Will give the output
0,1,2,3,4,5,6,7,8,9,10
A general approach could be to make a distinction between the first item and all the others. The first run, no comma is printed BEFORE i. After that, a comma is printed before i, every time.
public static void atob(int a,int b) {
boolean first = true;
for(int i = a; i <= + b; i++) {
if ( first == false ) System.out.print(",");
System.out.print(i);
first = false;
}
}
In this specific case, using the ternary operator (http://en.wikipedia.org/wiki/Ternary_operation), you could write it as compact as:
public static void atob(int a,int b) {
for(int i = a; i <= + b; i++) {
System.out.print( i + ( i < b ? "," : "" ) );
}
}
Without ternary operation, this would look like this (and is more readable, which is often a good thing):
public static void atob(int a,int b) {
for(int i = a; i <= + b; i++) {
System.out.print( i );
if ( i < b ) System.out.print( "," );
}
}
(note that + b is the same as b, so you could replace that, as others have done in their answers)
With slight adjustments (method name, variables, and space after comma):
public static void printSequence(int start, int end) {
if (end < start) {
return; // or however you want to handle this case
}
if (end == start) {
System.out.print(start);
return;
}
StringBuilder sequence = new StringBuilder();
for (int i = start; i <= end; i++) {
sequence.append(i).append(", ");
}
// now simply print the sequence without the last ", "
System.out.print(sequence.substring(0, sequence.length() - 2));
}
Try:
public static void atob(int a, int b) {
if (b < a) {
final int temp = a;
a = b;
b = temp;
}
System.out.print(a++);
for (int i = a; i < b ; i ++ ) {
System.out.print("," + i);
}
}
Use StringBuilder for it. use substring based index.
public class arraySort {
public static void main(String[] args) {
int a[] = { 2, 7, 5, 6, 9, 8, 4, 3, 1 };
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] < a[j]) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Descending order:{");
StringBuilder br = new StringBuilder();
for (int i = 0; i < a.length; i++) {
br.append(a[i] + ",");
}
System.out.print( br.substring(0, br.length()-1));
System.out.println("}");
}
}
public static void atob (int a,int b){
for(int i = a; i <= b; i++)
{
System.out.print(i );
if(i<b){
System.out.print(",");
}
}
}
Clunky solution, but hey - it works.
public static void atob(int a, int b){
int count = 1;
for(int i = a; i <= + b; i++) {
System.out.print(i);
if(count!=((b + 1) - a)) {
System.out.print(", ");
count++;
}
}
}
Alternatively, this works too.
public static void atob(int a, int b){
int count = 0;
for(int i = a; i <= + b; i++) {
if(count > 0){
System.out.print(", ");
}
System.out.print(i);
count++;
}
}
Found another simple way using regex:
String str = "abc, xyz, 123, ";
str = str.replaceAll(", $", "");
System.out.println(str); // "abc, xyz, 123"
You can simply use escape sequence for backspace(\b),outside the main loop,it will delete the last comma.
public static void atob(int a,int b)
{
for(int i = a; i <= + b; i++)
{
System.out.print(i + ",");
}
System.out.print("\b");
}

Categories