I feel like I am really close to getting what I want accomplished with this class -- but the method getNumbers continues to error -- advising I need .class where i say if numbers[i].isValid(i) -- and if I change it I get "int cannot be dereferenced." Part of my assignment is showing that I can use multiple methods to accomplish something and I know I'm definitely shaky on it. Any advice on that method would be appreciated. It is trying to populate an array and verify each number is between 0 and 59 and also that each number is not a repeating number.
import java.util.*;
public class Luck //edited
{
public int numbers[];
public Luck()
{
numbers = new int[4];
}
public void greeting()
{
System.out.println("Please enter 5 numbers, each > 0 and < 59.");
}
public void getNumbers()
{
Scanner reader = new Scanner(System.in);
int count = 0;
int[] numbers = new int[4];
while(count<5)
{
System.out.println("Please enter a number > 0 and < 59");
for(int i=0; i<5; i++)
{
numbers[i] = reader.nextInt();
if((isValid(numbers[i]) || isNotRepeat(numbers[]))
{
count++;
System.out.println("Number " + count + " is " + numbers[j]);
}//end second if
else TryAnother();
//else TryAgain();
}//end for
}//end while
}//end method
public boolean isNotRepeat(int numbers[]) //edited
{
for(int i=0; i< 5; i++)
{
for(int j=0; j< 5; j++)
{
if (i == j)
return false;
else return true;
}//end for
}//end for
}
public boolean isValid (int number)
{
number = newNumber;
if (newNumber < 0 || newNumber > 59)
return false;
}
public void showNumbers(int numbers[])
{
int count = 0;
//int numbers[] = new int[4];
//int i;
for(int i=0; i < 5; i++)
{
System.out.println("Number " + count + 1 + " is " + numbers[0]);
}
}
public void goodLuck()
{
System.out.println("Good luck!");
}
}//end class
numbers is an int[] (array of int). In several places in your code, you are trying to call methods on the elements of numbers, for example here:
if(numbers[i].isValid(i))
if (numbers[j].isNotRepeat(numbers[]))
That is not going to work, because you cannot call methods such as isValid and isNotRepeat on an int. Also, the second line quoted above isn't even valid Java syntax (what do you mean when you try to pass numbers[] to a method?).
You probably meant something like this:
if(isValid(numbers[i]))
(Where's the method isNotRepeat?).
There are two visible errors in your code:
1 Your constructor Name should be same as your class name.
public Luck()
should be
public Lucky()
2 you cant invoke isValid() and isNotRepeat on an int primitive.
if you just want to check if an number is valid, just do
if(isValid(i)) or if(isNotReapeat(array))
EDIT:
change
if((isValid(numbers[i]) || isNotRepeat(numbers[]))
to
if((isValid(numbers[i]) || isNotRepeat(numbers)) // you dont need the brackets, you only need to pass the reference variable
Related
This question already has answers here:
Printing with delimiter only between values
(3 answers)
Closed 2 years ago.
I was tasked to do a looping problem for Java, but I'm currently having a problem on how to display a factorial of a number. For example, 1x2x3x4x5 = 120.
I'm almost there, but I can't seem to figure out how to, or is there any possible way to display the factorial of a number because there is always an additional "x" at the end of the 5.
Here is my code:
import java.util.*;
public class trylangpo2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
int j;
for (j =1; j <=1 ; j++){
System.out.print("*");
}
}
}
}
Example output:
1x2x3x4x5x
Your loop for (j =1; j <=1 ; j++) can be removed. It only loops once so, just write System.out.print("*"). No loop required
Then if you think about it, you want to print the number and the * all the time, except when it is the last number (fctr)
So write it that way:
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
if(i<fctr) {
System.out.print("*");
}
}
Try to add a condition if it’s not at the end of the loop. Then add start and if it’s the end, then just print the number:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
for (int i = 1; i <= fctr; i++) {
if (i < fctr) {
System.out.print(i + " * ");
} else {
System.out.print(i);
}
}
}
I always use a construct like
String sep="";
for (...) {
System.out.print(sep);
System.out.print(payload);
sep="x";
}
You need to make the printing of ***** condition. Don't print ***** if i == fctr. And you don't need that additional loop of j. As below :
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
// IntStream.range(1, fctr).
long factorial = 1;
for (int i = 1; i <= fctr; i++) {
factorial = factorial * i;
if (i == fctr) {
System.out.print(i);
} else {
System.out.print(i + "*");
}
}
System.out.print("=" + factorial);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.ArrayList;
public class hangman {
public static void ttt(String inputWord) {
int wordLength = inputWord.length();
String blanks = "";
for (int i = 0; i < wordLength; i++) {
blanks = blanks.concat("_ ");
}
// System.out.print(wordLength);
System.out.println(blanks);
int points = 0;
int counter = 0;
ArrayList<String> usedChars = new ArrayList<String>();
while (points < wordLength) {
Scanner reader = new Scanner(System.in);
System.out.println("Guess: ");
String guess = reader.next();
// int checker = 0;
// for(int k = 0; k < usedChars.size(); k++) {
// if(usedChars.get(k) != guess) {
// checker = checker + 1;
// }
// else {}
// }
// if(checker == usedChars.size()) {
for (int i = 0; i < wordLength; i++) {
if (guess == inputWord.substring(i, i + 1)) {
points = points + 1;
usedChars.add(guess);
System.out.println("hit"); // this is me trying to see if
// this part is working
} else {
}
}
System.out.println("Used letters: " + usedChars);
// }
// else {
// System.out.print("Sorry, that letter has already been used");
// }
counter = counter + 1;
if (counter == 5) {
points = wordLength;
}
}
System.out.println("Game over");
}
public static void main(String[] args) {
ttt("to");
}
}
Don't worry about the commented out code, that's just me going over the top trying to prevent duplicate guesses, but it's more important that I get the rest of the code to work first.
Anyway, the only part of my code that seems to be working is the counter part. You can try it yourself, but it seems like all it does it take 5 guesses (5 lives, kind of random) and print game over.
edit: in hindsight i need to revisit that counter part, because it should only increase for incorrect guesses
The first thing I noticed was that my array isn't working correctly. It's not .add()'ing like I ask it to add my guesses. (Source: https://beginnersbook.com/2013/12/java-arraylist-add-method-example/)
Then, the more serious problem of the code not even being able to record correct guesses :/
I'm starting to code in my school's java class and decided to try this on my own for fun, any help would be greatly appreciated! :P
change the following boolean expression
guess == inputWord.substring(i, i + 1)
to
guess.equals(inputWord.substring(i, i + 1))
because guess is a String object. using '==' operator will only compare the reference, not the value.
also you might want to use
String guess = reader.nextLine();
instead of
String guess = reader.next();
Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}
I am trying to finish an assignment. I have to write a program in Java that generates random numbers in an array size100 and then asks the user for a number between 1 and 100. If the number is in the array it displays that the number was found at what location. If not it kicks back that no number was found. So far I can only get it to kick back that the number was not found. It prints it back out 4 different times.
package lab1;
import java.util.Random;
import java.util.Scanner;
public class RandomArray {
public static void main(String[] args) {
int [] randomArray = new int [100];
Random randomGenerator = new Random();
for (int i = 0; i< randomArray.length; i++){
randomArray[i] = randomGenerator.nextInt(100);
}
Scanner input = new Scanner (System.in);
int searchNumber;
System.out.println("Please enter a number to search for between 1 and 100: ");
searchNumber= input.nextInt();
boolean found = false;
for (int i = 0; i < randomArray.length; i++){
if (searchNumber == randomArray[i]){
found = true;
break;
}
if (found){
System.out.println("We have found your" + "number at index " + i);
}else{
System.out.println("We did not find your number");
}
}
}
}
Your if statement inside for loop. So each time searchNumber == randomArray[i] is false you checkif (found). It leads to else branch which print"We did not find your number"`.
PS: Learn how to use debugger. It greatly simplify your life.
you forget the case , if there are more than two location of the same number, as it is just generating random number.
How about this :
boolean found = false;
for (int i=0; i < randomArray.length; i++) {
if (searchNumber == randomArray[i]) {
found = true;
System.out.println("We have found your number at index " + i);
}
}
if (!found) {
System.out.println("We did not find your number");
}
I am writing a program that would help me find whether the number entered is a palindrome or not but i am trying it using arrays. And i would like to know if that is even possible?? And if it is possible then what am i doing wrong.
I have marked the code where i think the problem lies but feel free to suggest anything.!!!!
Thanks!!!
import java.util.Scanner;
public class palindrome
{
public static void main(String args[])
{
int size = 10,i,j,flag=0;
int num[] = new int[size];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the number ");
size = sc.nextInt();
System.out.println("Enter the number ");
for(i=0;i<size;i++)
{
num[i]=sc.nextInt();
}
i=size-1;
for(j=0;j<(size/2);j++,i--)
{
if(i>(size/2))
{
if(num[i]==num[j])
{
flag = 1;
}
}
}
if(flag==1)
{
System.out.println("The number is a palindrome");
}
else
System.out.println("The number is not a palindrome ");
}
}
Edit: Guys the problem is actually solved because i was doing a blunder mistake i.e. i was asking the user to enter the number in the form of an arry but i was not actually entering the digits in the number one by one instead i was entering the whole number in the first iteration.
But still a lot of thanks for the replies. I would still try your ideas and let you guys know. Thanks
:)
Try
public boolean isPalindrome(int[] num){
for(int i = 0 ; i < num.length/2 ; i++) {
if(num[i]!=num[num.length-(i+1)]) return false;
}
return true;
}
Yes it's possible, moreover, it's possible by using ArrayList, String - whatever you like. In order to write down a correct implementation, first decompose your current solution:
// Extract a method, do not cram all code into main()
// note: all you need is array, to get size of the array, put value.length
private static boolean isPalindrome(int[] value) {
...
}
public static void main(String args[]) {
int userInput[];
...
if (isPalindrome(userInput)) {
System.out.println("The number is a palindrome");
}
else {
System.out.println("The number is not a palindrome");
}
}
Now, let's implement isPalindrome():
private static boolean isPalindrome(int[] value) {
if (null == value)
return true; //TODO: or false, or throw exception
for (int i = 0; i < value.length / 2; ++i)
if (value[i] != value[value.length - 1 - i])
return false;
return true;
}
The easiest and most intuitive way (imo) to check for palindromes is through recursion. The idea is simple:
Is the first and last char the same?
YES Remove first and last char and check first and last char of the new String
NO There is no palindrome.
When the input is only 1 char then it's trivial.
Have a look at this code:
private void isPalindrome(String number){
if(number.length() == 1){
System.out.println("yes");
}else if(number.charAt(0) == number.charAt(number.length()-1)){
isPalindrome(number.substring(1, number.length()-1));
}else{
System.out.println("no");
}
}
Testing with:
isPalindrome(String.valueOf(232)) Returns "yes"
isPalindrome(String.valueOf(23)) Return "no"
Of course this also works with Arrays just as easily. Replace the parameter with an array and search through the indices the same way. When cutting down the array just create a new smaller array without first and last index of the previous array.
Your class has several issues:
First you're not checking if a number is a palindrome or not. Your algorithm is flawed
Second, you're asking to enter a size but in the end, the user inputs it but you don't use it yourself. Instead, you're using that introduced value in the number array.
Here's how you should do it.
public class Palindrome {
private static boolean isPalindrome(int[] array) {
for (int i = 0, j = array.length-1; i < j; i++, j--) {
if (array[i] != array[j]) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you want to enter? ");
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter number %s: ", i+1);
numbers[i] = scanner.nextInt();
}
if (isPalindrome(numbers)) {
System.out.println("The number is a palindrome");
} else {
System.out.println("The number is not a palindrome");
}
}
}