Why is my substring causing an error in my program? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
When I run this program, an error comes up, saying that it is due to "String.substring(int, int)line: not available. However, it outputs the correct answer (with a number of 123 and a target of 2, the final should be 35). Any help would be great, thanks!
import java.util.Scanner;
public class Math{
public static void main(String[] args) {
for (int i=1; i<=5; i++) {
System.out.println("Please enter your number:");
Scanner input = new Scanner(System.in);
String number= input.nextLine();
System.out.println("Please enter your target:");
int target= input.nextInt();
// input.close();
String outcome= "0";
long final = Long.parseLong(outcome);
for (int h=0; h<=((number.length())-target+1); h++) {
String result = number.substring(h, (target+h));
long output = Long.valueOf(result);
final = final + result;
System.out.println(final);
}
}
}
}

You have several problems here:
final is a reserved keyword, and cannot be a variable name. You must rename it
You are trying to add a String to a long in the line:
final = final + result;
You have a index out of bounds error when you call substring. You are looping one more time then necessary. Change <= to <:
Code:
String outcome= "0";
long finalVar = Long.parseLong(outcome);
for (int h=0; h<((number.length())-target+1); h++) {
String result = number.substring(h, (target+h));
long output = Long.valueOf(result);
finalVar = finalVar + output;
}
System.out.println(finalVar);
Input/Output:
Please enter your number:
123
Please enter your target:
2
35

Related

Java multiplication (in the type PrintStream is not applicable for the arguments (String, int)) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
Table of a any number
getting this error - on System.out.println(number+" x "+i+" = ",+number*i);
(in the type PrintStream is not applicable for the arguments (String, int))
package JAVAS;
import java.util.Scanner;
public class number {
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
System.out.println("Enter the number ??");
int number = num.nextInt();
int i=1;
System.out.println("the table of the following number is ");
while (i <= 10)
{
System.out.println(number+" x "+i+" = ",+number*i);
i++;
}
}
}
Your problem is you have an extra comma in your println. However, for clarity and to expose to you better methods of doing this, consider the following:
public static void main(String[] args) throws IOException {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the number ??");
int number = scanner.nextInt();
System.out.println("the table of the following number is ");
String format = "%d x %d = %d";
for (int i = 1; i < 11; i++) {
System.out.println(String.format(format, number, i, number * i));
}
}
}

How do I fix the unreachable statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I tried reading about this and I can't find the real problem. I'm new to java and it's my first time that I've encountered this problem. I tried putting the counter inside main method and outside of it and it still says unreachable statement.
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Harrylist{
static Random Userinput = new Random();
static Scanner input = new Scanner(System.in);
static String cancellor;
static int counter = 0;
static int integer = 0;
public static void main(String[] args) {
System.out.println("Guessing game! please enter a total number of guesses");
int y = input.nextInt();
int[][] GuessingGame = new int[2][];
GuessingGame[0] = new int[y];
GuessingGame[1] = new int[y];
//AI inputs
for(int i = integer; i < y; i++){
GuessingGame[1][i] = Userinput.nextInt(50);
//System.out.println(GuessingGame[1][i]);
//User inputs
System.out.println("Please enter a number within the range of 50");
cancellor = input.nextLine();
GuessingGame[0][i] = input.nextInt();
for(int j = 0; j<y; j++){
if(GuessingGame[0][integer] == GuessingGame[1][j]){
System.out.println("Correct!");
break;
counter++;
}
You cannot put anything after break statement because it break your loop. counter++ will never be reached. Use this:
counter++;
break;
instead this:
break;
counter++;
the break keyword causes your code to interrupt and exit out of the loop. Therefore everything insite of the if(GuessingGame[0][integer] == GuessingGame[1][j]) condition and after the break will not be reached. To fix this you just need to make sure that the break statement is the last thing in its block of code.

Hackerrank says my output is wrong even though the output matches perfectly [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am doing an assignment on Hackerrank for Java where I had to perform some mathematical operations with scanner data. I ran the code with two samples and I got a 100% match with the expected output (see picture) but somehow Hackerrank still says there is no match. Is it possible that you print something and it looks the same but it is recognized as something different? I already tried to write the code in a different way so the result would be picked up correctly, by using System.out.println but this was to no avail.
import java.util.*;
import java.io.*;
class Solution {
public static void main(String []argh) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String jj = "";
for (int i = 0; i < t; i++) {
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
String hh = "";
for(int k=1;k<n+1;k++){
long oo = a ;
for (double o = 0; o < k; o++) {
oo = oo + b * (long) Math.pow(2, o);
}
hh = hh + " " + oo;
}
if (i > 0) {
System.out.print("\n");
}
System.out.print(hh);
}
in.close();
}
}
image of Hackerrank result
Since there's no picture included to compare your code to output and/or expected output, I can only guess, but might be that System.out.print("\n"); is not visible in html output, but is still picked up by the validation algorythm, and if lets say 5 is expected \n5 would obviously be wrong, even if the \n whitespace part is invisible

Integer cannot be converted to boolean using "indexOf()" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to count how many times the word "ing" occurred in a string asked by a user, I'm having an error saying it cannot be converted.
I tried using s.indexOf("ing")
package javaapplication3;
import java.util.*;
public class JavaApplication3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s,q = null;
String i = "ing";
int count=0;
System.out.println("Entrer une ligne de texte :");
s = in.next();
if ( s.indexOf("ing") ){
count++;
q = s.replaceAll("ing", "ed");
}
System.out.println("\"ing\" est occuree " +count +" fois.");
System.out.println(q);
}
}
I expect the output would give me and count how many times it occurred but I'm having an error.
Use s = in.nextLine(); rather than next() to read the whole line
You need to count until the lookFor part is still in the word, each time replace the first occurence by something else, and continue using a while loop
String lookFor = "ing";
while (s.indexOf(lookFor) != -1) {
count++;
s = s.replaceFirst(lookFor, "ed");
}
same as
String lookFor = "ing";
while (s.contains(lookFor)) {
count++;
s = s.replaceFirst(lookFor, "ed");
}
You should loop over your input till your string does not have the required literal available,
int count = 0;
while (s.indexOf("ing") != -1) {
s = s.replaceFirst("ing", "");
count++;
}
System.out.print("Total occurances : "+count);

Fixing java.lang.nullpointException [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi there I am trying to create an array of records in java in which you have to enter 3 details, the name of a town, the population and the county in which is resides. Before then outputting all the data on a county which you have asked for. I was wondering if anyone could show me why a null.point.exception occurs if I enter the population of a town when does not occur when i enter another one.
import java.util.*;
public class CathedralTowns
{
public static String name;
String population;
String county;
public static int count = 0;
public static int continuation = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
while (loop1 <= 0) {
System.out.println("Please enter the name of the town. ('no' to end)");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides. ('no' to end)");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town. ('no' to end)");
String populationEntered = input.nextLine();
if (nameEntered.equals("no") || populationEntered.equals("no") || countyEntered.equals("no") ) {
loop1 = 5;
System.out.println("Thank you for entering your county.");
continuation = 1;
}
WorkingDemCathedrals(nameEntered, populationEntered, countyEntered);
}
}
public static void WorkingDemCathedrals(String nameEntered, String populationEntered, String countyEntered) {
Scanner input = new Scanner(System.in);
CathedralTowns[] allTowns = new CathedralTowns[50];
allTowns[count] = new CathedralTowns();
int loop2 = 0;
int loop3 = 0;
while (loop2 == 0){
allTowns[count].name = nameEntered;
allTowns[count].population = populationEntered; //the error relates back to here according to bluej
allTowns[count].county = countyEntered;
if (continuation == 1) {
loop2 = 1;
System.out.println("please enter the name of a county for which you wish to know the details.");
String countyOfChoice = input.nextLine();
while (loop3 > 0){
if ((allTowns[loop3].county).equals(countyOfChoice)){
System.out.println(allTowns[loop3].name);
System.out.println(allTowns[loop3].population);
loop3 = -2;
}
loop3 = loop3 +1;
}
}
count = count + 1;
}
}
}
Elements in an Object array are null by default. Initialialise the elements prior to attempting to access them
for (int i=0; i < allTowns.length; i++) {
allTowns[i] = new CathedralTowns();
}
This lines is very suspicious
allTowns[count] = new CathedralTowns();
You allocate only one object in the array while you have a line before allocated an array of the length 50.
CathedralTowns[] allTowns = new CathedralTowns[50];
Not to mention that it is prone to ArrayIndexOutOfBoundsException if count is equal or more that 50
Then you start to loop and increment count and that's where it happens!
your should loop over the entire array and allocate an object in each slot.
The NullPointerException occurs at "population" and not at "name" is because the "name" field is static, whereas the "population" is non-static.
Also the allocation of the array of CathedralTowns has to be done as per the first answer.
The while (loop2 == 0) could end up in a infinite loop. There is no end condition for this while loop, if the user wants to enter details of more than one county.

Categories

Resources