Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Coding Challenges: Code tips or tricks  RSS feed

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I created this topic for codes. Of course. BUT

Yesterday I realized when I sent a small bug - that so many other Marshalls helped to solve it and even show a better way.
For example yesterday I realized the Boolean

and


better than this:

to avoid bugs like this:




This is why I created this. Here is the idea:


If there is TASK, Challenge any question regarding a code, come here and ask it with the description of the Challenge and your code and the plan how to solve it.

Somebody will have a better way or perspective - and through this we will learn.

This is the Tips or Tricks "blog"


halloween-hero-1.jpg
[Thumbnail for halloween-hero-1.jpg]
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I struggle with this task:

-Read 10 numbers from the console entered by the user and print the sum of those numbers.
-Create a Scanner like we did in the previous video.
-Use the hasNextInt() method from the scanner to check if the user has entered an int value.
-If hasNextInt() returns false, print the message ÅgInvalid NumberÅh. Continue reading until you have read 10 numbers.
-Use the nextInt() method to get the number and add it to the sum.
-Before the user enters each number, print the message ÅgEnter number #x:Åh where x represents the count, i.e. 1, 2, 3, 4, etc.
-For example, the first message printed to the user would be ÅgEnter number #1:Åh, the next ÅgEnter number #2: Åh, and so on.

Hint:
-Use a while loop.
-Use a counter variable for counting valid numbers.
-Close the scanner after you donÅft need it anymore.
-Create a project with the name ReadingUserInputChallenge.



I found out this but it gives me two times to enter an Integer meanwhile the second one isn't even stored.
I have also a question about it:
- How can I create a Getter to send out to the Stored SUM the outter part of the console ?
So I know the problem that it is inside the scope but how could I get that sum to print it out?


 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
https://paste.ofcode.org/jMYRNmFDUgxyLJHQWRYpFk



[code=java]
int count = 1;
       do{

           Scanner inputDataClass = new Scanner(System.in);

           System.out.println("This the #" + count + " please enter a number: ");
           int something1 = inputDataClass.nextInt();
           boolean hashNextInt = inputDataClass.hasNextInt();
           int sum += something1;

           count++;

           if (! hashNextInt) {
               System.out.println("The entered data type is invalid.");
           }
           System.out.println("The entered numbers' sum is: " + sum + " at " + count);

       } while (count <= 8);

[/code]



*Disabled BB code in the message
 
Marshal
Posts: 61741
193
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried that sort of code on JShell? You can even mimic System.in there.
Start counting from 0 and make the continuation test use < rather than <=. That is the usual way to do it in Java®.
Don't create the Scanner in the loop; you need one Scanner per application to read from System.in. And make sure never to close it. I think the name inputDataClass is inappropriate because it points to an object, not a class.
Once you have removed the instantiation from the loop, go through the loop with pencil and paper and work out what is happening at each part of the loop. I think all the parts are correct, but they are in the wrong order.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Have you tried that sort of code on JShell? You can even mimic System.in there.
Start counting from 0 and make the continuation test use < rather than <=. That is the usual way to do it in Java®.
Don't create the Scanner in the loop; you need one Scanner per application to read from System.in. And make sure never to close it. I think the name inputDataClass is inappropriate because it points to an object, not a class.
Once you have removed the instantiation from the loop, go through the loop with pencil and paper and work out what is happening at each part of the loop. I think all the parts are correct, but they are in the wrong order.



I still do not know about anything Unit Testing - I know that is something which is important in JS too and heard some program with it.
As I guess it is a "unit-based" / "byte-based" testing system which check the code and the compiler how many date have been sent. (?)


I found an another challenge - will detail in the next post.

Thank you in advance, I will do my research. Also the webpages!
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-Read the numbers from the console entered by the user and print the minimum and maximum number the user has entered.
-Before the user enters the number, print the message ÅgEnter number:Åh
-If the user enters an invalid number, break out of the loop and print the minimum and maximum number.

Hint:
-Use an endless while loop.

Bonus:
-Create a project with the name MinAndMaxInputChallenge.






Here is mine solution for it.
There is a bit misunderstanding at the scannerName.NextLine(); / Which should handle nextLine. I do not know what it is actually.

Please try to explain in plain - it is very helpful if you have a webpage or something which is helpful.
Try to organize in order that later somebody else will use this as a learning page.
Thank you!


 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.Scanner;

public class MinimumAndMaximum {

   public static void main(String[] args) {

       int count = 0;
       int max = 0;
       int min = 0;
       boolean first = true;

       Scanner minimumMAximumInput = new Scanner(System.in);
       while(true){

           System.out.println("Enter a number: ");
           boolean hashNextInt = minimumMAximumInput.hasNextInt();

           count += 1;
           if(hashNextInt) {

               int storedNumber = minimumMAximumInput.nextInt();

               if(first){
                   first = false;
                   min = storedNumber;
                   max = storedNumber;
               }

               if(storedNumber > max) {
                   max = storedNumber;
               }

               if(storedNumber < min) {
                   min = storedNumber;
               }

               if(count == 5) {
                   break;
               }
           } else {

               System.out.println("Invalid number");
               break;
           }

           minimumMAximumInput.nextLine(); // Handle nextline input (?) QUESTION
       }

       System.out.println("The minimum number of this: " + min);
       System.out.println("The maximum number of this: " + max);


       minimumMAximumInput.close();

   }




}
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another solution without boolean flag to test


import java.util.Scanner;

public class MinimumAndMaximum {

   public static void main(String[] args) {

       int count = 0;
       int max = 2147483647;
       int min = -2147483647;


// This implicates that any numbers what the user will press in this range.
       

       Scanner minimumMAximumInput = new Scanner(System.in);
       while(true){

           System.out.println("Enter a number: ");
           boolean hashNextInt = minimumMAximumInput.hasNextInt();

           count += 1;
           if(hashNextInt) {

               int storedNumber = minimumMAximumInput.nextInt();

               if(storedNumber > max) {
                   max = storedNumber;
               }

               if(storedNumber < min) {
                   min = storedNumber;
               }

               if(count == 5) {
                   break;
               }
           } else {

               System.out.println("Invalid number");
               break;
           }

           minimumMAximumInput.nextLine(); // Handle nextline input (?) QUESTION
       }

       System.out.println("The minimum number of this: " + min);
       System.out.println("The maximum number of this: " + max);


       minimumMAximumInput.close();

   }




}
 
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:I still do not know about anything Unit Testing...


Unit testing doesn't have anything to do with the compiler.  It tests the behavior of the class methods.  The most popular unit testing framework is JUnit.  Google it to find more info.
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look carefully at your nested if statements testing for min and max.  Are they doing what want?

More minor, you can use Integer.MAX_VALUE and Integer.MIN_VALUE to set min and max.
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you need this statement?
Try commenting it out and see how it runs.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!

I will try it out and google some more information for Unit testing.


On that line of code my quesiton is that what is it doing?

The program works properly as it excepted.
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was looking at the code you posted here:

https://coderanch.com/t/702679/java/Coding-Challenges-Codes-Tips-Tricks#3295034

The lines look like this:

               if(storedNumber > max) {
                   max = storedNumber;
               }

               if(storedNumber < min) {
                   min = storedNumber;
               }  


And are also related to this:

       int max = 2147483647;
       int min = -2147483647;  


I'll look at the program listing above this one too.
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In both your programs listed above, you have a problem if the user enters something other than an int.  You program terminates.  Instead, it should ask for a number again.
 
Campbell Ritchie
Marshal
Posts: 61741
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:. . . Hint:
-Use an endless while loop. . . .

Disagree. There are much better ways to run a loop than an infinite loop; to those of us who study program semantics, the infinite loop is the epitome of a program gone completely wrong.There is a far better way to run a loop using a Scanner, using methods already defined in the Scanner object.
Scanner documentation link, to make it easier for you to find. It even shows an example similar to what you want .

-Before the user enters the number, print the message ÅgEnter number:Åh

What encoding is your teacher using?
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Knute Snortum

Yes, this is why now I am learning more about the different method what I've just studied.
Some parts are still foggy - I mean I should dive into it because just now I've realized that the different objects are pre-made methods which uses the Java syntax or other language's keywords and methods.
With this information I just put together that probably this is why so many different language have been made in C-language.
( https://softwareengineering.stackexchange.com/questions/267086/is-every-language-written-in-c )

For this / if the user enter an another type of data value, I grabbed an info about scannerobject.hasNextInt(); boolean method.
Sometimes I still lost in it because what I said before - two times put an input in the console - sometime I find a clue where I can continuesly put toghether what I know.

Now, I show from my head what could be a solution for my perspective:

I stumbled a question here which is if I create a ' boolean ' to test the firstly typed value then where should it be ?
Before  int somethign = sc.NextInt(); or after ?

Also are there any good solution to do not run 6 times a simple question ?
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's Tim Buchalka, but sometime I surpised too when he suggested that create an infinite loop with an expectation ( are there any name for it? ) which is always true.

Where can I study programming semantics ?
I am really interested in that it's like a program development philosophy!
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is amazed me!



   Is each and every language written in C language?

A language is a set of abstract mathematical rules and restrictions ("if I write this, that happens"). It isn't written in anything, really.

It is specified, usually in a mixture of a formalized subset of English, mathematical notation, and maybe some specialized specification language. The syntax is often specified in a variant of EBNF or ABNF.





   Is C language mother/father of all languages?

No, it is not. C is pretty young. There are a lot of old languages. Since time travel is physically impossible, it is simply impossible for C to have had any influence whatsoever on those old languages.

   Plankalkül (1943)
   Speedcoding (1953)
   Fortran (1954)
   IPL (1956)
   Lisp (1958)
   Algol (1958)
   COBOL (1959)
   JOVIAL (1960)
   APL (1962)


Plankalkul?

By the way I think time travel even according to Feyman's theory is possible indeed. Also I could not agree that a future object does not influence a previous object - I mean in the term of philosophical questions. :B
 
Campbell Ritchie
Marshal
Posts: 61741
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nonononononononono!

Never close a scanner reading from System.in.

we used to teach programming semantics here, but that course hasn't run for about five years
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And this is why it is really amazing because in this post they mentioned this webpage where I stumbled this:

White space

White space is used to separate elements of a definition; for space to be recognized as a delimiter, it must be explicitly included. The explicit reference for a single whitespace character is WSP (linear white space), and LWSP is for zero or more whitespace characters with newlines permitted. The LWSP definition in RFC5234 is controversial[4] because at least one whitespace character is needed to form a delimiter between two fields.

Definitions are left-aligned. When multiple lines are required (for readability), continuation lines are indented by whitespace.



In this case the Scanner object delimeter which recognizes white space has a relation with this.
I just assumed that this is beging translated into code what the CPU adds together to create a new outpot for you, right?

 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Back to the topic. So How can I test that there is a number or a string there ?

I found this but in this case the boolean prevents to type in something.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:So How can I test that there is a number or a string there ?


I would suggest you create a method that looks like this:
 
Campbell Ritchie
Marshal
Posts: 61741
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:Back to the topic. So How can I test that there is a number or a string there ?  . . .

That question doesn't make sense. All the input is in the form of a String, even the whitespace you are ignoring. Some of those Strings also represent a number. The hasNextXXX() methods of Scanner, as you can tell from Knute's post, test whether the next token is also in the right format to be an XXX.
The learning practice example hides a serious error: that of using double arithmetic for money.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!

So then I can use in the input part an entire object ? And does it test the entire object - I guess.
public static int something(Scanner scannerObjectName) {} ?


Also why do you think that it is an arithmetic probelem? Because I experienced that sometimes it puts out a long and faulty number line - like: 200.0000007 or similar and I solve it with a method.


Now I am workin on this:
Write an isPalindrome(){} method. It should return a boolean and accept an Int.

I found out that may I need:
public static boolean isPalindrome(int originalNumber){
// Then I store the integer into a String to read it backwards with a for loop

String reverse = Integer.toString(originalNumber);

// This is tricky and I stumbled some questions
for (int i = reverse.length(); reverse.lenght() =< 0; reverse.length - 1;){

// Here the center question that how I could store values. I think it is
char A = reverse.length()-1;
String reversedWord += char A;
}
Int reversedNumber = Integer.parseInt(reversedNumber);
// which is actually a number //

if (reversedNumber == originalNumber){
return true;
} else{
return false;
}


}

}

What do you think about this?
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:So then I can use in the input part an entire object ? And does it test the entire object - I guess.
public static int something(Scanner scannerObjectName) {} ?


If you declare the Scanner object outside of any method (usually at the top of the class) then you can use it in any method in that class.  You don't need to pass the Scanner object into a method with a parameter.
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:Also why do you think that it is an arithmetic probelem? Because I experienced that sometimes it puts out a long and faulty number line - like: 200.0000007 or similar and I solve it with a method.  


Doubles, and any floating point object, are going to be approximations.  Use the class BigDecimal to rectify this.
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:Now I am workin on this:
Write an isPalindrome(){} method. It should return a boolean and accept an Int.

I found out that may I need:
public static boolean isPalindrome(int originalNumber){ ...


Please UseCodeTags (that's a link).  Is this code yours?  If not, tell us the source.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Guys in my one-person blog.. So

I found out this one but a bit confused that where I should put the return to get back the value of a boolean.
It should test that it is a palindrome number or not.

 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:What do you think about this?


Well, first off, it's poorly formatted.  Learn HowToFormatCode (that's a link).  Because the formatting is bad, you can't see that there's an extra brace (}) at the end.
There are all sorts of problems here.  The first is that reverse.length() is being used as if a value could be assigned to it.  The syntax of the for loop is incorrect.   There are a few other problems that I'll leave to you.
You can't initialize a char with a number.  It is the Java convention to use camelCase for variables and method names.
Int should be int (lowercase).
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote: I found out this one but a bit confused that where I should put the return to get back the value of a boolean.
It should test that it is a palindrome number or not.


The boolean value is being returned here, but it's not the best way to do this.  You can reduce the code to this one line:
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tomorrow I will take a closer look what you wrote.

Now I revised the method and came out with this.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for posting your new code.  I couple of small things:

1) Line 30, "Please type a valid number" isn't the best warning.  Maybe "Please type an integer greater than zero."

2) numberChangable isn't a good parameter name.  Name it what it is, maybe candidateNumber.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is candidateNumber better ?
( I agree because you're the expert just asking if there is an approach)
I heard that there are different type of variable naming like CamelCase etc-etc.

I have a new question - I solved this challenge on HackerRank and it looks like this (The question is not about algoritmic then about a compiler error)
Objective In this challenge, we're going to use loops to help us do some simple math.  Task Given an integer, , print its first multiples. Each multiple (where  ) should be printed on a new line in the form: N x i = result.  Input Format  A single integer,  .  Constraints  Output Format  Print lines of output; each line (where ) contains the of  in the form: N x i = result.  Sample Input


This is the solution:
for(int i = 1; i <= 10; i++){
           int result = i *N;
           System.out.println(N + " x " + i + " = " + result);


But when I click run on this page - not hackerrank but similar. I got this error:

Main.java:8: error: variable n might not have been initialized
           int result = i * n;
                            ^


What's the problem here?

If I do not write there
int n - this will come up the same. If I write there it will say that " outpot is different then teh input.
If I build a scanner it is also not working.

What do you think?



 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:Why is candidateNumber better ?
( I agree because you're the expert just asking if there is an approach)
I heard that there are different type of variable naming like CamelCase etc-etc.


First, questioning experts is a good thing (up to a point).

To me, numberChangable does tell much about what the variable is doing.  candidateNumber implies at least that this number is something, and in context you can see that something is a palindrome.  Maybe candidatePalindrome is a better name.

Camel case is the traditional way to name variables and methods.  It looks like this: thisIsCamelCase.  Classes, and therefore types, are in Pascal case, which is camelCase with the FirstLetterUpperCase.

But neither of these describe what a variable is, they are just naming conventions.
 
Knute Snortum
Sheriff
Posts: 5446
147
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Barbara Fischer wrote:
But when I click run on this page - not hackerrank but similar. I got this error:



What's the problem here?  


Well, the code has a capital N (terrible variable name) and error message has a lowercase n, but beyond that, this is a code fragment.  It assumes a lot of setup, for instance, how is N set?  From the keyboard? Past in as an OS argument?

Also, I'm assuming that there is a closing brace for the for-loop.  Remember that programming is a very precise disiplin.
 
Barbara Fischer
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Knute that you put in the work - really!
This is something what I really appreaciate and I hope that later when I am able to achieve a good command of Java coding - I give it back to the society or our community.

I solved the problem - there were an input and it was needed a Scanner. I created one inside the contstructor a (System.in) method(? - do I tell it correctly? ) and it worked.

I have a bunch of different task whic should be somehow solved - and also I need to put and store all knowledge from it. Could you help in that ?

Similiar like this - actually HackerRank challenges.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!