"Broken" while loop in Java - java

import java.util.*;
public class ValidatePercent {
Scanner k = new Scanner(System.in);
boolean val = false;
int pc;
while (!val)
{
System.out.print("please input a percentage");
pc=k.nextInt();
if (pc>=0 && pc<=100){
val = true;
}
}
}
I get an error at line 6 "illegal start of type // cannot find symbol // symbol: class val // location: class ValidatePercent // expected"
What does it mean? Why doesn't it work?
I have tried changing it to loop while pc is a value and then it doesn't recognise that either.

You need to put these inside a method or a block.
Simply use main()
public class ValidatePercent {
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
boolean val = false;
int pc;
while (!val)
{
System.out.print("please input a percentage");
pc=k.nextInt();
if (pc>=0 && pc<=100){
val = true;
}
}
}
}
You can't use while, System.out.print() and if outside a method or a block

You need to put your code into a method, like main. Main method is the one from which Java starts execution.
Here is the fixed code:
import java.util.*;
public class ValidatePercent {
public static void main(String[] args)
{
Scanner k = new Scanner(System.in);
boolean val = false;
int pc;
while (!val)
{
System.out.print("please input a percentage");
pc=k.nextInt();
if (pc>=0 && pc<=100){
val = true;
}
}
}
}

Related

Why does a variable declared in static block when used in main method is not not found?

I have a little difficulty understanding how the static block works
import java.io.*;
import java.util.*;
public class Solution {
static {
Scanner sc = new Scanner(System.in);
int B = sc.nextInt();
int H = sc.nextInt();
boolean flag= false;
if(B<=0 || H<=0){
flag= false;
System.out.println("java.lang.Exception: Breath and Hieght must be positive");
}
}
public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}
}
}
when I try to run it says cannot find symbol flag, B, H. Can anyone explain why?
The scope of the variable is within static block or any block for that matter. You should declare it outside the block and define it inside ur static block.
All the variables in your static block will be detroyed at the end of the execution of the block. To prevent this, you could declare those variables as fields like this
import java.io.*;
import java.util.*;
public class Solution {
private static int B;
private static int H;
private static boolean flag;
static {
Scanner sc = new Scanner(System.in);
B = sc.nextInt();
H = sc.nextInt();
flag = false;
if(B<=0 || H<=0){
flag= false;
System.out.println("java.lang.Exception: Breath and Hieght must be positive");
}
}
public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}
}
}
You should declare static variables outside the static code block.

How do you use methods from sub classes in the main class in Java?

I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.

Program won't run when using java.util.Arrays -- what might be going wrong?

I get a bunch of errors when the code within the "clearPets" method is not commented out. As long as I delete that code, the program will run otherwise.
How can the problems be fixed? I've only recently learned about creating and calling methods, and this is my first time using java.util.Arrays.
The errors in the console are:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Boolean
at java.util.Arrays.fill(Unknown Source)
at rf.uhh.clearPets(uhh.java:34)
at rf.uhh.optionOne(uhh.java:39)
at rf.uhh.main(uhh.java:20)
Here is the code I have:
public class uhh {
public static void main(String[] args){
System.out.println("Select a number");
System.out.println("1");
System.out.println("2");
System.out.print("Choice: ");
Scanner scnr = new Scanner(System.in);
String numberChoice = scnr.nextLine();
if( "1".equals(numberChoice) ) {
System.out.println("You chose 1");
optionOne(new boolean[][] { {false}, {true} });
}
scnr.close();
}
public static boolean[][] adoptPets( int cats, int dogs) {
boolean[][] pets = new boolean[cats][dogs];
return pets ;
}
public static void clearPets( boolean[][]pets) {
Arrays.fill(pets, false);
}
public static void optionOne(boolean[][] center) {
clearPets(center);
boolean[][] dogFaceMan = adoptPets(10, 10);
dogFaceMan[1][1] = true;
}
}
You are passing a 2D array into a method (Arrays.fill) that expects a 1D array.
Try this:
public static void clearPets( boolean[][]pets) {
for(int i = 0; i < pets.length; i++) {
Arrays.fill(pets[i], false);
}
}

While loop doesn't quit

i wrote a program in java wich compares tow variables values, X and Y.
when i enter the same number for X and Y in the first attempt of the loop it says Match and terminate. But if it returned "false" in the first loop and then returned "true" in the next it doesn't terminate and goes on as if "b" has a "false" value.
import java.util.Scanner;
public class clads {
//Variables
public static int y;
public static int x;
static boolean b = mymethod() ;
//MainProcess
public static boolean mymethod() {
Scanner myscanner = new Scanner(System.in);
System.out.println("put a number for X");
x = myscanner.nextInt();
System.out.print("put a number for Y");
y = myscanner.nextInt();
if (y==x){
System.out.println("match");
return true;
}else{
System.out.println("Mismatch, Redo");
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
while(b ==false){
mymethod();
}
}
}
But when I added a "Break;" keyword it terminated whenever it returned a "true" value. can i have some explanation please.
public static void main(String[] args) {
// TODO Auto-generated method stub
while(b ==false){
mymethod();
Break;
}
When you initialize b by calling mymethod, it's set to either true or false forever. If it's true, your doesn't execute. If it's false, your loop executes forever.
Your mistake is in setting the value of b when b is declared. You actually don't need b at all. Just put the invocation of mymethod() inside the while condition:
import java.util.Scanner;
public class clads {
//Variables
public static int y;
public static int x;
//MainProcess
public static boolean mymethod() {
Scanner myscanner = new Scanner(System.in);
System.out.println("put a number for X");
x = myscanner.nextInt();
System.out.print("put a number for Y");
y = myscanner.nextInt();
if (y==x){
System.out.println("match");
return true;
}else{
System.out.println("Mismatch, Redo");
return false;
}
}
public static void main(String[] args) {
while(!mymethod());
}
}
You have to check the return value from mymethod() every time it's invoked. Your original code just caught the first value and used it forever.
Because your variable initialize once and then never get updated. try:
public static void main(String[] args) {
while(!b){
b = mymethod();
}
}
you can modify the code as follows below
public static void main(String[] args) {
// TODO Auto-generated method stub
while(b ==false){
if (mymethod()) {
break;
}
}
if the function mymethod() returns true, the while loop will terminate, but when the function returns false, the while will continue.

Variable does not exist?

So, I have some fairly simple code, but in the second class, neither method can find name. Is this a simple issue of scope?
package rpg;
import java.util.Scanner;
public class Start {
static String name;
public static void main (String args[])
{
Engine test12 = new Engine();
name = test12.gameStart();
System.out.println("So, " + name + " it is!");
}
}
Which calls this class:
package rpg;
import java.util.Scanner;
public class Engine {
static boolean playerNameLike = false;
String name = (" ");
public String gameStart()
{
while (playerNameLike = false)
{
System.out.println("So, whats your name?");
Scanner gameStart = new Scanner(System.in);
name = (gameStart.next());
nameTest();
}
return name;
}
public boolean nameTest()
{
System.out.println("Does " + name + " sound good?");
System.out.println("(Y)es or (N)o?");
Scanner gameStart = new Scanner(System.in);
String yesNo = new String (gameStart.next());
if (yesNo.equals("Y"))
{
playerNameLike = true;
return playerNameLike;
}
if (yesNo.equals("N"))
{
playerNameLike = false;
return playerNameLike;
}
return playerNameLike;
}
}
Does anyone know what I'm doing wrong?
You should make name a local variable in the gameStart method, and pass it to nameTest as a parameter, like this:
public String gameStart()
{
String name = "";
boolean playerNameLike = false;
while (!playerNameLike)
{
System.out.println("So, whats your name?");
Scanner gameStart = new Scanner(System.in);
name = (gameStart.next());
playerNameLike = nameTest(name);
}
return name;
}
public boolean nameTest(String name) // Use your current code from here on
Also, you are assigning false to the variable in the if statement. This is allowed, but it does not do what you want. You should either use ==, or (better) use ! to negate the variable:
while (!playerNameLike) ...
Use == to compare in the condition as:
while (playerNameLike == false)
or just check the negation of it as its a boolean type:
while (!playerNameLike)
Also, move the Scanner instantiation outside the while loop as:
Scanner gameStart = new Scanner(System.in);
while (!playerNameLike)
{
System.out.println("So, whats your name?");
name = (gameStart.next());
nameTest();
}

Categories

Resources