How to convert a char array to an int array? - java

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).
(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)
What should I do?
import java.util.Scanner;
public class stringHundredDigitArray {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
String num1 = in.nextLine();
char[] num1CharArray = num1.toCharArray();
//for (int i = 0; i < num1CharArray.length; i++){
//System.out.print(" "+num1CharArray[i]);
//}
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = num1CharArray[i];
}
for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
System.out.print(" "+num1intarray[i]);
}
}
}
I really have to split the string, to preferably an array of additionable data types.

try Character.getNumericValue(char); this:
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}

Try This :
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++)
{
num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
System.out.print(num1intarray[i]);
}

Short and simple solution!
int[] result = new int[charArray.length];
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));

Related

Using an array to input strings, and another one to output word frequency

So I am trying to complete this code. The goal is to input an array of strings, then count the frequency of how often the words are found. For example:
input:
joe
jim
jack
jim
joe
output:
joe 2
jim 2
jack 1
jim 2
joe 2
An array must be chosen for Strings, and another array much be chosen for word frequency.
My code so far:
I am stuck into trying to implement this. The string method is set, but how am I going to count the frequency of words, and also assign those values to an array. Then print both side by side. I do know that once the integer array is set. We can simply do a for loop to print the values together such as. System.out.println(String[i] + " " + countarray[i]);
public class LabClass {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int freq = 0;
for (int i = 0; i < listSize; i++) {
if (wordsList[i].compareTo(currWord) == 0) {
freq++;
}
}
return freq;
}
public static void main(String[] args) {
LabClass scall = new LabClass();
Scanner scnr = new Scanner(System.in);
// assignments
int listSize = 0;
System.out.println("Enter list Amount");
listSize = scnr.nextInt();
// removing line to allow input of integer
int size = listSize; // array length
// end of assignments
String[] wordsList = new String[size]; // string array
for (int i = 0; i < wordsList.length; i++) { //gathers string input
wordsList[i] = scnr.nextLine();
}
for (int i = 0; i < listSize; i++) {
String currWord = wordsList[i];
int freqCount = getFrequencyOfWord(wordsList, listSize, currWord);
System.out.println(currWord + " " + freqCount);
}
}
}
int some_method(String[] arr, String word) {
int count = 0;
for (int i=0; i<arr.size(); i++) {
if (arr[i].equals(word)) count++;
}
return count;
}
Then in main method:
String[] array = ["joe", "jake", "jim", "joe"] //or take from user input
int[] countArray = new int[array.size()]
for (int i=0; i<array.size(); i++) {
countArray[i] = some_method(array, array[i])
}
System.out.println(array[0] + " " + countArray[0]);
Ouput:
joe 2

Problems with iterated nextLine function

I am trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);

Why does my method that I am trying to call to inside main not work?

minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}

Filling a 2d character array from a file in java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

use of parseInt

I want to use parseInt() method, but I don't now how to put array a
my code:
import java.util.Scanner;
public class StaticMethodsWrapper {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = input.nextInt();
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
int x = Integer.parseInt(a);//here is the error
}
}
parseInt(a) expects String type parameter for a. But you are providing it with int[] parameter. It is an array not a string.
If you want to concatenate all numbers use this code when you have your a array populated:
StringBuilder sb = new StringBuilder();
for (int oneInt:a) {
sb.append(oneInt);
}
System.out.println(sb.toString);
And later you can parse this composed string to int or long variable type via parseInt of Integer class or parseLong of Long class. Like that:
long myLong = Long.parseInt(sb.toString());

Categories

Resources