This question already has answers here:
Using charAt method, won't add them as an Int, and wont print as string. Will explain better
(4 answers)
Using charAt in System.out.println displays integer?
(5 answers)
Why does this code print the ASCII value instead of the character
(2 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm getting the user to enter a string of numbers, then a for loop should pick out each number from the string and add it to an ArrayList. I'm sure someone can help me out fairly quickly
My problem is as follows. When I print out all the values in the ArrayList, It is printing out much higher numbers e.g. 1234 = 49 50 51 52.
I think what is happening is that it is printing out the ASCII values rather than the numbers themselves. Can anyone spot where and why this is happening?
I have tried changing the int variable barcodeNumberAtI to a char, which yields the same result.
Apologies for lack of comments but this was only supposed to be a quick program
int tempNewDigit;
String barCode, ans;
int barcodeNumberAtI;
ArrayList <Integer> numbers = new ArrayList <Integer>();
public void addNumbers(){
Scanner s = new Scanner(System.in);
do{
System.out.println("Please enter a 12 digit barcode\n");
barCode = s.nextLine();
for(int i = 0; i < barCode.length(); i++){
barcodeNumberAtI = barCode.charAt(i);
System.out.println(barcodeNumberAtI);
numbers.add(barcodeNumberAtI);
}
System.out.print("Would you like to add another? y/n\n");
ans = s.nextLine();
} while (!ans.equals("n"));
}
public void displayNumbers(){
for(int i = 0; i < numbers.size(); i++){
System.out.print(numbers.get(i));
}
}
Happens at this line: barcodeNumberAtI = barCode.charAt(i);
barCode.charAt(i) returns a char which is converted to a int by using its ASCII value.
Use this instead:
barcodeNumberAtI = Character.digit(barCode.charAt(i), 10);
What Character.digit does is converting its first argument from the type char to the corresponding int in the radix specified by the second argument.
Here's a link to the documentation
Related
This question already has answers here:
Java: parse int value from a char
(9 answers)
How can I convert a char to int in Java? [duplicate]
(4 answers)
Closed 2 years ago.
I have this problem where I need to create a method that takes in a String and creates an integer array of each character. I have checked each step of the for loop and the array before and after the loop, and I am lost.
It correctly shows each character as '3' '4' and '5', however once it is inserted into the array, it always prints [51, 52, 53]. I am so lost where those numbers even came from? Thanks so much...
public class CodingBat {
public static void main(String[] args) {
String text = "345";
int[] create = new int[text.length()];
for(int i = 0; i < text.length(); i++) {
System.out.printf("Current array: %s\n", Arrays.toString(create));
//System.out.println(text.charAt(i));
create[i] = text.charAt(i);
System.out.printf("Adding %c\n", text.charAt(i));
}
System.out.println(Arrays.toString(create));
}
}
You're inserting a char into a int array, if i remember, the numbers that you see printing the array are the ASCII code.
So, if you want to get the number, use:
create[i] = Character.getNumericValue(text.charAt(i))
This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 3 years ago.
im asked to write a program that removes duplicate letters from a string
**note: uppercase and lowercase letters are considered duplicates.
I wrote the code and it's working for all inputs without spacebars, when an string is given with spaces, it show errors.
i have to use loops and arrays only, no extra functions or hashs,
this is my code that ALMOST works:
case 2:
System.out.println("Give the string input");
String original=reader.next();
char[] charts=original.toCharArray();
int length=charts.length;
for (int i=0; i<length; i++){
for (int j=i+1; j<length; j++){
if(charts[i]==charts[j]||charts[i]+32==charts[j] ||charts[i]-32==charts[j]){
int temp=j; //duplicate element index
for (int k=temp; k<length-1; k++){ //delete shifting elements to left.
charts[k]=charts[k+1];
}//inner inner for
j--;
length--; // reduce char array length because we removed a character
}//if
}//inner for
}//for
String CleanString= new String(charts); //new string without repeated chars
CleanString=CleanString.substring(0,length); //set its length
System.out.println("New str = "+CleanString);
break;
I recommend you to use Scanner's method nextLine() to read string with spaces and process it with your algorithm
Scanner scanner = new Scanner(System.in);
String original = scanner.nextLine();
By the way, if you cannot use regular expressions, you maybe want to use count sort-based approach. Create an array of size equal to maximum size of char. Iterate over string and increment an array element of index X when you meet character value 'X'. Add X to your array of chars. When you meet array[X] >= 1, do not add X to array.
Your code will work fine. Just use this code at third line:
String original="";
original+=reader.nextLine();
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have a String like the following 2 4 12 12 yellow Hi how are you
I want to split the string like this {2,2,12,12,yellow, Hi how are you} in order to pass the items in the list as parameters in a constructor.
Any help?
The trivial answer is to split the string:
String[] fragments = theString.split(" ", 6);
Given that the fragments have specific meanings (and presumably you want some of them as non-string types), it might be more readable to use a Scanner:
Scanner sc = new Scanner(theString);
int x = sc.nextInt();
int y = sc.nextInt();
int width = sc.nextInt();
int height = sc.nextInt();
String color = sc.next();
String message = sc.nextLine();
This approach is also easier if you are reading these strings, say, from a file or standard input: just create the Scanner over the FileReader/InputStream instead.
I have a program that asks the user for an input which is an int(using a scanner).
I only want the program to take in 7 digits.
If the input is not 7 digits I want to truncate it to 7 digits.
So if the number were 12345678 I would want it to be 1234567.
Currently I am storing the input in an array like the following:
for(int i = 0; i > 7; i++)
{
numbers[i] = input1 % 10;
input1 /= 10;
System.out.print(numbers[i]);
//stores the numbers backwards so if input was 123, first element would be 3, 2, 1
}
so that's when I run into the problem if I enter 12345678, it will store it as 8765432. I want it to store as 7654321 instead.
If anyone has any suggestions on my loop making the number store as 1234567 or 7654321, it would be quite helpful :)
An easier way can be to save the input into a String
Then check if length>7, if yes keep the 7 first character, if no, do nothing ;)
String input1 = sc.nextLine();
if(input1.length>7){
input1 = input1.substring(0,7);
}
int input = Integer.valueOf(input1);
It's clearly easier than storing each digit individually or iterate over the input ;)
Edit with '?' ('?' definition and explication)
String input1 = sc.nextLine();
int input = Integer.valueOf(((input1.length>7) ? input1.substring(0,7) : input1);
This allows to not change the value of input1 this will stay the original input
Well, there are several things.
First of all, I think it'd be better for you to use ArrayList and work on Integers, rather than primitive types such as int. If you use ArrayList, then you can simply do .add(Integer e) to put next Integer into your list.
Next thing, your loop should be:
for(int i = 0; i < 7; i++) instead of for(int i = 0; i > 7; i++). See the difference? If you are using i++, then you limit your loop with a <, not >.
As for reversing the input, it's pretty simple, use i-- instead, but I think you can figure this out yourself.
public static void trauncateNumber(int input1) {
String Str=Integer.toString(input1);
//int changeValue=0;
if(Str.length()>7){
//Str=Integer.toString(input1);
Str=Str.substring(0, 7);
input1=Integer.parseInt(Str);
}
//int changeValue=
System.out.println(input1);
}
This question already has answers here:
Java calculator not executing if-statement [duplicate]
(3 answers)
Closed 9 years ago.
In the code below, in the first iteration of the first for loop, boxes[a] is automatically assigned a null value.
The remainder of the iterations are fine (user input is accepted). Only the first has the issue where a null value is automatically assigned.
Does anyone know why this may be? Thank you.
package testing;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
int boxNumber;
boxNumber = in.nextInt();
String[] boxes = new String[boxNumber];
System.out.println(boxNumber);
for(int a=0; a <= boxes.length - 1; a++){
boxes[a] = in.nextLine();
System.out.println(boxes[a]);
}
int packageNumber;
packageNumber = in2.nextInt();
String[] packages = new String[packageNumber];
System.out.println(packageNumber);
for(int n=0; n <= packageNumber - 1; n++){
packages[n] = in.nextLine();
System.out.println(packages[n]);
}
}
}
The scenario fitting the description of what occurs is when you type in a number on the first line, then the rest of the lines are strings for the boxes.
But the nextInt() method doesn't advance past the first newline character, so the first time you call nextLine(), it matches on the rest of the line until the first newline character, "" ( not null).
After the call to nextInt(), insert a call to newLine() before the for loop to bypass the first newline character.
String firstNewLine = in.nextLine();
for(int a=0; a <= boxes.length - 1; a++){
when you did hit enter after entring the first number you also have and empty line that's why nextLine() return empty string, you can use this boxNumber = in2.nextInt(); instead but I would suggest to think of another way, normally you don't need two Scanner instances