I am trying to create a program that displays the x and y coordinates of any given point, reflected across the linear function ax+b. However, I get a runtime error which says that it's out of bounds. I know you can't invoke methods on primitive data types, but I have no idea how else to get it.
import java.util.*;
public class ReflectivePoint {
public static void main (String[]args){
Scanner lol = new Scanner(System.in);
System.out.println("Please enter the linear function.");
//That will be in the format ax+b
String function = lol.nextLine();
Scanner lol2 = new Scanner(System.in);
System.out.println("Please enter the point.");
//That will be in the format a,b
String point = lol2.nextLine();
int a = point.charAt(1);
int b = point.charAt(3);
int m = function.charAt(1);
int c = function.charAt(4);
int x1 = (2 / (m + 1 / m)) * (c + b - a / m) - a;
int y1 = (-1/m) * x1 + a / m + b;
System.out.println(x1+", "+y1);
}
}
Perhaps you are getting a String of length 3, eg "1,2".
charAt(3) will try and return the 4th char of the String which doesn't exists so it throws an StringIndexOutOfBoundsException.
The index out of bounds error means "You have asked me for the 4th character of this string, but the string has fewer than 4 characters."
Note that (like most computer language indexes), the first character is 0. charAt("hello",1) == 'e'
You should check the length of the string before calling charAt(). Or, catch the exception and handle it.
charAt() probably isn't the best choice for your program, because it will only currently handle single-digits. Try String.split() to split the String on the comma.
Also, at the moment it's using the ASCII value of the character. That is (if you fixed the indexes) "a,b" would result in you doing your maths with m=97 and c=98. I guess that's not what you want. Find out about Integer.parseInt()
Aside from the out of bounds issue, which others have pointed out is you need to start at charAt(0) because the number is an offset into the char array (string), not getting the nth element.
You also need to subtract '0' to convert to an integer.
string point = "4";
int a = point.charAt(0);
//a=52 //not what you wanted
string point = "4";
int a = point.charAt(0) - '0';
//a=4 //this is what you wanted
You can use:
int a = point.charAt(0);
provided that that point is not empty.
Ideally you should perform a pre-use length check on the input String.
Related
This is my program and what I am trying to achieve is taking the char value in string amount1 at position 1 i.e for example amount1=$3.00 amount2=2. However it doesn't print out what I expected, 2.
System.out.print("$"+cost[0]+".00 remains to be paid. Enter coin or note: ");
String amount1 = keyboard.nextLine();
char amount2 = amount1.charAt(1);
String amountcheck = "$"+cost[0]+".00";
int [] remainder = new int[1];
if (amount1.equals(amountcheck)) {
System.out.println("Perfect! No change given."); }
if (amount2 < cost[0]) {
remainder[0] = cost[0] - amount2; }
System.out.println("Remainder = "+remainder[0]);
System.out.println(+amount2);
For example,
$3.00 remains to be paid. Enter coin or note: $2.00
Remainder = 0
50
The problem is both in lines 2 and 3. Firstly 3, It don't understand why it outputs 50 as char at amount1 index 1. If i'm not wrong don't char positions work similarly off array index systems. Secondly line 3, the if statement in lines of 8 and 9 of my original code don't seem to catch that amount 2 < cost[0] and don't do the following operations.
So what I expected to happen when I am taking char at position 1 of "$2.00" is newamount would be equal to 2 instead of 50 which the program is outputting.
I've tried changing the char positions but all this seems to do is decrement the value.
You set your amount2 as a char and when you print it, it translates to the ASCII number of that charater which for the charater '2' is 50.
If you want to output 2 you should change your amount2 to type intand parse the char to integer like this Integer.parseInt(""+amount1.charAt(1)); in line 3.
You are using a char to store a numeric value, but that value is a character, not a number. Meaning you are storing '2' which is actually 50 in ASCII. You should remove the value of 48 to get the correct value ('0') or parse the String into a number directly with Integer.parseInt(String).
But as I said in comment, this is easy to correct so I will not provide much more code to this.
But let's be honnest, your logic is risky from the beginning.
You are asking the user to input an amount in a specific format : "$#.00". If the number is two digit $##.00 it fails, if he add a space or don't put the $ or any mistake that users are professional to find, it fails.
First, you should simplified this, do you need the $ ? Ask for dollar currency if you want to specifiy it.
Then, do you need decimals ? Let first assume you don't (see Note for decimal hint).
You just need to input an integer value through the Scanner, which provide method to get Integer -> Scanner.nextInt()
int ammountReceived = keyboard.nextInt();
Then you need to see if this is
Equals
Too much
Not enough
Like this :
int remainder = amountToPay - amountReceived;
if(remainder == 0){
//equals
} else if(remainder > 0){
//not enough
} else {
//too much
}
This would give a simpler solution of :
Scanner sc = new Scanner(System.in);
System.out.print("Amount to pay : $");
int amountToPay = sc.nextInt();
System.out.print("Amount received : $");
int amountReceived = sc.nextInt();
int remainder = amountToPay - amountReceived;
if (remainder == 0) {
System.out.println("That perfect, thanks.");
} else if (remainder > 0) {
System.out.println("Remaining : $" + remainder);
} else {
System.out.println("Need to give back : $" + -remainder);
}
sc.close();
Yours and mine are close, but you will see this is more readable and focused on the problem, I don't play with char to get from a specific String pattern, I am focused on the problem -> to get paid ;)
Now, you have to add a loop here to ask again until you received the correct amount. But please, don't read a numerical String character by character...
Note :
Scanner.nextInt throws exception if the format is incorrect (not an integer)
You can easily adapt this to get double, float or better BigDecimal
This is part of a longer coding challenge - one part involves "flipping" the digits of an input number (i.e. 1234 becomes 4321) and removing leading zeros as applicable.
Below, I have written the method flipOpp that accomplishes this. Most of the time, it works perfectly. But sometimes, I'm getting an error because the last digit becomes a dash ("-") and obviously, the Integer.parseInt() method won't work if one of the digits is a dash!
Any ideas what might be causing this? Also, is there an easier way to flip the digits of an int? The method I'm using right now doesn't seem very efficient - turning an int to a String, then to a character array, manipulating the characters of this array, turning it back into a String, and finally back to an int.
Thanks! Code for this method is below:
// third operation: reverse the digits and remove leading zeros
public static int flipOpp(int num){
char temp;
// change int to a String
String stringNum = Integer.toString(num);
// change String to a char array of digits
char[] charNum = stringNum.toCharArray();
// flip each character and store using a char temp variable
for (int i=0;i<charNum.length/2;i++){
temp = charNum[i];
charNum[i]=charNum[charNum.length-i-1];
charNum[charNum.length-i-1]=temp;
}
// turn flipped char array back to String, then to an int
// this process removes leading zeros by default
String flipString = new String(charNum);
if (flipString.length()<7){
int flipInt = Integer.parseInt(flipString);
return flipInt;
}
else return 0;
}
Any ideas what might be causing this?
Definitely sounds like negative numbers
is there an easier way to flip the digits of an int? The method I'm using right now doesn't seem very efficient
Keep it as an integer. Don't worry about the negative
public static int flipOpp(int num) {
int reversed = 0;
while (num!=0) {
reversed = reversed*10 + num%10;
num /= 10;
}
return reversed;
}
For example, -50,
0*10+0=0
-50/10=-5
- -
0*10+(-5)=-5
-5/10=0
- -
END, output -5
This is the actual question:
Write an interactive program that adds two integers of up to 50 digits each
(Represents integer as an array of digits).
This is a homework question and the language to be used is Java. I got this far but I don't think it is even close.
1. It is not taking input more than 20 digits but have to work with 50 digits.
2. The method 'integerToDigits' is producing two arrays but i am unable to sort out how to use them and add them in the main method.
Help please.
package One;
import java.util.Scanner;
public class AddInt {
public static void main(String[] args) {
Long x,y;
Long a[] = new Long[50];
Long b[] = new Long[50];
System.out.println("Please enter two numbers which have no more than 50 digits: ");
Scanner s = new Scanner(System.in);
x = s.nextLong();
y = s.nextLong();
System.out.println(x+ "and "+y);
integerToDigits(x);
integerToDigits(y);
}
public static Long[] integerToDigits(Long n){
Long digits[] = new Long[50];
Long temp = n;
for(int i = 0; i < 50; i++){
digits[49-i] = temp % 10;
temp /= 10;
}
return digits;
}
}
It is not taking input more than 20 digits but have to work with 50 digits.
This is because you're using x = s.nextLong() which is trying to convert the input to a long. The maximum long value is 9223372036854775807 which is nowhere near 50 digits. You'll need to get the input as a String and then covert that to your int[]
The method 'integerToDigits' is producing two arrays, but I am unable to sort out how to use them and add them in the main method.
In terms of adding up the arrays of digits, you can use the same process we learn very early on in school.
Add the units, then carry over any tens.
Add the tens and carry over any hundreds.
Add the hundreds and carry over any thousands.
...
This process can be iterated adding each order of magnitude with the carry over from the previous one.
Hopefully those tips give you a way to solve your problem.
If you do want a solution, I've produced one here that seems to work as you require. (Although not in ideone apparently)
If "Represents integer as an array of digits" is a suggestion and not a requirement a solution using BigInteger would look something like:
// read numbers from input
// store first value as String "firstNumber"
// store second value as String "secondNumber"
BigInteger a = new BigInteger(firstNumber);
BigInteger b = new BigInteger(secondNumber);
BigInteger result = a.add(b);
System.out.println("Result is " + result.toString());
If "Represents integer as an array of digits" is a requirement, well, then it's a silly assignment :) No one would store an integer like that. Worst case, I'd store it as a String if BigInteger was not allowed.
here i have a problem. i want a user to input some numbers, then i will convert the input into a string,i will then count the length of the string, and if it is less than 8,i want to add more zeros to the input to make it 8 so that i can do some staff with the number. i have tried to use decimalformat but its not working. plz help.
thanks in advance
int s=Integer.parseInt(s1.readLine());
String news=String.valueOf(s);
if(news.length()<8){
DecimalFormat myformat=new DecimalFormat("00000000");
String out= myformat.format(s);
int onth=(Integer.valueOf(out)).intValue();
s=onth;
}else{
System.out.format("your number is: %d\n",s);
Forget about using the DecimalFormat.
Change your format to the following
System.out.format("your number is: %08d\n",s)
The %08d will lead with zeros, to a width of 8.
This will only display the number in the format you've requested. As stated elsewhere in this thread, treating it as a number would remove the leading zeros.
If you want to store it in a String variable however, you can use
String intString = String.format("%08d", s);
to store it.
Update *
As you have a specific need to get a series of numbers between a substring
the following code will do what you want.
private static int getSubNumber(int startIndex, int stopIndex, int number) {
String num = String.format("%08d", number);
return Integer.parseInt(num.substring(startIndex, stopIndex));
}
If you pass in the number you want to convert, it will change it to a string, and then convert the substring between the two indexes you pass in back into a number
System.out.println(getSubNumber(2,5,12345678)); // = 345
System.out.println(getSubNumber(2,5,12345)); // = 12
System.out.println(getSubNumber(2,5,123)); // = 0
This is non inclusive, getSubNumber(2,5,...) gets values at position 2,3 and 4 NOT 5.
For your example of 144, use start index 2, stop index 6 for positions 2, 3, 4 and 5
System.out.println(getSubNumber(2,6,144)); // = 1
DecimalFormat is to format numbers in the way we give the pattern.
And to append zeros, please follow this:
Add leading zeroes to a string
If you need to add 0 after the value, you can multiply it by 10 pow the number of missing 0:
int result = Integer.parseInt(news);
if(news.length()<8){
int diff = 8 - news.length();
result = result * Math.pow(10, diff); // ==> result = result * 10^(8 - news.length())
}
I think that's the simpliest way to do that.
Edit Ahhh, yes... There is prefix in the question. Nevermind!
Even if you prefix an int with zeros the actual value will change to the original value. If you want padding you'll have to go with string. The out variable will give you the result.
Update based on comment
import java.util.Scanner;
public class SquareSubString {
public static void main(String[] args) {
String userInputSquare = getSquaredInput();
int digits2to5 = Integer.parseInt(userInputSquare.substring(2, 6));
System.out.println("Squre of digits 2 to 5 is : " + (digits2to5 * digits2to5));
}
private static String getSquaredInput() {
System.out.println("Enter a number : ");
Scanner in = new Scanner(System.in);
int input = in.nextInt();
in.close();
return String.format("%08d", (input * input));
}
}
An aromatic number is of the form AR, where each A is an Arabic digit, and each
R is a Roman numeral.
Each pair AR contributes a value described below, and by adding or
subtracting these values together we get the value of the entire aromatic number.
An Arabic digit A can be 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9. A Roman numeral R is one of the seven letters I, V, X, L, C, D, or M. Each Roman numeral has a base value:
This program is designed to take a AR value on the same line (inputted like e.g. 3V), and multiply it. 3V would be 3 x 5 = 15. Since V is 5.
My issue is that I cannot take what the user inputs and multiply an integer by a string. This makes it tedious. I tried converting the string into a int but the program gives me a nullformatException.
Also A would be in the first cell [0] and R (the numeral) in cell [1]
import java.io.*;
import java.util.*;
import java.text.*;
public class AromaticNumerals
{
public static int decode (String x) // since input is direct the program doesnt require validation
{
if (x.equals ("I"))
return 1;
else if (x.equals ("V"))
return 5;
else if (x.equals ("X"))
return 10;
else if (x.equals ("L"))
return 50;
else if (x.equals ("C"))
return 100;
else if (x.equals ("D"))
return 500;
else
return 1000;
}
public static void main (String str[])
throws IOException
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
int Output;
int MAX = 20;
String[] x = new String [MAX]; // by picking an array we can separate the A-R
System.out.println ("Please input an aromatic number. (AR)");
x [0] = (stdin.readLine ());
int y = Integer.parseInt (x [0]);
Output = ( y * decode (x [1]));
System.out.println (Output);
}
}
int MAX = 20;
String[] x = new String [MAX]; // by picking an array we can separate the A-R
Incorrect. All of your input is going into the first element of the array, x[0]. You are confusing an array of strings with an array of characters. The simplest solution is to eliminate the String[] and use a plain String, then extract the individual characters with charAt() or substring().
stdin.readLine() is going to grab all the characters from the console and store them in the string found at x[0]. You're then attempting to parse an integer from the full string, not just the first character, this is why your call to parseInt is failing. Instead, call parseInt on the first character via parseInt(x[0].substring(0,1)) and pass the second character of the string to the decode method via decode(x[0].substring(1,2)). Also, if you don't need an array of strings, don't use one.
Did you by chance come from a C background? Or any other languages where string is a pointer to the first element of an array of characters? Java works differently in that respect, a Java string is first class object so x [0] = (stdin.readLine ()); reads the whole line into the first string so int y = Integer.parseInt (x [0]); will try to parse both A and R. Instead you want perhaps x[0].charAt(0) and x[0].charAt(1), also you don't need x to be an array.
Why you're getting errors:
When you read the user input here
x [0] = (stdin.readLine ());
... you are reading the whole aromatic number e.g. 4V or whatever, and you are putting it in the first index of your array x. Then,
int y = Integer.parseInt (x [0]);
Here you try to parse the first element of x as an integer. But you didn't just put the integer part of the aromatic number there, you put the whole thing. You'll get a NumberFormatException there, because the Integer class can't parse the letter character you're passing it along with the number. Then,
Output = ( y * decode (x [1]));
... you try to pass the second element of x to the decode method, but there's nothing there, because you put the entire string in x[0]. That's your NullFormatException, because x[1] is null.
To fix it:
String line = stdin.readLine();
int y = Integer.parseInt(line.charAt(0));
int output = y * decode(line.charAt(1));
or whatever.