Beginner; Methods and Strings - java

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);
}
}

Related

using Boolean variable with a loop

I have a 2D array populated with exam results. Array contains names. User inputs some name and the prog checks if that name equals to any other name stored in an array. If they match it prints out the whole row, that contains that name. If there is no such name it should print out an "error". I need to use a Boolean variable that checks if something was found. But the problem is I can't come up with the idea how to check that something was found in a loop. When I use this line:
boolean=namesmatch=namechk.equalsIgnoreCase(math[x][1]);
It only makes it right if user inputs first name, since x=0. If user inputs any other name it prints out the needed row and then an "error". What should I do to get rid of this "error"?
public class Math extends StudentCharts {
public Math(){
math = new String [3][3];
math[0][0]="math"; math[0][1]="Bill Gates"; math[0][2]="49";
math[1][0]=math[0][0]; math[1][1]="John Doe"; math[1][2]="12";
math[2][0]=math[0][0]; math[2][1]="Paul Allen"; math[2][2]="31"; }
public void prnt (String namechk){
int x=0;
int y=0;
boolean namesmatch=namechk.equalsIgnoreCase(math[x][1]);
for (x=0; x<3; x++) {
if (namechk.equalsIgnoreCase(math[x][1])) {
for (y=0; y<3; y++) {
System.out.print(math[x][y]+" ");
} } }
if (!namesmatch) {
System.out.println("error");
} } }
this is the main class
public class Studentsarrays {
public static void main(String[] args) {
Math chr1 = new Math();
Scanner user = new Scanner(System.in);
System.out.println("Enter full name, please");
String namecheck = user.nextLine();
chr1.prnt(namecheck); } }
This should work.
Declare boolean namesmatch = false. In the inner for loop (y loop), set namesmatch = true. namesmatch would be set to true only if there was at least one match.
public class Math extends StudentCharts {
public Math(){
math = new String [3][3];
math[0][0]="math"; math[0][1]="Bill Gates"; math[0][2]="49";
math[1][0]=math[0][0]; math[1][1]="John Doe"; math[1][2]="12";
math[2][0]=math[0][0]; math[2][1]="Paul Allen"; math[2][2]="31"; }
public void prnt (String namechk){
int x=0;
int y=0;
**boolean namesmatch=false;**
for (x=0; x<3; x++) {
**if (namechk.equalsIgnoreCase(math[x][1]))** {
for (y=0; y<3; y++) {
System.out.print(math[x][y]+" ");
**namesmatch=true;**
} } }
if (!namesmatch) {
System.out.println("error");
} } }

Why this method doesn't return the value

public class Main {
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(tex));
reader.close();
}
public static int calculateCharacters(String text, int tex){
tex = text.length();
return tex;
}
}
So I receive a string from String text, then I send it to the method to calculate it's length and return a number which should be intercepted by System.out.println(calculateCharacters(tex)); and the probram should show me the number of letters in the string that was entered, the problem is: nothing reaches System.out.println(calculateCharacters(tex)); why ? where is this return tex; returning it then ?
Well I'm not entirely sure why you've got an int texvariable, but removing it lets this work perfectly. Try rewriting your method:
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
or if you're ready to be snazzy:
public static int calculateCharacters(String text) {
return text.length();
}
Java is pass-by-value (Is Java "pass-by-reference" or "pass-by-value"?), so keeping an extra int in there that you only use to store things locally won't actually change your value of tex.
Also, you instantiate the String text, but then pass tex to calculateCharacters(). Since you haven't created a texvariable before this, your compiler doesn't know what to pass to calculateCharacters(). Try changing that to:
System.out.println(calculateCharacters(text));
instead.
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(text));
reader.close();
}
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
}
It works
For counting the string use below code...
public class Main {
static int stringCount;
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
calculateCharacters(text);
System.out.println(stringCount);
reader.close();
}
public static int calculateCharacters(String text){
stringCount = text.length();
return stringCount;
}
}

Java Error; array required, but java.lang.String found

I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";

BIT is not showing the correct value

I am having a String , i am creating a BIT of String based on the frequency of the element present
String:
abcdbcaab
Code:
class Test{
static int[][] dp;
public static void update(int i , int val ,int[] dpp){
while(i<=100000){
dpp[i]+=val;
i+= (i&-i);
}
}
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i);
}
return ans;
}
public static void main(String args[] ) throws IOException {
Scanner in = new Scanner(new InputStreamReader(System.in));
dp = new int[27][1000001];
String s = in.next();
for(int i=0;i<s.length();i++){
update(i+1,1,dp[s.charAt(i)-'a']);
}
System.out.println(dp[0][7]); // Should show 2 as the frequency of 'a' at 7 position is 2
}
}
Where i am doing wrong . i could not get it but dp[0][8] is showing me 3Please Help i could not figure it out where i have commit mistake
Negativity should be avoided in life !!! but i think a little more negativity can improve you'r code:
value function you are doing wrong decrement of value of i
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i); // Should be (i&-i);
}
return ans;
}

Parsing string to accept other inputs

General info.
A mixed number is one of 3 forms:
1).An integer such as 12.
2).Fraction = int/int such as ¾
3.Mix of forms 1 and 2: 1 ¾ In this case one of more blanks act as a separator between integer and the fraction.
Question: 1.Treat the 1st and the 2nd forms as the special input and enhance the method parse to include these two cases.
* **I have already done the 3rd form of a mixed number and i am confused on how to parse the string to include an integer and a fraction alongside the mixed number in Mix.java . Output should be in gcd form. The following three programs run together.Some help me please thank you.
Here is my Mixed number code:
import java.util.Scanner;
class Mix extends Fraction{
public Mix(int n, int m) {super(n,m); }
public String displayMix() {
String str="";
if (first < second) str=first+"/"+second;
else str= first/second +" "+ first%second+"/"+second;
return str;
}//display
public Mix(String str) {
int[] iA= parse (str);
int top=iA[0]*iA[2]+iA[1];
int bot= iA[2];
int gcd = gcd(top,bot);
first=top/gcd;
second =bot/gcd;
}//Mix
public static Mix add (Mix s, Mix s2){
int gtop=s.first * s2.second
+ s2.first * s.second;
int gbottom= s.second * s2.second;
return (new Mix(gtop,gbottom));
}//add
public static String get (){
Scanner scan = new Scanner (System.in);
String userInput = scan.nextLine();
userInput =userInput.trim();
return (userInput);
} //get
public static int[] parse (String userInput){
int pos = userInput.indexOf(" ");
String sNum=userInput.substring(0,pos);
int iNum = Integer.parseInt(sNum);//first integer
String sNum2=userInput.substring(pos+1);
pos= sNum2.indexOf("/");
String sTop=sNum2.substring(0,pos);
int iTop = Integer.parseInt(sTop);//second integer
String sBot=sNum2.substring(pos+1);
int iBot = Integer.parseInt(sBot);//third integer
int[] sA = {iNum,iTop,iBot};
return (sA);
} //parse
public static void main(String[] args) {
System.out.print("Please enter mixed-format number :");
String userInput = Mix.get();
System.out.println("Input is: "+userInput);
Mix s = new Mix(userInput);
s.displayMix();
System.out.print("Please enter mixed-format number :");
userInput = Mix.get();
System.out.println("Input is: "+userInput);
Mix s2 = new Mix(userInput);
s2.displayMix();
Mix h= Mix.add(s,s2);
System.out.print(h.displayMix());
}//main
}//class
Here is the Fraction code:
public class Fraction extends Pair {
//attributes: NONE
public Fraction() { first=0; second=1;}
public Fraction(int n, int m) {
super(n,m);
int g=gcd(n,m);
first = first/g;
second=second/g;
}//Fraction
public String display2() {
String str = first+"/"+second;
return str;
}//display
public static Fraction add (Fraction f1, Fraction f2){
int gtop=f1.first * f2.second
+ f2.first * f1.second;
int gbottom= f1.second * f2.second;
return (new Fraction(gtop,gbottom));
}
public static int gcd (int n, int m){
while ( n!=m) {
if (n>m) n=n-m;
else m=m-n;
}//while
return (n);
}//gcd
//test the class
public static void main(String[] args) {
//pseudo-code is here
Fraction f= new Fraction();
f.display();
System.out.print(f.display2());
}//main
} //class
Finally here is pair:
import java.util.Arrays;
public class Pair {
int first;
int second;
public Pair (){first=0; second=0;}
public Pair(int n, int m) {
first=n;
second=m;
}//Pair
public int[] display() {
//pseudo_code is here
int[] c = {first, second};
return c;
}//display
public static void main(String[] args) {
//pseudo-code is here
Pair f= new Pair();
f.display();
System.out.println(Arrays.toString(f.display()));
}//main
} //class
You would have to make your own methods to do that using methods like str.split("/"), I don't know of any other way.

Categories