readCharArray() Method is not working - java

I have a problem with a method which i want to use to read a complete line of characters.
First of all i'm using the following package for my method:
package chararray;
import java.util.*;
import java.util.regex.*;
import java.text.*;
public class Console
{
private static Scanner sc;
private Console()
{
}
public static char[] readCharArray()
throws NoSuchElementException, IllegalStateException
{
sc = new Scanner(System.in);
String text = sc.nextLine();
return text.toCharArray();
}
}
And that's the main code where i include the package. My compiler (BlueJ) is telling me: "incompatible types - found char[] but expected char". But normally my method should work for char[]? Any suggestions what i'm doing wrong here?
import chararray.Console;
public class kundenverwaltung
{
public static void main (String args[])
{
int nk;
System.out.print("Wie viele Kunden möchten Sie erfassen?: ");
nk = Console.readInt();
char [][] kundenregister;
kundenregister = new char [nk][4];
for (int i = 0; i < nk; ++i)
{
System.out.print("Kundennummer: ");
kundenregister [i][0] = Console.readCharArray();
System.out.print("Name des Kunden: ");
kundenregister [i][1] = Console.readCharArray();
System.out.print("Vorname des Kunden: ");
kundenregister [i][2] = Console.readCharArray();
System.out.print("Adresse des Kunden: ");
kundenregister [i][3] = Console.readCharArray();
}
}
}

Look at this line:
kundenregister[i][0] = Console.readCharArray();
The expression kundenregister[i][0] refers to a char variable - not a char array.
It's not clear what you're trying to do - and in particular why you need the values as char arrays rather than as strings - but this would make it work:
char[][][] kundenregister = new char[nk][4][];
Having a 3-dimensional array is almost always a mistake. I would strongly suggest that you refactor the code to:
Use strings instead of char arrays
Encapsulate the 4 values into a type with properties for the number, name, first name and address
Create a List<Customer> or whatever... perhaps using ArrayList<T> as the implementation. Then you don't even need to know the number of customers beforehand... the user could just hit return (or whatever) to indicate that they'd finished.

Your variable kundenregister is declared as an array of arrays of chars. That means that for each x and y, kundenregister[x][y] is a single char (the yth character of the xth array of characters). Yet you are trying to assign it an entire array of characters.
I'm not sure what your goal is here so I can't suggest an easy fix. You either want to assign the result to some index of kundenregister or declare kundenregister as a 3-dimensional array.

I'm not exactly sure what you're trying to do here so I can't offer a full solution, but the immediate problem causing the error is in your kundenverwaltung class, in the for loop.
You're trying to assign Console.readCharArray() to kundenregister[i][0], which is where the type mismatch occurs since Console.readCharArray() returns a char[], and kundenregister[i][0] is of type char.
To help you understand this: kundenregister is essentially a 2d grid, where each slot is a single char. kundenregister[i][0] refers to one of those slots, so when you write kundenregister[i][2] = x, x has to be a char otherwise it won't work.

Related

Read a message character by character from keyboard and store in an array up to 256 characters

I'm coming here with another question because I've ran into a snag and haven't been able to figure out what the issue is..
My problem: Create an array of 256 characters, and read a message character by character from keyboard and store them in the array up to 256 symbols. The method should return number of the characters stored in the array.
Then pass the array to another method to print each word of the message in a line.
My attempted solution:
public static void main(String[] args){
char[] arrItem7 = new char[256];
readArray(arrItem7);
printOneInLine(arrItem7);
}
public static char[] getMsg(){
String myMessage;
System.out.print("Input Message: ");
Scanner input = new Scanner(System.in);
myMessage = input.nextLine();// Read a line of message
return myMessage.toCharArray();
}
public static char[] readArray(char[] arr){
arr = getMsg();
return arr;
}
public static void printOneInLine(char[] arr){
for(int i = 0; i < arr.length; i++){
if(arr[i] == 0){
System.out.print(" ");
}else{
System.out.print(arr[i]);
}
}
System.out.println();
}
The program prompts for input but then, unfortunately, prints NULL. I must be doing something wrong when setting the array to my message method.. Can someone help me? I've been trying to wrack my brain for the past 20 minutes.. Thanks so much
Have a look at this answer: Is java pass by reference or pass by value.
In short, Java is pass by value. Which means when you pass the array into your readArray() method, you in fact just pass the reference to that array into it. When you then assign a new array to the input parameter, you are overwriting the reference it's pointing to. You're not changing the original array. So the arrItem7 in the main method still points to the originally created array.
As you have found out, this does not work in the way you're using it. You could remove readArray() completely and just assign the value of getMsg directly to arrItem7:
public static void main(String[] args){
char[] arrItem7 = getMsg();
printOneInLine(arrItem7);
}

Input characters in array one by one java

I'm trying to take user input and put it into a character array and then print it out.... It's part of a bigger program and since i'm a new coder, I was hoping if you could keep the program simple without....
I get the error "Array index out of bounds". I tried changing the length of the array but that still didn't work.
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] ToEdit = new char [];
Scanner sc = new Scanner(System.in);
for (int i=0; i<5; i++)
{
System.out.println(i + ":");
ToEdit[i] = sc.next().charAt(i);
}
System.out.println(ToEdit);
}
Thank you
The problem lies here: char[] ToEdit = new char [];.
On that line, you are creating an empty array without a size. You would need to change it to : char[] ToEdit = new char [5];.
Further more, you will need to change this: ToEdit[i] = sc.next().charAt(i); to this: ToEdit[i] = sc.next().charAt(0);. The problem with your current line is that even if you enter 1 character, your code will look for more.
As a side note, it would be recommended that you extract the number 5 as a variable. This will allow you to increase or decrease the amount of characters your program can process by changing just one location.
As a further excercise, you can take a look at lists and see how you can make your program more flexible, without having to define a size for the array.
This wont compile as you need to add char array length first:
char[] ToEdit = new char[5];
Then this code ToEdit[i] = sc.next().charAt(i); produces String array out of bound exception. Because charAt(i) each time find char at 0,1,2,3,4 and so on position in string as shown below (the output of your program). So you need to change this to ToEdit[i] = sc.next().charAt(0);
0:
abcde
1:
acx
2:
acv
3:
acvff
4:
acdcdvc
acvfd

Using a method to find the letter in the inputted integer

"Write and test the method that returns a letter of the alphabet from a given word, it the position is given. (Hint: use the method that begins with static char getLetter (String txt, int n)."
I've been staring at this question for 20 minutes, can't seem to understand what it wants me to do.
This is what I have so far:
// The "Divide_raminAmiri" class.
public class Divide_raminAmiri
{
public static void main (String[] args)
{
String word;
int location;
System.out.println ("Enter a word.");
word = In.getString ();
System.out.println ("Enter the location of the letter.");
location = In.getInt ();
} // main method
public static void test (char c)
{
System.out.println (word.charAt (location));
}
} // Divide_raminAmiri class
I'm confused. I think what it wants me to do is use methods to find the letter at the location provided, but I'm getting errors. Any help appreciated!
Okay so I'm not gonna give the full solution since this seems to be some kind of an exercise.
What might help you:
The way you are doing it, you can't access the variable word in the test-method because it is only visible to the main-method, that's why we use parameters so you can pass variables to other methods.
Speaking of parameters, your method is asked to have two parameters, one being the String and one being an int, your test-method only has a char as parameter (?)
Your program starts and ends in the main-method, since you don't call your test-method there, it never gets executed.
Hints for your actual problem:
You can get a char at position x from a String with the method
char myChar = myString.charAt(x);
A char can be cast to an int with
int asciiValue = (int) myChar;
My last hint: Big letters have an ASCII-Value starting at 65 (='A'), small letters of 97 (='a').
Hope that helped, if you got any more questions feel free to ask.

Exception in thread "main" java.lang.Error : String[] not initialized

i want to write a program as it takes input strings from the user(for example bhas1234#gmail.com) and it prints as bhas1234(leaves the characters after #) when i write the below code it shows the following error:
import java.util.*;
import java.util.Scanner;
public class Name {
public static void main(String[] args) {
Scanner take =new Scanner(System.in);
int j=0;
String[] sh;
String gmail;
for(j=0;sh[j]!="exit";j++)
{
sh[j]= take.nextLine();
int i=sh[j].indexOf('#');
gmail= sh[j].substring(0,i);
System.out.println(gmail);
}
}
}
it shows the error as
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable sh may not have been initialized
You have to initialize your String array.
String[] sh = new String[numbefOfIndexes];
In Java, there is no way to use an array before having it initialized.
Keep in mind that, even if you initialize it like I did, the values by default are null as it is an array of objects, to avoid this, you can fill the array directly like below
String[] sh = {"valueOne", "valueTwo"};
Basically you want to
do endless loop (while)
read in a line of input
if it equals "exit", quit
otherwise either split at "#" and print the first part OR
find the "#" char's index and print a substring (what you did). The effects of the two methods are the same. It's only a matter of favor.
You are getting error at for loop where you are using sh[j] before it is initialized.
You should change your code to get input from user and check that as string only instead of array of string. I am giving solution as per your code only though. Update your code to:
Scanner take =new Scanner(System.in);
int j=0;
String sh;
String gmail;
while(!(sh = take.nextLine()).equals("exit"))
{
int i=sh.indexOf('#');
gmail= sh.substring(0,i);
System.out.println(gmail);
}

charAt method is returning an integer. Need to convert to int

I'm creating a method that will take the given input and set the value to "plate". I then proceed to use the charAt method and try to take the characters(letters/String) input and set it to a new value. But i'm told to set it to a char value. When I run aprint statement with it, the output is just a bunch of integers, or in my case (for the code i'm going to show) it outputs "195" when I put the license plate as abc 123. Also, the model doesn't do anything(or atleast isnt supposed to). If anyone could tell me what exactly i'm doing wrong it would be a great help.
Here is my code so far:
import java.util.Scanner;
public class CarRental {
public static String model;
public static String plate;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
char one = plate.charAt(0);
char two = plate.charAt(1);
System.out.println(two + one);
}
}
To make my issue clear, what I'm hoping to do is, assign the actual letters I type into the input to a separate value. I'm using the charAt method and it is returning integers.
if anyone could offer a suggestion it would help alot!
Thanks,
Sully
the + operator treats 2 chars as ints, try
System.out.println("" + two + one);
You can just use
Character.toChars(X)
Where x is your number to convert to char and then display said chars once they've been converted.

Categories