You are here:

Java/code query..very urgent!

Advertisement


Question
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.in);
     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;
     while(i>a){
        r1 = x%10;
        r2 = ((x%100)-r1)/10;
        c = r1-r2;
        if (c != 1){
         z = 1;
        }
        x = x/10;
        i = i+1;
     }
     if(z==0){
        System.out.print("step");
     }
     else{
        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:
while(i>a){

It probably should be:
while(i<a){

As you have it now, the loop never executes.

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

to

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) !?

Answer
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.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

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

Experience

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#

Organizations
Washington State University

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

©2016 About.com. All rights reserved.