Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

java - why does the code loop past 122 in ASCII Binary

So I'm having trouble understanding why the given code doesn't work out as intended as expected, what I want to get is for it to output the letter change (the change value) so for example the letter "a" + change(has a value of 3) is going to produce "d", except when the letter "number" + the change are greater than the letter "z" which has a value of 122 then it will loop to a and then go from there . (I tried every possible way to fix it but it doesn't work out as expected) please help thanks :D (also here is the input yzdkvyzgtyrkdspkcstqdkxlvpckdstckslbopbkotokizekmbedpkqzbnpkdstckmikdbityrkcstqdckzypkldklkdtxpkzbkecpklkqzbkwzzkdzkozkdspkcstqdtyrkwplcpkgbtdpkmbedpkqzbnpklckdspkvpikqzbkdlcvkyexmpbkdgz)

package LabExperience;

import java.util.Scanner;

public class LabExperienceChiper {
    public static void main(String[] args) {
        System.out.println("enter the code");
        Scanner machine = new Scanner(System.in);
         String let = machine.next();
         String news = "";
         int find;
         int find2;
        for(int change = -1; change <= 1; change++)
        {
         for(int x = 0; x<let.length(); x++)
         {
             char num = let.charAt(x);
             if(num + change > 122)
             {
                 find = 'z'-num;///find how much to take away from the change
                 find2 = change-find;////this takes the value 0f change and subtracts what is taken and adds it to the value of 'a'
                num= (char) (num + find2);
                news = news+num;
             }
             else
             {
                 if(num + change <= 122)
                 {
                 num = (char) (num + change);
                 news = news + num;
             }
             }
         }
        System.out.println(news);
        news = "";
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So I figured out what the problem was in line 32 (the find 2 section). I didn't subtract 2 which caused an additional adding for the binary number (so 97 would be 99).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...