Adding spaces between operation marks [duplicate] - java

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed last month.
Whats the difference between these two operations?
I imagined:
length - 1
to be the same as
length-1
but I am getting an error with length when using the latter
using operation here: for (int i = length - 1; i >= 0; i--)
int length = Integer.parseInt(scan.nextLine());
Edit: ENTIRE CODE:
import java.util.Scanner;
import java.util.Arrays;
public class continuousmedian
{
public static void main(String args[])
{
Scanner scan = new Scanner (System.in);
int cases = Integer.parseInt(scan.nextLine());
for (int set = 0; set < cases; set++)
{
int length = Integer.parseInt(scan.nextLine()), med = 0;
String[] copy = (scan.nextLine()).split(" ");
int[] test = new int[length];
for (int i = length-1; i >= 0; i--)
{
test [i] = Integer.parseInt(copy[i]);
//System.out.println("4 is " + test[4]);
Arrays.sort(test);
//*
System.out.print(">>");
for (int a = 0; a < length; a++)
System.out.print(test [a]);
System.out.println();
//*/
//System.out.println(i);
int mid = length - 1 - i;
if (i%2 == 0)
med += test[mid];
else
med += Math.floor((test[mid] + test[mid+1])/2);
//System.out.println("TEST AT " + mid + " is " + test[mid]);
}
System.out.println(med);
}
}
}
input case:
2
6
1 3 6 2 7 8
7
1 3 6 2 7 8 5
and finally, the error message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1 3 6 2 7 8"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:784)
at continuousmedian.main(continuousmedian.java:13)
For those of you saying that it is trying to parse a line of input:
The ONLY thing I changed is length-1 -> length - 1

"They are the same. Coding conventions say to use spaces, but the semantics are the same." - Ole
This was correct. Turns out, it didn't matter which of the formats I chose. In the end, it was completely 50/50 when running the program whether it worked or not. I ran the program a few times, copy pasting the same input into the same program. Sometimes it worked, sometimes it didn't. Maybe something with my computer clock or something, Idk but thanks for the help anyways.

This line is your problem:
int length = Integer.parseInt(scan.nextLine()), med = 0;
If the input line is "1 3 6 2 7 8", then you attempt to parse that line as an integer, which it manifestly is not. An exception is thrown indicating you're applying parseInt to invalid data.
We can tell this with absolute certainty - the exception message says so. You were trying to apply parseInt to the string "1 3 6 2 7 8". This is not in doubt.
It looks like that particular line of input was intended for the next line of code, which will split it on spaces, but in fact you never get there because of the previous error.
Given your statement that the input was supposed to be
2
6
1 3 6 2 7 8
7
1 3 6 2 7 8 5
then it looks like you didn't actually type one of the "2" or the "6".

Related

Index n out of bounds for length n Exception. I am trying to try to remove duplicates from an array to make a new array then display it [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
Expected output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Here are the distinct numbers 1 2 3 4 5
output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 5
out of bounds for length 5
at Main.main(Main.java:26)
/*
Johnny Santamaria
CS 111B Assignment 5 - deDup
This program gives you instructions to remove duplicate numbers in an array
*/
class Main {
public static void main(String[] args) {
int[] numArray;
int index = 0;
int num;
if (args == null || args.length < 1) {
System.out.println("Usage: java Main 1 2 3 4 5 5 to remove duplicates from the numbers 1 2 3 4 5 5");
return; //exit function
}
//finds integers in command line
index = args.length;
numArray = new int[index];
//convert to integers to actually make the array
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[index] = num;
index++;
}
int uniqueIndex = deDup(numArray, index);
}
public static int deDup(int[] numArray, int index) {
if (index == 0 || index == 1) {
return index;
}
//creates new index to store unique numbers
int uniqueIndex = 0;
//checks each number in the array to remove duplicates to make a new index
for (int i = 0; i < index - 1; i++) {
//deletes a number in the index of the array then reformats them
if (numArray[i] != numArray[i + 1]) {
numArray[uniqueIndex++] = numArray[i];
}
}
numArray[uniqueIndex++] = numArray[index - 1];
System.out.println("Here are the distinct numbers: " + numArray[uniqueIndex]);
return uniqueIndex;
}
}
The exception message indicates that you are trying to access an index that does not exist:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5 at Main.main(Main.java:26)
Illegal access occurs on this line:
numArray[index] = num;
The reason is that in numArray there is no index with the value of the index variable.
PS: note that on line 19 you assign the length of args to the variable index.
The problem is that you define these values:
index = args.length;
numArray = new int[index];
and then in the first loop iteration you access
numArray[index] = num;
which is not a valid index since it is too big by 1.
The real problem here is that you are using index as a running variable in your loop, but it is not set to the starting value of 0. You are using the same variable for two different purposes.
Either
set index = 0; before the loop or
use a different variable in your loop, such as i:
int i = 0;
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[i++] = num;
}

what is the best algorithm to solve this programming challenge ? Given a positive integer number consisting only of digits 6 and 9 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Traverse from left to right and change the first occurrence of 6 to 9. If there is not any 6 while traversal then does not change any digit.
Following code may help:-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class testing {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int a=sc.nextInt();
String numberString = Integer.toString(a);
for (int i = 0; i < numberString.length(); i++){
char c = numberString.charAt(i);
if(c=='6') { // check if the digit is 6 or not, if 6 is present then change it to 9
numberString = numberString.substring(0, i) + '9' + numberString.substring(i + 1);
break; // break the loop if 6 is changed to 9
}
}
System.out.println("Largest Number is : "+numberString);
}
}
public class Maximum69 {
public static void main(String[] args) {
int num=6669;
int added = 0;
int cur = 1;
int curNum = num;
while(curNum > 0) {
if(curNum % 10 == 6)
added = cur;
cur *= 10;
curNum = curNum / 10;
}
System.out.println(num + added * 3);
}
}
I found out how to slove, This takes less time to run:
I have found a formule, it could have been a single line solution but for clarity I have divided in two lines
First , get the highest number based on input number of digits , for example if input is 6, topNumber will be 9, for 69 top will be 99 , for 696 top is 999, so topNumber can be 9 or 99 or 999 or 9999 or 99999,etc up to java limit, the formula to get number of digits in an integer is :
floor(log10(input)) + 1
Then you can notice that the top number minus the input, it gives you a number that starts with 3, for example 9-6 = 3 , 99 - 69 = 30 , 999 - 696 = 303, except when the input is equal to the top number, in that case the result is 0,
knowing that fact, we can conclude that for switching the first 6 in the number can be achieved by summing up 3 * (((the position of the 6) -1) * 10) , eg. 3 or 30 or 300 or 3000 or 30000, etc.
resulting in the last part of the function : input + (10^(NumberOfDigits(top - input)) -1) * 3
private static int largest69(int number) {
int topNumber = (int) (Math.pow(10,(int)(Math.log10(number)) + 1) -1);
return number + (int) Math.pow(10,(( (int)(Math.log10(topNumber - number)) + 1 ) -1) ) * 3;
}
If you're not as good as nitinsridar at intuitively implementing math into your algorithm, and if you don't want to mess around with strings like backdoor did, then you can utilize data structures to help you come to a solution without much thought
public static void main(String[] args) {
System.out.println(maxNumber(9669));
}
public static int maxNumber(int number) {
Stack<Integer> numbers = new Stack<Integer>();
int numberLength = 0;
while(number > 0) {
numbers.push(number % 10);
number /= 10;
numberLength++;
}
boolean changedFirstOccurrence = false;
int maxNumber = 0;
for(int i = numberLength; i > 0; i--) {
int numberToAdd = numbers.pop();
if (numberToAdd == 6 && !changedFirstOccurrence) {
numberToAdd = 9;
changedFirstOccurrence = true;
}
maxNumber += numberToAdd * (int) Math.pow(10, i);
}
return maxNumber / 10;
}
Is this the best solution? Nope, I would go with nitinsridar's answer (I also believe that his/her answer should get the green checkmark).
Backdoor's answer is definitely how I would've solved this problem before I took my data structures and algorithms class. I'm not saying it's a bad answer. In fact, his algorithm is more concise than mine. It's just my opinion that you don't want to get in the habit of relying on string manipulation to solve these sort of "numerical" problems, because one day it's not going to work; in this case, it did. I'm just providing another way of doing it

"while" loop not iterating correctly

I am supposed to print the following output by using loops:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
The highest number in this pattern (in this example, 7) is determined by user input. Here is the applicable code for the pattern:
index=patternLength+1; n=1; //These values are all previously intitialized
while (index!=1) {
index--;
printSpaces((index*2)-2); //A static method that prints a certain number of spaces
while(n!=1) {
n--;
System.out.print(n + " ");
}
System.out.print("\n");
n=patternLength+1-index;
}
And here is the incorrect output for the user input "7":
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
There are two blank lines preceding the incorrect output; these lines have the correct number of spaces necessary for the complete/correct pattern, but for some reason, the actual numbers start printing too "late" in the loop. In other words, the spaces that appear before the "1, 2 1" in the correct example are in the incorrect output. It's some of the numbers that are missing and make the incorrect example incorrect.
OK, I got it.
index=patternLength+1; n=1;int nSetter=1;
//Loop C
System.out.println("Pattern C:");
while (index!=1) {
index--;
printSpaces((index*2)-2);
while(n!=0) {
System.out.print(n + " ");
n--;
}
System.out.print("\n");
nSetter++;
n = nSetter;
}
My problem was that my "n" needed to go both up and down, so the extra variable "nSetter" seems to have solved that, although this may be a round-about solution. Whatever. Thanks to #Andreas for pointing me in the correct direction and #JohnKugelman for the helpful edit.
Please try this code your second while loop is not correct.
int index = patternLength + 1;
int n = 2; //These values are all previously intitialized
int i = 1;
while (index != 1) {
index--;
printSpaces((index * 2) - 2); //A static method that prints a certain number of spaces
while (n != 1) {
n--;
System.out.print(n + " ");
}
System.out.print("\n");
i++;
n = i+1;
}

Creating a sliding number puzzle board using arrays in Java

So I'm kind of new to Java and decided to create a sliding number puzzle of some sort. Here's what I have :
int[] puz = {1,2,3,
4,5,6,
7,8,9}
for(int i=0; i<puz.length; i++){
System.out.println(puz[i]);
}
The 1 is supposed to be the blank spot but I'll figure that out later. My problem is that the code prints:
1
2
3
4
5
6
7
8
9
when I want it to print:
1 2 3
4 5 6
7 8 9
I've also tried doing a nested loop that I'm too embarrassed to show on here due to how hideous it was.
Would I try using a 2d array instead?
I guess you could try...
int puz = {1,2,3,4,5,6,7,8,9};
int n = Math.ceil(Math.sqrt(puz.length));
for (int i = 0; i < puz.length; i++) {
System.out.print(puz[i] + ((i + 1) % n == 0 ? "\r\n" : " ");
}
Try creating a variable counter and increment it every time you iterate through the loop. Using a modulus operator, divide it by 3 and when remainder is 0, create a new line.
int puz = {1,2,3,4,5,6,7,8,9};
int counter = 1;
for(int i=0; i<puz.length; i++){
System.out.print(puz[i]);
if (counter % 3 == 0){
System.out.println("");
}
counter++;
}
The trick here is to use the modulus operator. This operator divides one number by another, and returns the remainder. In java (and everywhere else as far as I know), % is the modulus operator. If you want every third number to have a line break after it, simply divide by three using modulus division, like so:
int[] puz = {1,2,3,4,5,6,7,8,9};
//For what it's worth, you don't have this semicolon in your question, so I added it in.
for(int i=0; i<puz.length; i++){
System.out.print(puz[i] + " ");
if(i % 3 == 2){//It's equal to 2 because you start at 0 and not 1.
System.out.println("");
}
}
This code, when executed, prints the following, which is what you wanted:
1 2 3
4 5 6
7 8 9

How to fix this exception in Java?

My code is like this
import java.io.File;
import java.util.Scanner;
public class ReadFile{
public static void main(String[] args)throws Exception {
Scanner scan = new Scanner(new File("input.txt"));
int[][] arr = new int[4][4];
for(int t = 1; t <= 2; t++){
int firstRow = scan.nextInt();
System.out.println(firstRow);
for(int i = 0; i <= 4; i++){
if(scan.hasNextLine()){
String[] splited = scan.nextLine().split("\\s");
for(String f : splited)
System.out.println(f);
for(int g = 0; g <= 4; g++){
arr[i][g] = Integer.parseInt(splited[i]); // at this point the exception is being thrown
}
}
}
}
}
Through which I am trying to read a file having data arranged in following format
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 5 4
3 11 6 15
9 10 7 12
13 14 8 16
Basically I want to read the first number 2 (single value in a line) and 3(again a single value in line 6th from top) and store them in firstRowNum variable and secondNumRow variable and the rest of the numbers in two 4X4 matrices.
But when I am running the code I am getting the following exception
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at ReadFile.main(ReadFile.java:20)
I think I am not setting the loops correctly.
Thanks
Replace
splited[i]
with
f
as the argument to Integer.parseInt(). Also, don't use another loop for the g index; use
arr[i][g++]
and initialize g to 0 before the inner for each loop. Alternatively, use the g-based loop as it is, but replace splited[i] with splited[g].
You have other issues as well, such as using
i <= 4
as the upper bound condition of the loop, but your array's indices range from 0 to 3 (i < 4 should be used).
You can check if the String is empty before the conversion to Integer, using the function String.isEmpty()

Categories

Resources