(noob) java values use (Scanner + For) - java

I wanted to program a java app that can print as many stars as the user want.
The programm will ask the user how many starts he want to print.
Here is my code :
import java.util.Scanner;
public class lab {
public static void main(String[] args){
int StarsN;
Scanner input;
input = new Scanner(System.in);
System.out.println("How many stars do you need?");
StarsN= input.nextInt();
}
public static void loopz(String[] args) {
int loopEnd = StarsN;
int loopStart;
for (loopStart = 0;loopStart==loopEnd;loopStart++) {
System.out.print("*");
}
}
}

First thing to note.. I don't know why you are sending your loopz method a String[].. Here is what i would do differently in the loopz method:
public static void loopz(int numOfStars)
{
for(int i = 0; i < numOfStars; i++)
System.out.print("*");
}
Also call loopz in main and send it the parameter.

your for loop : loopStart = 0 then it says is loopStart == loopEnd , and it won't enter in the loop because loopStart don't equals loopEnd so you should change "==" in your loop to "<" .

Here is the answer:
import java.util.Scanner;
public class lab {
public static void main(String[] args){
int StarsN;
Scanner input;
input=new Scanner(System.in);
System.out.println("How many starts do you need ?");
StarsN= input.nextInt();
int loopEnd = StarsN;
int loopStart;
for (loopStart = 0;loopStart<loopEnd;loopStart++) {
System.out.print("*") ;
}
}
}
I really would like to teach you how to fish, instead of just giving you the fish, but I think that you need too much theory before this. Try to find some book or a good and complete tutorial to follow, I'm sorry but I don't know neither of both to say to you.

Change for (loopStart = 0;loopStart==loopEnd;loopStart++) to for (loopStart = 0;loopStart < loopEnd;loopStart++).
And don't forget to call loopz() from main():
public static void main(String[] args){
Scanner input = null;
try {
input=new Scanner(System.in);
System.out.println("How many starts do you need ?");
int StarsN= input.nextInt();
loopz(StarsN); //Add this
} finally {
if( input != null )
input.close();
}
}
public static void loopz(int numStars) { //You don't need the String[] args here since you never use it
for (int loopStart = 0; loopStart < numStars;loopStart++) {
System.out.print("*") ;
}
}

Related

Use Variable Which is in main method in Another Method

I'm trying to create a simple program to output the number of stars entered by user. I'm trying to learn how to use more than one method to do this
Here's my code
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
}
public static void Loop ()
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
The problem I'm facing is that in the Loop method, I am unable to use the variable n
Is there a way to use a variable which is in the main method, in another one?
Ty
-Pingu
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n); //calls Loop function and passes parameter n
}
public static void Loop(int n) //this function now expects a number n
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
simply pass it as parameter:
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n);
}
public static void Loop (int count)
{
for (int counter = 1; counter <= count; counter++)
{
System.out.println("*");
}
}
Pass it as a paramteer
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
loop(n); // added this
}
public static void loop (int n) // changed here
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
I think you should use it as a instance variable and for better understanding name your class like StarClass it can provide better understanding. Good programming practice.
But you should avoid unneccesserily making instance variable without any logic behind it.
I also think you could declare n as a public variable.
That should make it accessible throughout the code.
public int n;
But I guess that passing it as parameter is a better practice, since you don't create a deppendance inside your code. What I mean is, if something changes with the variable you break the function. It's good practice to always keep things "modular" in your code, so it makes it more resilient to changes and debugging.
It's better if you get used to it from the beggining =)
Two ways.. one has been posted already as answer and the other one would be using the variable as a field. This way you can access (and modify) it in every method without having to pass it on.
public class Alpha
{
static int n;
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter no. of stars");
n = input.nextInt();
loop();
}
public static void loop ()
{
for (int counter = 0; counter < n; counter++)
{
System.out.println("*");
}
}
}
And please start method names with lowercase and counting with 0. It's common practise and it helps a lot to use the standards right from the beginning.
Like this you can use variable from different methods in different methods
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum=0;
int a=Sum(sum);
System.out.println("The Average of the numbers is: "+a);
}
public static int Sum(int sum) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the total count of number for Average: ");
int a=sc.nextInt();
for(int i=1;i<=a;i++) {
System.out.println("Enter the"+i+"Number: ");
int b=sc.nextInt();
sum+=b;
}
int avg=sum/a;
return avg;
}

What are the errors here?

import java.util.Scanner;
public class program4
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println(" Hello and welcome to the program ");
System.out.println("Enter your number.");
int number = input.nextInt();
int integerDoubled;
System.out.println("Your result is" + doubleNumber(number));
System.out.println(" thank you for using my program ");
}
public static int doubleNumber (int x){
int integerDoubled;
return integerDoubled = (x*2);
}
if (integerDoubled < 100 ); {
less_100(integerDoubled);
} else if ;
greater_100(integerDoubled);
public static int less_100 (int integerDoubled)
{
int integerDoubled;
return integerDoubled =(x*2);
}
public static int greater_100 (int integerDoubled)
{
int integerDoubled;
return integerDoubled =(x*3);
}
}
}
I think the error is in the If statement but i don't know how to fix it.
I know integerDoubled is a local variable and i should make it global but I'm not sure how to do that. should i put the if statement together with the doubleNumber function??
If you formatted your code (your IDE will do this for you), you would see that the if statement is not inside a method as it must be. If you use your IDE correctly, finding and correcting such error would be much faster and you barely have to think about it.
I tried to make sense of your program this is what I came up with
import java.util.Scanner;
public class T
{
public static int doubleNumber (int x){
int integerDoubled;
return integerDoubled = (x*2);
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println(" Hello and welcome to the program ");
System.out.println("Enter your number.");
int number = input.nextInt();
int integerDoubled=doubleNumber(number);
System.out.println("Your result is" + integerDoubled);
System.out.println(" thank you for using my program ");
if (integerDoubled < 100 ) {
less_100(integerDoubled);
}
else
greater_100(integerDoubled);
}
public static int less_100 (int integerDoubled)
{
return integerDoubled =(integerDoubled*2);
}
public static int greater_100 (int integerDoubled)
{
return integerDoubled =(integerDoubled*3);
}
}

(Process String) in Java program

I want to help me in this program.
Write a program that prompts the user to enter a string and displays the characters at even positions.
package lab6b;
import java.util.Scanner;
public class Lab6b {
public static void main(String[] args) {
Scanner in = new Scanner("Enter a number:");
char s = 0;
for (int i = 0; i < s.charAt(i); i++) {
if (i % 2 == 0) {
continue;
} else if (i % 2 == 1) {
break;
}
}
}
}
You could do like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a string:");
String enteredString = in.next();
for (int i = 1; i < enteredString.length(); i+=2) {
System.out.println(enteredString.charAt(i));
}
But I think you have to look into things like Scanner, String, loops etc...
The use Scanner class for input you must pass System.inas argument,then use<object>.nextLine()to accept String object then iterate from 1 to s.length()-1 with increment by 2.
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=in.nextLine();
for(int i=1;i<s.length();i+=2)
System.out.print(s.charAt(i));
//I assume the user understands the string begins with 1...s.length()
}

Trying to make a random array that I can call 5 times, and that i can test against a user input

Need some help trying to set up this assignment. I am not to good with arrays, nor setting up methods to be used in the main. I need to make an array of 10 random numbers 1-100, that can be compared to the user input. I only need the comparison true/false to display. Here is what I have.
I get several errors in trying to print, so i haven't even tried to compare it to the user input yet.
Thanks,
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print(shots);
}
public int [] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++)
shots[i] = r.nextInt(100);
return shots;
}
public static void print(int shots[]) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}
As commentors said, please provide error messages.
However, I can pick out several issues just for starters. Let's look at your main method...
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print int [](shots);
}
In this call to the print method, why do you have int [] in there? Are you trying to cast something to an int array? Anyways, that has to come out.
Also, you are passing the print method some shots variable that doesn't exist.
Your print method takes an int array as its only argument, so you have to pass it a valid int array. Perhaps you meant to call getRandomNumbers() and pass the int array that it returns to the print method?
Also, what's with the nested classes you're showing. You have this class Final with another class ShotClass defined inside of it. And your closing brackets are all out of whack.
In short, you need to do as the comments ask and format your code and then work through each individual error message, because you've got a whole lot to fix.
EDIT
I'm not sure if I'm doing you more harm than good by giving you the answer to your homework assignment, but I feel for you so here it is. Please just look very carefully at the exact differences between what you posted in your question and what I show below. There's several mistakes you made, including bad syntax and a misunderstanding of how scope works, and I can't properly explain all the problems without typing several pages, so I hope you can learn from this example instead...
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
int[] shots = getRandomNumbers();
print(shots);
}
public static int[] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++) {
shots[i] = r.nextInt(100);
}
return shots;
}
public static void print(int[] shots) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}//END class

Can't get my Scanner to work with ArrayList

Hi sorry in advance about my bad code haha. I'm trying to get my code to read out what I type in the keyboard (only one phrase) forwards and then backwards however I keep getting errors with every different method I try.
import java.util.ArrayList;
import java.util.Scanner;
class hw
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
sal.add(kb.next());
sal.add(kb.next());
sal.add(kb.next());
display(sal);
displayb(sal);
}
public static void display(ArrayList<String> sal)
{
for (int i=0; i<sal.size(); i++)
System.out.print(sal.get(i)+ " ");
System.out.println();
}
public static void displayb(ArrayList<String> sal)
{
for (int z = sal.size(); z >= 1; z--)
System.out.print(sal.get(z-1) + " ");
System.out.println();
}
}
I know this has something to do with using a while loop and something like
String s;
s = kb.next();
but I keep getting infinite loops and other errors with everything I try. Any ideas?
I am quite sure code is ok, you need to make following change though.
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
sal.add(kb.next());
sal.add(kb.next());
**Sal.add(kb.next());**
here replace "Sal" with "sal"
For simple constant adding using a while loop, you need some type of termination condition:
int i = 0;
while (i < 5) {
sal.add(kb.next());
i++;
}
/* or */
String last = "";
while (!last.equals("end")) {
last = kb.next();
sal.add(last);
}

Categories