Java for/while loop for unique integer - java

Need help figuring out what's wrong with my code. I am taking a
beginning java course so I have to use simple code.
an integer N is unique if there exists an integer i such that: N = i*i
+ i Here are some examples of unique numbers: 2 (because 2 = 1*1 + 1) 6 (because 6 = 2*2 + 2) 12 (because 12 = 3*3 + 3)
Asks the user to enter an integer N. Prints out whether that number is
a unique number. If not print not a unique number
import java.util.Scanner;
public class task4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Enter an integer N: ");
int N = in.nextInt();
boolean unique = true;
int i = 1;
while ((i*i)+i == N)
{
if ((i*i)+i != N)
{
unique = false;
i++;
}
}
if (unique)
{
System.out.printf("%d is unique.\n",N);
}
else
{
System.out.printf("%d is not unique.\n", N);
}
}
}

Your while loop will only evaluate if 1*1 + 1 == N is true. I don't want to give you the answer directly so I will give you a hint: how can you change the while loop to return true for every value up to N?
Also try redoing the inside of the while loop. Think about how you can make it to make unique true if any value of i is valid.

This should be of some hlep to you. Check for i should always be lesser than N in the while loop. At least it has got some exit condition (which is logical). In your case there is no exit condition out of while loop when your (i*i)+i grows beyond N.
import java.util.Scanner;
public class Task4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Enter an integer N: ");
int N = in.nextInt();
boolean unique = false;
int i = 1;
while (((i*i)+i) <= N)
{
if ((i*i)+i != N) {
i++;
} else {
unique = true;
break;
}
}
if (unique)
{
System.out.printf("%d is unique.\n",N);
}
else
{
System.out.printf("%d is not unique.\n", N);
}
}
}

Maybe you can try this:
import java.util.Scanner;
public class task4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Enter an integer N: ");
int N = in.nextInt();
boolean unique = true;
double sd = Math.sqrt(N);
double fd = Math.floor(sd);
if(sd * (sd+1) != N){
unique = false;
}
if (unique)
{
System.out.printf("%d is unique.\n",N);
}
else
{
System.out.printf("%d is not unique.\n", N);
}
}
}

Related

I want to check whether an integer is unique inside an array using recursion

//Remove Method
public static int[] remove(int[]a){
int [] x = new int[a.length - 1];
for(int i = 1; i <= x.length; i++) {
x[i-1] = a[i];
}
return x;}
IsUniqueMethod to check uniqueness of Passed int
public static boolean isUnique(int []x, int n) {
if(x.length == 1) {
return true;}
else {
if(x[0] != n) {
return isUnique(remove(x), n);
}
else {
return false;
}
}
}
How could I check the uniqueness?
This will never give you the isUnique() output that you are looking for. Even if somehow you make it past the ArrayIndexOutOfBound, the code you have written is so inefficient that the JIT will be called every single time you pass a method parameter inside a recursive call.
Try this instead
import java.util.ArrayList;
import java.util.Scanner;
public class Unique {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
//Taking length of the array from the user
System.out.println("Enter the length of the desired array : ");
int length = sc.nextInt();
System.out.println("Please enter the values of the array");
ArrayList<Integer> al = new ArrayList<Integer>();
//Entering the values into the arrayList
for (int i = 0; i < length; i++) {
al.add(sc.nextInt());
}
System.out.println("Enter a number you wish to check : ");
int checkNumber = sc.nextInt();
//Using the built-in method indexOf() to check the occurance of the entered number and return its index if present, else returns -1
System.out.println(al.indexOf(checkNumber)>=0?"The entered number is present in the array":"The entered number is not present in the array");
}}

Finding the largest, second largest, second smallest, and smallest int from an array in java

I'm using a method to print the largest, second largest, smallest, and second smallest integers. This is what I have so far for the base:
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
This is the method being called so far:
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
The actual output is to formatted like
(largest,secondlargest),(smallest,secondsmallest)
I've never used an array before, and I'm not sure how to use loops with it to find the values. How do I begin this?
Here is the complete code for my program. You can disregard the second and third case, however, I still need help with the third. I need to display all prime numbers in order. Here is the requirement: Twin Prime Numbers: This should let the user specify a limit n (I used limit instead) (if n is 1000, then consider 1
to 1000), and lists the pairs of twin primes up to n. The sample run is (3,5),(5,7),(11,13),(17,19)
The complete code:
import java.util.Scanner;
public class PatternChecker{
// The scanner is accessible for every method included
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int limit;
System.out.println("List of Pattern Checker problems:\n1) Largest and Smallest Pairs\n2) Patterns of Triangles\n3) Twin Prime Pairs\n4) Quit");
System.out.print("Choice: ");
int choice = input.nextInt();
// The switch statement for the variable "choice" and each case
switch (choice) {
default:
System.out.println("\n*** INVALID OPTION");
break;
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
case 2:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(triangleOne(limit));
System.out.println(triangleTwo(limit));
System.out.println(triangleThree(limit));
System.out.println(triangleFour(limit));
break;
case 3:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(primePairs(limit));
break;
case 4:
System.out.println("\n*** End");
break;
}
}
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle One)
public static String triangleOne(int limit) {
System.out.println("*** Patterns of Triangles");
for (int x = 1; x <= limit; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Two)
public static String triangleTwo(int limit) {
for (int x = limit; x > 0; x--) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Three)
public static String triangleThree(int limit) {
for (int row = 1; row <= limit; row++) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = row; num > 0; num--) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Four)
public static String triangleFour(int limit) {
for (int row = limit; row >= 0; row--) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = 1; num <= row; num++) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 3 Method: Twin Prime Pairs
public static String primePairs(int limit) {
System.out.println("*** Twin Prime Numbers up to " + limit);
return "";
}
}
Ok based on the comment i have written a quick answer with arraylists. hope this helps.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MaxMin {
private List<Integer> alist = new ArrayList<Integer>();
public static void main(String args[]) {
MaxMin maxmin = new MaxMin();
maxmin.init();
}
public void init() {
System.out.println("Welcome!!!");
readFromUser();
printUserList();
doSort();
display();
}
public void readFromUser() {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Enter the total number of elements :");
Integer totalElements = scanner.nextInt();
for (int i=0;i<totalElements;i++) {
System.out.print("Enter the " + i +" number");
alist.add(scanner.nextInt());
}
}catch(Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
public void printUserList() {
System.out.println("user entered list is :");
System.out.println(alist);
}
public void doSort() {
Collections.sort(alist);
}
public void display() {
System.out.println("(" +alist.get(alist.size()-1)+ "," +alist.get(alist.size()-2)+ ")" + "(" +alist.get(0)+"," +alist.get(1) +")");
}
}
I hope this isn't a homework problem, but the idea is to use a loop with the array, and keep track of the largest and smallest numbers.
Start with assigning the smallest number variable to Integer.MAX_VALUE, so the first number you check will be assigned to the smallest number, because all integer values except 2^31 - 1 are smaller than Integer.MAX_VALUE, and you do that for biggest too, but with Integer.MIN_VALUE.
And then whenever you assign the biggest number again, you assign the secondBiggest variable to the "biggest" variable.
With that in mind, you just need to loop through the values of the array and check if they're larger than the biggest (in which you re-assign it) or smaller than the smallest(same thing as biggest).
int[] array = new int[]{5, 3, 4, 1, 2};
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
^
Example of looping through an array
I created an example for you.
First of all it generates a list of prime numbers till the limit (in this case hardcoded 100). Next it asks for all prime pairs and prints them. The pairs are stored in an ArrayList so it is very easy to get the first and the last pair.
It's not realy hard to understand so I don't know what to explain. Take a look at the code and if you have any questions feel free to ask.
import java.util.ArrayList;
public class PatternChecker {
public ArrayList<Integer> primes = new ArrayList<>();
public static void main(String[] args) {
PatternChecker pc = new PatternChecker();
pc.detectPrimes(100);
ArrayList<int[]> numbers = pc.getPairs();
System.out.println("Print all pairs: ");
numbers.stream().forEach((intA)->System.out.println(intA[0]+" / "+intA[1]));
System.out.println("Print just the greatest and the smallest pair: ");
System.out.println("("+numbers.get(0)[0]+","+numbers.get(0)[1]+")");
System.out.println("("+numbers.get(numbers.size()-1)[0]+","+numbers.get(numbers.size()-1)[1]+")");
}
public void detectPrimes(int limit) {
for(int i=2;i<limit;i++)
if(isPrime(i))
primes.add(i);
}
protected boolean isPrime(int no) {
for(int i=0;i<primes.size();i++)
if(no % primes.get(i) == 0) return false;
return true;
}
public ArrayList<int[]> getPairs() {
ArrayList<int[]> result = new ArrayList<>();
int last = primes.get(0);
for(int i=1;i<primes.size();i++) {
if(primes.get(i)==last+2) {
int[] resH = new int[2];
resH[0] = last;
resH[1] = primes.get(i);
result.add(resH);
}
last = primes.get(i);
}
return result;
}
}

Recursive methods which exclude each other?

I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;

Switched to BigInteger and progam does not run any more

So right I was creating a program that made palindromic numbers based on this project. My program would work for the smaller numbers, but integer can only compute a small amount of numbers, so I changed necessary integers to BigInteger(). After doing this Ive ran into some problems that Im not really sure of. Would anyone have any advice as to how to make this work?
public class Main {
public static final boolean DEBUG = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//gets the number from the console
int number = input.nextInt();
if(DEBUG) System.out.println("Got your number!");
if(DEBUG) System.out.println("Bout to makePalendrome!");
makePalendrome(number);
}
public static boolean isPalendrome(BigInteger number){
String numberString = number.toString();
for(int i = 0; i < numberString.length(); i++){
if(numberString.charAt(i) != numberString.charAt(numberString.length() - 1 - i)) return false;
}
return true;
}
public static void makePalendrome(int input){
int steps = 0;
BigInteger number = new BigInteger((input + ""));
if(isPalendrome(number)) printResult(input, steps, number);
while(!isPalendrome(number)){
String numberString = number.toString();
String reversed = "";
for(int i = 0; i < numberString.length(); i++){
reversed += numberString.charAt(numberString.length() - 1 - i);
}
BigInteger numReversed = new BigInteger(reversed);
number.add(numReversed);
steps++;
}
printResult(input, steps, number);
}
public static void printResult(int number, int steps, BigInteger palendrome){
System.out.printf("The number %d becomes palendromic after %d steps, and becomes the number: %d%n", number, steps, palendrome);
System.exit(0);
}
}
Your code goes into infinite loop while(!isPalendrome(number)) because,
number.add(numReversed);
this doesn't change the value of number. You need assign it back.
number= number.add(numReversed);

How can I make a program which ask the user to enter number of limit odd number?

For example, if I enter 5, then the first 5 odd numbers will be shown, like 1,3,5,7,9.
import java.util.Scanner;
/**
*
* #author Hameed_Khan
*/
public class JavaApplication20 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
int i;
System.out.println("Enter limit of ODD num");
i=obj.nextInt();
for(int n=0;n<10;n++){
if(n%2!=0){
int count=n;
while(count!=i)
System.out.print("\t"+n);
n++;
}
}
}
}
If I understand your question, I'd suggest a simple for loop.
int limit = (what ever user input you use);
int oddNums = 1;
for(int ii = 0; ii < limit; ii++ )
{
System.out.println(oddNums);
oddNums += 2;
}
Here you go.
import java.util.Scanner;
public class JavaApplication20 {
public static void main(String args[]) {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
int count = in.nextInt();
for(int i =1, j=1 ; i <= count ; j+=2,i++){
System.out.print(j);
if(i < count) System.out.print(",");
}
}
}
Hope you understand whats happening with the loop and the 2 variables.
Here i control the no. of iterations i.e. equal to the integer entered by the user and j is used to store the value of the odd number and is always incremented by 2 to get the next odd number.
Try its as:
public class JavaApplication20 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
{
Scanner obj=new Scanner(System.in);
int i,count=0;
System.out.println("Enter limit of ODD num");
i=obj.nextInt();
for(int n=0;;n++)
{
if(n%2!=0 && count!=i)
{
System.out.print("\t"+n);
count++;
}
}
}
}

Categories