Java8-StringIndexOutOfBoundsException - java

This is my code snippet:
import java.util.Scanner;
public class Numrs {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int pos, i = 1;
char d;
while (num <= 10) {
String line = in.nextLine();
pos = line.length();
if (line.length() <= 1000000) {
if (line.charAt(i) == 'R') {
line.replace('R', 'K');
i++;
}
if (line.charAt(i) == 'K') {
line.replace('K', 'R');
i++;
}
num++;
}
}
}
It's showing a StringIndexOutOfBoundsException when I enter a single digit number like 3, and even if a 2 digit number is entered, it's getting terminated without reading the string. Please help.

Well, if you enter only one character /digit, then size will be 1 but it will be placed in index 0. and you are trying to do line.charAt(i) where i=1

There are many problems in this approach.
1. The input you need to pass is more than a digit, like 3 this works because after the 3 your in expects some string.
you are not updating num. So it will end up in an infinite loop
This won't work if you give any value more than 10. I m not sure what you wanted to achieve.
Start i from 0, Developers start with 0 :)

Related

Find the binary equivalent of integer in Java using a while loop

I'm new to Java. I've been writing code to find the binary equivalent of an integer in Java using a while loop. I've written the following code and it's not throwing any error, but it was not printing INVALID INPUT. It is printing the valid binary number of a given integer value. Can anyone suggest where and what I'm doing wrong? And how should I get the proper input?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if ((n >= 0) && n > 999) {
System.out.println("Invalid Input");
} else {
while (n > 1) {
if (n <= 999) {
System.out.println(Integer.toBinaryString(n));
break;
}
}
}
}
}
Change && to ||:
if (!(n >= 0) || n > 999) {
Or even better, express conditions without negation:
if (n < 0 || n > 999) {
Positive conditions, ie "a is b", are easier to read.
Why are you using a loop at all? You're just adding needless complexity. Your code can be re-written to this:
if (n >= 0 && n < 1000) {
System.out.println(Integer.toBinaryString(n));
return;
}
System.out.println("Invalid Input");
You haven't said if this is an assignment but typically it is done like this for such questions.
loop until value is 0
get remainder from division by 2.
prepend to string
divide n by 2 to expose next binary digit.
// get some input,
int n = 1249;
String s = "";
while(n != 0) {
s = (n%2) + s;
n/=2;
}
System.out.println(s);
prints
10011100001

binary to decimal converter without using parseint or arrays

Getting string index out of range but I don't understand why I've went through it about 50 times
import java.util.Scanner;
public class binary {
public static void main(String[] args) {
System.out.println("Enter the first binary number");
Scanner keyboard = new Scanner(System.in);
String num1 = keyboard.next();
//System.out.println("Enter the second binary number");
//String num2 = keyboard.next();
int total = 0;
for(int i = num1.length(); i>0;i--) {
if(num1.charAt(i) == 1) {
total += 2*i;
}
}
if(num1.charAt(3) == 1) {
total -= 1;
}
System.out.println(total);
}
}
Here's a complete solution to what you're trying to do, including a set of tests:
class binary {
private static int binaryToInt(String binary) {
int total = 0;
for (int i = 0 ; i < binary.length(); i++) {
total *= 2;
if (binary.charAt(i) == '1')
total += 1;
}
return total;
}
private static void test(String binary, int expected) {
int n = binaryToInt(binary);
String rightWrong = "right";
if (n != expected) {
rightWrong = String.format("WRONG! (should be %d)", expected);
System.out.printf("%s -> %d is %s\n", binary, n, rightWrong);
}
public static void main(String[] args) {
test("0", 0);
test("1", 1);
test("10", 2);
test("100", 4);
test("111", 7);
test("0000111", 7);
test("1010101010", 682);
test("1111111111", 1023);
System.out.println("");
// test sanity check
System.out.println("This last test should fail (we are just testing the test method itself here)...");
test("1010101010", 0);
}
}
Result:
0 -> 0 is right
1 -> 1 is right
10 -> 2 is right
100 -> 4 is right
111 -> 7 is right
0000111 -> 7 is right
1010101010 -> 682 is right
1111111111 -> 1023 is right
This last test should fail (we are just testing the test method itself here)...
1010101010 -> 682 is WRONG! (should be 0)
One significant problem in your code hasn't yet been addressed in the comments or earlier answers. Note this line vs the one in your code:
if (binary.charAt(i) == '1')
You were testing for the numeric value 1, which is never going to be true because you're getting back a character from charAt(), not a number.
While length() counts the number of elements, their indexes start at 0. For a string of "1111" the last character would be at index 3, not 4, so .length()-1. You would need to either change your for statement to for(int i = num1.length()-1; i>=0;i--) (notice also the condition change) or change the charAt statement to if(num1.charAt(i-1) == '1').
Also, based on what you are trying to do, I assume for total += 2*i you actually need something like total += Math.pow(2, i-length()) depending on what you decide to do with i first.

How to print single number only once using nested loops in Java?

Everything runs fine in my Java code except at the very end of the code. So basically I can't figure out how to print out the User's Number if it is the same. For example I am prompt the User for a starting number and an ending number (integers). So say the user enters in the same integer "10" for starting number and "10" for ending number. I want the output to only be "10" to be printed only just once. I've tried everything I can think of with trying While Loop, Do-While Loop, and For Loops but I just can't figure it out?
------------------------JAVA CODE BELOW-------------------------------------------
import java.util.Scanner;
public class LoopsAssignment {
public static void main(String[] args) {
// input Scanner
Scanner input = new Scanner(System.in);
// ask user for a starting number and a ending number
System.out.println("Now I'll print whatever numbers you'd like!");
System.out.println("Give me a starting number: ");
startNum = input.nextInt();
System.out.println("Give me an ending number: ");
endNum = input.nextInt();
// count the users range of numbers
System.out.println("I counted your range of numbers: ");
int a = startNum;
int b = endNum;
while (a <= b) {
System.out.println(a);
a = a + 1;
}
while (a >= b) {
System.out.println(a);
a = a - 1;
}
while (a == b) {
System.out.println(a);
}
}
}
---------------------OUT PUT BELOW -----------------------------------------------------
Now I'll print whatever numbers you'd like!
Give me a starting number:
10
Give me an ending number:
10
I counted your range of numbers:
10
11
10
----jGRASP: operation complete.
You could restructure your code as follows:
while (a < b) {
System.out.println(a);
a = a + 1;
}
while (a > b) {
System.out.println(a);
a = a - 1;
}
if (a == b) {
System.out.println(a);
}
You can use for loop:
public static void printRange(int minInclusive, int maxInclusive) {
for (; minInclusive <= maxInclusive; minInclusive++)
System.out.println(minInclusive);
}
So you are either counting up, down or there's just one.
So
int step = endNum>startNum ? +1 : -1;
int a = startNum;
int b = endNum;
while (a != b) {
System.out.println(a);
a = a + step;
}
System.out.println(b);
Or put a break in the middle of a for loop. Also there's +=, and a few things we can make more conventional.
int step = endNum>startNum ? +1 : -1;
for (int i=startNum; ; i+=step) {
System.out.println(i);
if (i == endNum) {
break;
}
}
The issue is in your first two while loops where you are using ">=" and "<=". You can remove "=" from the condition.
However you can improve your code as suggested in other comments.

Issue with flow of a program

I am new to Java and just learning the basics.
I have gone through if checks/statements(if-if-if; if-else if-else, if-else), while and for loops as well. I have an assignment which I can not for the life of me figure out. I am having some issues with the flow of the program itself and I just get it to work half way through in Eclipse.
The idea of the program is for it to accept three integers from the keyboard(keyboard input using Scanner) and print out all numbers, between 0 and the first integer from the input, which can be divided by the second and third input integers, respectively. The first input integer has to be between 200 and 100. I will provide what code I have written. I can get the program to accept input but then I get the message in the console.
I set up the three integers, I set up a condition for the first integer using a while loop and then I use a for loop to print all the numbers between 0 and the first input integer. Then within the for loop I do in if check and print out all the numbers. It accepts the input three times but then I just goes to terminated status.
package Javawork;
import java.util.Scanner;
public class Test {
private static Scanner keyboard;
public static void main(String[] args) {
firstProgramme();
}
public static void firstProgramme() {
keyboard = new Scanner(System.in);
System.out.println("Enter number: ");
int firstNum = keyboard.nextInt();
int secondNum = keyboard.nextInt();
int thirdNum = keyboard.nextInt();
while (firstNum > 100 && firstNum < 200) {
for (int i = 0; i <= firstNum; i++) {
if (i % secondNum == 0 && i % thirdNum == 0) {
System.out.println(i);
}
}
}
}
}
As per your requirement you need to check whether the first number is between 100 and 200. For that you should use
if(firstNum > 100 && firstNum < 200) {
instead of
while(firstNum > 100 && firstNum < 200) {
As if will check the condition and while will iterate based on condition.

Unsure what the issue is

I'm really new to this whole programming thing, and I'm trying to wrap my head around why the loop ends abruptly and does not continue to the final if statement. Can you guys help me figure out whats wrong?
import java.util.Scanner;
public class FunnyAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many values to read? ");
int top = in.nextInt();
System.out.print("Enter Value: ");
int one = in.nextInt();
int number = 1;
int sum = 0;
sum = sum + one;
while (number <= top) {
if (one % 6 != 0 && one % 17 != 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
} else if (one % 6 == 0 && one % 17 == 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
}
}
if (sum / top != 0) {
System.out.print("Average: " + sum / top);
}
System.out.print("None Divisible");
}
}
The final if() condition executes if you give the right input values. I ran your code and gave the below inputs to execute the final if() statement.
How many values to read? 1
Enter Value: 1
Enter Value: 1
Average: 1None Divisible
I dont understand what are you trying in the code, but there are many things missing like i assume you want to capture the sum of the input numbers, but sum is not used in the while loop.
Looks like you end up in the non-present else case (within the while loop). Consequently, number isn't increased and you are stuck in the while loop.
Try reading one within the while loop. This way the user will be prompted to enter a new number in each loop.
Otherwise you will be stuck in the while loop once the user enters a number that isn't conform with your checks.

Categories