You are here:

Java/code query..very urgent!


QUESTION: "I was given this question:"A number is said to be a step number if for each pair of consecutive digits in the no. the difference is 1 (eg:456567). Single digit numbers can be considered as step numbers."

Here's the code I've written:
import java.util.*;
public class question2 {
  public static void main(String[] args){
     Scanner s = new Scanner(;
     System.out.print("Input Nmber:");
     int x = s.nextInt();
     String y = s.nextLine();
     int a = y.length();
     int r1 = 0;
     int r2 = 0;
     int z = 0;
     int c = 0;
     int i = 0;
        r1 = x%10;
        r2 = ((x%100)-r1)/10;
        c = r1-r2;
        if (c != 1){
         z = 1;
        x = x/10;
        i = i+1;
        System.out.print("not step");

the problem is that the code ALWAYS gives me "step" even if the no. is not!! and I don't know why is that!!!
I really need a very quick reply coz I've an exam tomorrow! Thank You in advance.

ANSWER: You have:

It probably should be:

As you have it now, the loop never executes.

Also, you should probably change:
if (c != 1){


if (c != 1 && c != -1)

Since the number can go up and down.

---------- FOLLOW-UP ----------

QUESTION: I'm sorry for disturbing but the code still doesn't want to work!! What do you think I should do?
plus I didn't really get why the if condition should be ( c != 1 && c! = -1) !?

Alright, another issue I see is the line:
String y = s.nextLine();

Since you already read in a number the remainder of the line is empty. So, y will be "".

This means that:
int a = y.length();

will always be 0.

If you aren't using an IDE, get one. Java IDEs have debuggers that you can use to walk though the code and look at values as the code runs.


All Answers

Answers by Expert:

Ask Experts


Artemus Harper


I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.


I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Washington State University

MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2017 All rights reserved.