Not understanding the condition - java

I'm having problem with the condition that is in the for loop, I don't understand it, I know what it does, but I can't understand the logic of the code condition, can someone please explain it to me the logic of the condition:
if(smallWord == null || bigWord.compareTo(smallWord)<0)
/*2. Enter the Exercise2 class that performs this function:
1. Instructs the user to type a number [at least four (4): to use while loop] which indicates how many
words / sentences will be typed, and using for loop to ask the user to type those words / sentences.
2. Find and display on the console which word / sentence is the smallest (comes first alphabetically). */
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type a number greater than 4");
int size = scan.nextInt();
while (size < 4) {
System.out.println("Type a number greater than 4");
size = scan.nextInt();
}
scan.nextLine();
String smallWord = null;
for (int i = 0; i < size; i++) {
System.out.println("Shtypni fjaline e " + (i + 1) + ": ");
String bigWord = scan.next();
if (smallWord == null || bigWord.compareTo(smallWord) < 0) {
smallWord = bigWord;
}
}
System.out.println("The smallest word/sentence alphabetically is: " + smallWord);
}
}

The condition ensures that bigWord will be assigned to smallWord if:
smallWord == null
Or
bigWord is 'lesser' than smallWord (because compareTo() returns a value less than 0 if the string is lexicographically less than the argument)

The purpose of the for loop as a whole is to find the word that is lexicographically the smallest.
The way this is done is to compare each new word (bigWord) to the smallest one found so far (smallWord).
So the if test says 'if either no smallest word has been found so far, or this new word is smaller than the one found so far, then this new word is the smallest one we have right now'.

Related

Issues with loops? Program runs as it should but test keep failing. Java using TMCbeans

I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.

How to return the correct value from an int[] array?

I'm new to Java (and programming in general), so apologies if some of this doesn't make sense and/or if the code is really bad:
I am trying get a unique four digit code from a user input (that is what the Keyboard.readInput line does), and I have put in a couple of conditional statements to ensure that the code that is entered can only be 4 digits and that each digit must be different to the other three.
The if statements work as intended in the sense that they output the error message and prompt them to re-enter (i.e. the method getPlayerGuess() gets called). For example, if the user enters 123 (i.e. userGuess.length() != 4), it will prompt them to enter again. If they then enter 1234, the method will complete.
However, the problem I have is that when I call this method in another class that I have, the code that is being pulled through is the first code entered (i.e. 123) and not the four digit one I want (i.e. 1234) - which is resulting in an array IndexOutOfBoundsException.
Any ideas on how I can ensure that the code that is being returned is the four digit one that passes the conditionals, and not the first one entered?
public int[] getPlayerGuess() {
System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
getPlayerGuess();
}
int[] userCode = createArrayFromGuess(userGuess);
for (int i = 0; i < userCode.length-1; i++){
for (int j = i+1; j < userCode.length; j++){
if (userCode[i] == userCode[j]) {
System.out.print("Code must have four unique digits - ");
getPlayerGuess();
}
}
}
return userCode;
}
You call getPlayerGuess() which returns an int[] but you do not collect, nor assign the return value. Nor do you return it... so something like the following may work for you:
public int[] getPlayerGuess() {
System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
return getPlayerGuess(); // either assign or return the value that is actually calculated within that call...
}
int[] userCode = createArrayFromGuess(userGuess);
for (int i = 0; i < userCode.length-1; i++){
for (int j = i+1; j < userCode.length; j++){
if (userCode[i] == userCode[j]) {
System.out.print("Code must have four unique digits - ");
return getPlayerGuess(); // either assign or return the value that is actually calculated within that call...
}
}
}
return userCode;
}
Simplifying your code a bit (not too much ;-)):
public int[] getPlayerGuess(String msg) {
System.out.print(msg);
String userGuess = Keyboard.readLine();
if (userGuess.length() != 4) {
return getPlayerGuess("\nYour code must be 4 digits - ");
}
if (userGuess.chars().distinct().count() != 4) {
return getPlayerGuess("\nCode must have four unique digits - ");
}
return createArrayFromGuess(userGuess);
}
with the initial call being:
getPlayerGuess("Guess a four digit code: ");
Note that you can write this code also using an iterative approach. But I will leave that up to you.
Your problem lies here:
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
getPlayerGuess();
}
Yes, you call the method a second time, but you completely ignore that, and don't do anything with the result of it.
Change it to this:
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
return getPlayerGuess();
}
So you'll return the result of the new call, instead of completing the code after the if block.
EDIT:
A better approach would be:
System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();
while(userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
System.out.print("Guess a four digit code: ");
userGuess = Keyboard.readInput();
}

How would I take a user-input number and work on its digits individually?

I'm prompting a user for a number and am trying to determine the amount of even, odd, and zeros in that number
/* This program will determine and print the number of even, zero, and odd digits in
* an integer
*
* Author: Marco Monreal
* Date: 11/01/2016
*/
import java.util.Scanner;
public class PP5_3
{
public static void main(String[] args)
{
String exit_loop, go_again, user_num, first_char_string;
int odds, evens, zeros;
int first_char; //, second_char, third_char, fourth_char, fifth_char, sixth_char, seventh_char, eighth_char, ninth_char, tenth_char;
Scanner scan = new Scanner (System.in);
evens = 0;
odds = 0;
zeros = 0;
exit_loop = "no"; //initializing while loop
while (exit_loop.equals ("no"))
{
System.out.println ("Choose any number between 0 and 2,147,483,647. Don't include commas please.");
user_num = scan.next ();
I'm getting stuck around this area; "first_char" is not returning the digit value that I want/need.
//assigning a variable to each character of user_num
first_char = user_num.lastIndexOf(0);
/*second_char = user_num.charAt(1);
third_char = user_num.charAt(2);
fourth_char = user_num.charAt(3);
fifth_char = user_num.charAt(4);
sixth_char = user_num.charAt(5);
seventh_char = user_num.charAt(6);
eighth_char = user_num.charAt(7);
ninth_char = user_num.charAt(8);
tenth_char = user_num.charAt(9);*/
//copy every character into a string value
first_char_string = String.valueOf(first_char);
if (first_char == 2 || first_char == 4 || first_char == 6 || first_char == 8)
{
evens++;
}
else if (first_char_string.equals("1") || first_char_string.equals("3") || first_char_string.equals("5") || first_char_string.equals("7") ||
first_char_string.equals("9"))
{
odds++;
}
else
zeros++;
} //ends while loop
System.out.println ("There are " +evens+ " even numbers, " +odds+ " odd numbers, and " +zeros+ "zeros in ");
scan.close ();
} //ends main method
} //ends class
Hi take a look on this line:
user_num = scan.next (); // this will scan your user input, but does not jump to the next line
you might want to use:
user_num = scan.nextLine();
Also you made a mistake in your lastIndexOf(char) method.
This method expects a char. you supply this method an int e.g:
first_char = user_num.lastIndexOf(0);
this works because java interprets your number a an ASCI-number. the char representated by ASCI "0" is null. What you want to do is search for the character '0'. Like the following:
first_char = user_num.lastIndexOf('0');
The same for your equalisations:
first_char == 2 ---> first_char == '2';
Another notice. Please use camel case istead of underscores. instead of user_num you should write userNum. Thats the standard.
Yet another notice. The lastIndexOf() method will return the nummber of the last occurence of the parameter. e.g:
String test = "hello test";
test.lastIndexOf(e); // this will return 7 for it is the number ofthe last occurence of 'e'
I think yu want to use charAt(0) this returns the charactere at specified position
Last Notice. why are you comparing char values representing numbers ?
why not do the following:
int userNum = Integer.valueOf(yourCharHere).
Update
If I understood your comment correctly the your 'X' in the snippet below is defined by the user
first_char = userNum.charAt(X);
If I get you right you have a problem because you dont know how long the input of the user is. Instead of assigning the individual numers to variables I would do the following:
//Parsing your String into a int
int userNum = Integer.valueOf(yourUserInputHere);
Arraylist singleDigits = new ArrayList()<>;
//This goes through all digits of your number starting with the last digits
while (userNum > 0) {
singleDigits.add( userNum % 10);
userNum = userNum / 10;
}
//Reverses your list of digits
Collections.reverse(singleDigits);
Example input: 13467
your List should look like: [1],[3],[4],[6],[7]
This enables you to get the single digits by calling:
singleDigits.get(0) -> [1];
singleDigits.get(3) -> [6];
...
I hope that helps
First create sets that are containing odd/even/zero numbers:
Set<Integer> odds = "13579".chars().boxed().collect(Collectors.toSet());
Set<Integer> evens = "02468".chars().boxed().collect(Collectors.toSet());
Set<Integer> zero = "0".chars().boxed().collect(Collectors.toSet());
Then get an input from the user
Scanner scan = new Scanner(System.in);
System.out.println("Choose a number:");
String number = scan.next();
scan.close();
Parse number character by character to find out how many digits are matching each set:
long numberOfOdds = number.chars().filter(odds::contains).count();
long numberOfEvens = number.chars().filter(evens::contains).count();
long numberOfZeros = number.chars().filter(zero::contains).count();
Finally, display the result:
System.out.println("There are " + numberOfEvens + " even numbers, " + numberOfOdds + " odd numbers, and " + numberOfZeros + " zeros in ");

Find two smallest value inputs

The instructions are: "Ask the user for the following information, in this order:
A terminating value (real number). The user will enter this value again later, to indicate that he or she is finished providing input.
A sequence of real numbers. Keep asking for numbers until the terminating value is entered.
Compute and output the smallest and second-smallest real number, in that order. It is possible for the smallest and second-smallest numbers to be the same (if the sequence contains duplicate numbers)."
I uploaded my code and the grading software gave me a zero saying the program is not consistent with the assignment, however, when testing my code it runs just as required for the assignment. Any feedback as to why this may happen would be appreciated.
This is my code:
public class TwoSmallest
{
public static void main (String[] args)
{
double terminator;
System.out.print ("Please enter a terminating value: ");
terminator = IO.readDouble();
double lowest1;
double lowest2;
System.out.println("Please enter sequence of numbers:");
lowest1 = IO.readDouble();
while (lowest1 == terminator)
{
IO.reportBadInput();
lowest1 = IO.readDouble();
}
lowest2 = IO.readDouble();
while (lowest2 == terminator)
{
IO.reportBadInput();
lowest2 = IO.readDouble();
}
double input;
do
{
input = IO.readDouble();
if (input < lowest1)
{
if(lowest2 < lowest1)
lowest2 = lowest1;
lowest1 = input;
}
else if (input < lowest2)
lowest2 = input;
}while (input != terminator);
System.out.println("RESULT: " + lowest1);
System.out.println("RESULT: " + lowest2);
}
}
Here are the two scenarios which are not handled by your solution :
For suppose you have given the sequence of numbers 3,7,1 the result of your code is 1 and 7 not 1 and 3.
It is because you are not changing lowest2 value when input < lowest1.
If your input is 3,1,7 where first number is lowest1, second number is lowest2 and then input variable value is 7 then the condition (input < lowest1) is false, so there will be no swapping of lowest1 and lowest2 values and the result will be 3 and 1 instead of 1 and 3.

Finding letters in an array

I am trying to make a program, that lets me type in 10 characters and stores them in an array.
just single characters are enough, for example (d, s, a, e, h, j, e,). and then lets me look for one of the chars using linear search algorithm and gives out the position within the array.
I tried to program it but I can only do it with integers.
here is my code so far.
I don't know how to change it to letters / characters?
public static void main(String args[])
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " Letters");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("What letter do you want to find?");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
if (c == n) /* Searching element is absent */
System.out.println(search + " Letter is not found.");
I tried to program it but I can only do it with integers
No, you can do it if you use in.next().charAt(0) rather than in.nextInt() from Scanner Class to take the first Character form String.
I don't know how to change it to letters / characters?
Here you don't need to change it, or some regex or split it, the method in.next() get the String from the input (end-use) and then get the charAt(0) the first one.
Now, what i have changed in your code to be worked as you mentioned above:
Change search and array[] to char Data type.
Change the declaration of array[] to array = new char[n]
Change the input for search and array to in.next().charAt(0).
Try this:
public static void main(String args[]) {
int n,c;
char search,array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new char[n];
System.out.println("Enter " + n + " Letters");
for ( c = 0; c < n; c++) {
array[c] = in.next().charAt(0);
}
System.out.println("What letter do you want to find?");
search = in.next().charAt(0);
for ( c = 0; c < n; c++) {
if (array[c] == search) /* Searching element is present */ {
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
if (c == n) /* Searching element is absent */ {
System.out.println(search + " Letter is not found.");
}
}
}
The problem resides in your line array[c] = in.nextInt();. The nextInt() method of the Scanner class can read an integer, and only an integer.
You could try using array[c] = in.nextLine().charAt(0);, which would take any input from the console, store it temporarily as a String, get that String's first character, and store that. You would need to do the same to your second in.nextInt().
As an aside, it's generally bad practice to store char's in int's, even though it is valid Java. For example, I would change c and search to char's, and change array to a char[].
Here is a simpler approach, using Java's built-in functionality:
final Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of characters:");
final String input = in.next();
System.out.println("What do you want to find?");
final String search = in.next();
int pos = input.indexOf(search);
if (pos < 0) {
System.out.println("No match.");
} else {
while (pos >= 0) {
System.out.println("Found at location: " + pos);
pos = input.indexOf(search, pos + 1);
}
}
Differences:
There is only the scanning of the actual characters, because the length of the input defines how many characters the user actually wants to input.
The indexOf() method does about the same as your function, but it's faster and easier (because you don't actually need to code it).
This allows the user to scan for more than just one char. If that is not what is desired, I will leave it up to you to figure out how to change that. ;)

Categories