Scanner s = new Scanner(System.in);
String num = s.next();
char a = num.charAt(0);
char b = num.charAt(1);
char c = num.charAt(2);
char d = num.charAt(3);
For example , we can do it like this but i will enter long values for input so how can i write it like loop or easier rather than write 20 line as ı wrote ?
I thought , i can write it using "for" but i couldn't.I am new to java so if you can solve it using basic methods or codes and explain so , i would be grateful.
Scanner inp = new Scanner(System.in);
System.out.println("Enter the number");
String num = inp.next();
char a = num.charAt(0);
char b = num.charAt(1);
char c = num.charAt(2);
char d = num.charAt(3);
char e = num.charAt(4);
char f = num.charAt(5);
char g = num.charAt(6);
char h = num.charAt(7);
if (a < '2') {
System.out.print("0" + "" + b + "" + c + "" + d + "" + e + "" + f + "" + g + "" + h);
} else if (a > '2' & h == '0') {
System.out.print("0" + "" + b + "" + c + "" + d + "" + e + "" + f + "" + g + "" + "1");
} else if (a > '2' && h == '1') {
System.out.print("0" + "" + b + "" + c + "" + d + "" + e + "" + f + "" + g + "" + "0");
}
As well,Im trying for easier way of that.
Thanks in advance.
You can't do this with variables named
a,b,c, etc. You could only do it with an array, where you could index them by number, e.g.char[] chars, and usechars[0]instead ofa,chars[25]instead ofz, and so on.To do that, you can just do
char[] chars = num.toCharArray(), or even skip the array entirely and keep usingcharAt.