In my program the user will introduce a string(String A) and I want an Array(AA[]) of Strings to get every single letter of the String A. But it says that the Array
import java.util.Scanner;
public class arrays{
public static void main(String[] args){
String A,B,AA[];
int a,cX,cY,cc,c;
Scanner scanner=new Scanner(System.in);
System.out.println("Introduce your text");
A=scanner.nextLine();
a=A.length();
cX=0;
cY=cX+1;
cc=0;
for(c=0;c==a;c++){
B=A.substring(cX,cY);
AA[cc]=B;
cc+=cc;
cX+=cX;
cY+=cY;
}
}
}
It says(The error), that the variable AA might no have been initialized.
What I want is to make the Array to have all the letters from the String A...
UPDATED:
import java.util.Scanner;
public class arrays{
public static void main(String[] args){
String A,B,AA[];
int a,cX,cY,cc,c;
Scanner scanner=new Scanner(System.in);
System.out.println("Introduce your text");
A=scanner.nextLine();
a=A.length();
cX=0;
cY=cX+1;
cc=0;
AA = new String[a];
for(c=0;c==a;c++){
B=A.substring(cX,cY);
AA[cc]=B;
cc+=cc;
cX+=cX;
cY+=cY;
}
System.out.println(AA[2]);
}
}
Now when I print it out, it says null.
You need to initialize AA to the length of String A:
AA = new String[A.length];
And your loop is strange. You can change it to :
for(c=0;c<a;c++){
B=A.substring(c,c+1);
AA[c]=B;
}
Instance and class variables are initialized to null (or 0), but local variables are not.
A local variable must be explicitly given a value before it is used, by either initialization or assignment
There is a much simpler way:
public static void main(String[] args)
{
String inputString; //A
char [] inputStringCharacters; //AA
Scanner scanner=new Scanner(System.in);
System.out.println("Introduce your text");
inputString=scanner.nextLine();
inputStringCharacters = new char[inputString.length()];
for(int i = 0; i < inputString.length(); i++)
{
inputStringCharacters[i] = inputString.charAt(i);
}
//print each character in AA
for (int i = 0; i < inputString.length(); i++)
{
System.out.println(inputStringCharacters[i]);
}
}
I also strongly advise you to use descriptive variable names rather than things like "cc, A, AA", etc. It will be much easier to understand the logic of your code if you make it clear what a variable is supposed to contain.
Related
I am making a program with two classes, one to create methods and the other as the tester class. I am having difficulties assigning the input to a new variable, which needs to be used to invoke the methods from the other class.
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int obj = new NumberUtility(0);
System.out.println("Enter a number. Enter 0 to end");
obj = scan.nextInt();
As example here is the beginning of the other class
public class NumberUtility {
int n = 0;
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
public int getN() {
return n;
}
public boolean isEven() {
if((n % 2 == 0)) {
return true;
} else
return false;
}
My code is incomplete elsewhere but that is the main issue I have been trying to work around. Since if I set it to an int, it won't work. Sorry if this is a stupid question, I am new to java coding.
With this line:
int obj = new NumberUtility(0);
you are attempting to assign a new NumberUtility object to the variable obj which is of type int. You cannot do that! That's like trying to create a doghouse, and then shoving your dog into a birdhouse. They're just not compatible.
As well, later, you try to reassign obj to the result of scan, which would work, but probably not what you want, as obj is still an int:
obj = scan.nextInt();
I think what you want to do is something like the following:
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Enter a number. Enter 0 to end");
// Read a number from the scanner
int number = scan.nextInt();
// Create a new NumberUtility from this primitive integer
NumberUtility obj = new NumberUtility(number);
System.out.println("Even? " + obj.isEven());
By the way, you can simplify your isEven method as well:
public boolean isEven() {
return (n % 2 == 0);
}
Edit: I see I'm not done yet.
In the NumberUtility class, you have defined a constructor for the class:
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
This seems like an odd thing to do. You are ignoring the input (int n) and then calling all the methods of the class which don't really do much.
I think you want your constructor to be something like this:
public NumberUtility(int input_n) {
// Save the constructor's input parameter to the member field 'n'
this.n = input_n;
}
Hy my method is this:
public static String[] getcontestants(String[] contestants) {
int numcontestants = 8;
String name[] = new String[numcontestants];
for (int j = 0; j < numcontestants; j++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j] = ip.nextLine();
}
return name;
}
I would like to call this method in the static void main but I don't exactly know how to do it. Tell me if there's any mistake in this method. Thanks!
So tbh, I like Maarten Bodewes's answer better, but I think this might be a bit easier for you to understand.
Main :
public static void main(String[] args) {
String[] contestants = getcontestants();
}
I edited Your function just a bit:
public static String[] getcontestants()
{
int numcontestants=8;
String name[] = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j]=ip.nextLine();
}
return name;
}
Hope that answers your question!
You can just use
MyClass.getcontestants(new String[] { "MS", "MR" });
where MyClass is the class that contains the method. You can leave out MyClass. if your main method is in the same MyClass class.
This is a direct answer to your question. If you look at the design of your class then Hadeems answer shows you that you don't need to pass the String array to the method; the scanner can be used locally.
You don't need to create scanner object in this method (it will create as many objects as the loop goes which is not the standard way of coding & not efficient at all).
Declare static Scanner ip = new.... ; outside the method within a class as global variable. (static - so that it's only one instance)
class YourClassName{
static Scanner ip = new....;
public static void main(String [] args){
//String[] inputStringArray = getcontestants( //new String (){"my", "text", "as", "string", "array"});
// Why passing string array to the function where actually you are taking input from user
// Better don't pass anything except length of the string array
String[] inputStringArray = getcontestants(contestanstCount);
}
public static String[] getcontestants(..){}
}
here is the code. Try it.
import java.util.Scanner;
public class AmadouQuestion {
public static void main(String[] args) {
String [] names = getcontestants(3);
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
public static String[] getcontestants(int numcontestants)
{
Scanner ip=new Scanner(System.in);
String[] names = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
System.out.println("Enter contestant's name");
names[j]=ip.nextLine();
}
ip.close();
return names;
}
}
I am trying to find a way to assign values to an Array from the scanner input by using enhanced For loop. But I don't see a way I can do it.
In the code below i have declared a getInput() method which loops through the Array and assign numbers from the scanner input. But in case of enhanced For loop I can't really use something like this -
For(int i: baseData){
//basedata[i]=scanner.nextInt()}
because baseData array will not return any value as it iterates, so i thought how about iterating through scanner.nextInt() and assign values in the array, but scanner.nextInt() is not a array.
So what could the easy solution for this problem?
package com.ksk;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
for (int i = 0; i < baseData.length; i++) {
baseData[i] = scanner.nextInt();
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
A for-each loop hides the iterator, so you won't be able to update the array with one (at least not without adding a new counter / iterator). Instead, assuming you're using Java 8+, you can write an IntStream generator using your Scanner. Something like,
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
However, this is really just an example, in real life I would prefer code that is a little more forgiving with unexpected input.
Try like this.
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
printInput();
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
OR
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
int position =0;
for(int i:baseData){
baseData[position] = scanner.nextInt();
position++;
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
I am pretty new at Java and I am finding difficulty in solving the problem. Basically the code get a number, and generate a vector in the function generateVector. When I run this code, I am asked to put a number and then the software stay running forever. If possible, could you guys help me without other functions that is kind advanced? I am still learning. Thanks.
import java.util.Scanner;
public class Atividade02 {
static Scanner dados = new Scanner(System.in);
static int n;
//Main
public static void main(String args[]){
System.out.println("Type a number: ");
n = dados.nextInt();
int[] VetorA = generateVector(n);
for(int i=0; i<VetorA.length; i++){
System.out.println("Position: "+ VetorA[i]);
}
}
//Função
public static int[] generateVector(int n){
int[] VetorA = new int [n];
for (int i=0; i<n; i++){
VetorA[i] = dados.nextInt();
}
return VetorA;
}
}
I am asked to put a number and then the software stay running forever.
Did you enter in the n numbers required by generateVector? The program is probably just blocked on input from the user.
Try to modfiy the class as follows:
import java.util.Scanner;
public class Atividade02 {
// Added private access modifiers for properties.
// It's not necessary here, but as a general rule, try to not allow direct access to
// class properties when possible.
// Use accessor methods instead, it's a good habit
private static Scanner dados = new Scanner(System.in);
private static int n = 0;
// Main
public static void main(String args[]){
// Ask for vector size
System.out.print("Define vector size: ");
n = dados.nextInt();
// Make some space
System.out.println();
// Changed the method signature, since n it's declared
// as a class (static) property it is visible in every method of this class
int[] vetorA = generateVector();
// Make some other space
System.out.println();
// Show results
for (int i = 0; i < vetorA.length; i++){
System.out.println("Number "+ vetorA[i] +" has Position: "+ i);
}
}
// The method is intended for internal use
// So you can keep this private too.
private static int[] generateVector(){
int[] vetorA = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Insert a number into the vector: ");
vetorA[i] = dados.nextInt();
}
return vetorA;
}
}
Also when naming variables stick with the Java naming convention, only classes start with capital letters.
Here is the code:
import java.util.Scanner;
public class sending {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(first);
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(String first, String second){
first = ("Give me a number and I run down and add five to it");
second = ("Lol");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}
As you can see I am new to this and I am having a problem with the main method and the method giveMe.
I want to have giveMe work as a collection of strings that I can call when I need them.
But when I try the above example I eclipse tells me that "first cannot be resolved to a variable" on line six String text = giveMe(first);
What am I doing wrong?
You are trying to use an enum and you never declared one... declare your enum like this outside your Main.
enum s {FIRST, SECOND} //add this
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(s.FIRST); //add the s. so it knows to use your enum
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
Then you want to modify your method to take an enum instead like this
public static String giveMe(s string) {
switch (string) {
case FIRST:
return "Give me a number and I run down and add five to it";
case SECOND:
return "Lol";
}
return "invalid string";
}
Beginner, your problem is resolved.
Firstly declaration is important in java. "First" variable is not intailzed in your block of code. Ideally it is not necessary for your scenario.
Try this
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe();
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(){
String first = ("Give me a number and I run down and add five to it");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}