import javax.Swing.JOPtionPane;
public class while looping {
public static void main (String []args){
String a= JOptionPane.ShowInputDialog("Please enter an Integer");
int b=Integer.parseInt(a);
int j=1;
while(j<=b){
j++;
int k=1;
while (k<j){
System.out.print("*");
k++;
}
System.out.println();
}
}
}
}
This is my program and when i run it it says that javac: invalid flag: while what does it mean?
The "invalid flag" is probably related to the way you call the compiler. Do you call the compiler from a command line? How does the call look like?
You also have an error in your code, unrelated to the error message: you call your class "while looping". This is wrong on 2 (or 3) points: a class name must be one word, a class name must not be a reserved word ("while"), and a class name should start with a capital letter.
The last point is just a naming convention, but it makes life easier for everyone who has to read your code.
You can even see your error in your question with the highlighting:
public class while looping {
}
A class name may not contain any blank character.
Also it is usual to start class names with a capital letter.
Please rename your class to
public class WhileLooping {
}
and also rename your .java file accordingly.
Related
I've run into a problem where I attempt to define a constructor in the first part of a switch/case statement, and then I can't run the code because the program can't get the definition later.
The idea behind passing the constructor information from a switch/case function is that the user chooses what to do, but for some options, one must be done before the other is possible (e.g. Create password and Check password).
If I try doing it this way, it throws a VarMayNotHaveBeenInitialized error (I get the sense the answer is in a try/catch statement, but I don't know enough about them to be sure). I've included some code that is what I've been essentially trying to do below. (The two classes are to best simulate the project I'm working on.)
Any help is appreciated! : )
TestMain.java:
package exitTest;
public class TestMain {
InitializeTest init;
public static void main(String[] args) {
while (true) {
String x = InitializeTest.askQuestion();
switch (x) {
case "set":
InitializeTest init = new InitializeTest();
break;
case "get":
if (init != null) {
init.showExample();
} else {
System.out.println("Error: init not initialized.");
} break;
}
}
}
}
InitializeTest.java:
package exitTest;
import java.util.Scanner;
public class InitializeTest {
static Scanner in = new Scanner(System.in);
public InitializeTest thing1;
public String example;
public static String askQuestion() {
System.out.println("set for set example\nget for check example");
String action = in.nextLine();
return action;
}
public InitializeTest() {
System.out.println("Input string:");
String example = in.nextLine();
}
void showExample() { System.out.println(example); }
}
You include the type when you're declaring variables, not when simply assigning to an existing one. When you write
InitializeTest init = new InitializeTest();
That makes a new init variable, unrelated to the previous one, which stores the newly constructed object. That new variable shadows the existing one, but it gets released after the switch block is over (variables in Java are block-scoped).
To put it to an analogy, it's as though you wanted to tell your friend Alice a secret. But when you went to her house, her neighbor whose name is also Alice happened to be there instead. If you tell that Alice your secret, then your friend doesn't find out. Even though the two happen to share a name, they don't share any memory.
import java.util.*;
public class ArrayIndexOutOfBoundsException {
public static void main(String[] args) {
int[] array = new int[100];
//creating array with 100 storage spaces
for(int i = 0; i < array.length; i++) { //for loop to store random integers in each index of the array
array[i] = (int) (Math.random()*100);
}
Scanner input = new Scanner(System.in);
System.out.println("Enter the index of the array: ");
//prompting user to enter index to find
try {
int index = input.nextInt(); //declaring index variable to take on inputed value
System.out.println("The integer at index "+index+" is: "+array[index]); //printing the integer at the specified index
}
catch (ArrayIndexOutOfBoundsException ex) { //if user enters index value outside of 0-99, exception message will print
System.out.println("Out of bounds.");
}
}
}
When your code is being compiled to the byte code, the compiler has to discover all classes and extend all names into their FQDNs - packages + class name
In your case, when the programs is compiled, the main class name is ArrayIndexOutOfBoundsException - so the compiler maps ArrayIndexOutOfBoundsException to your own class.
When compiler gets to catch line, it takes ArrayIndexOutOfBoundsException and tries to first locate it in the map - and it is there. So the compilers starts checking the correctness, in particular, the class has to be in Throwable hierarchy. Since it is not in throwable hierarchy (your class implicitly extends Object), the compiler returns an error.
You could fix it using two ways:
rename you main class to avoid ambiguity
in catch you may specify full name for the class: java.lang.ArrayIndexOutOfBoundsException
The second options helps with a generic problem: what if two classes have the same name, but have to be used in the same scope.
The ArrayIndexOutOfBoundsException exception type is included in the java/lang package. So you have to import it or use the full name in your catch clause:
catch (java.lang.ArrayIndexOutOfBoundsException ex)
In your situation, import won't work because your class is also called ArrayIndexOutOfBoundsException so you'll need to use the full name in the catch clause.
As a final advice, I recommend you rename your class as a good practice cause as it is now, it could lead to confusion and turn the code difficult to read.
I am writing a simple Java program to rotate a Linked List, but when trying to compile the Java code through the compiler via: javac RotateLinkedList.java, I get the following error in my console:
jared#jared-linux:~/Desktop/Code Interviews$ javac RotateLinkedList.java
./LinkedList.java:9: error: class ListOperations is public, should be declared in a file named ListOperations.java
public class ListOperations{
^
RotateLinkedList.java:82: error: cannot access LinkedList
LinkedList<Integer> ll = new LinkedList<Integer>();
^
bad source file: ./LinkedList.java
file does not contain class LinkedList
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
Which is odd as this looks to be that the source code for Java is what is failing? I am compiling against Java JDK 8 and on Ubuntu 14.04.
Below is a snippet of the code I am running to create the LinkedList, if that helps:
import java.util.*;
public class RotateLinkedList {
public static void main(String args[]) {
// Crate the linked List
LinkedList<Integer> ll = new LinkedList<Integer>();
// Adding elements to linked list
System.out.println("How many elements should be in the binary linked list: ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if((num != null) && (num > 0)) {
System.out.println("Adding " + num + " elements into the linked list.");
for(int i = 0; i < num; i++) {
ll.add(i);
}
System.out.println("Linked List: " + ll);
} else {
System.out.println("NULL or invalid number inputted. Aborting");
}
}
}
Appreciate any feedback! Cheers.
The compilation error message is quite straight forward: The name of your java file is not the same as that of the public class defined in it.
It is one of the basic constructs of Java language that the file name should match exactly with the publicly declared class in that java file. Note here that there could be multiple classes in a java file, nevertheless, only one publicly declared class in it!
Just to confirm, try changing the name of your java file to "ListOperations.java" and then compile it.
So I was an idiot and forgot I had a LinkedList.java (which is mostly psuedocode, etc) file in my source folder when compiling, so the compiler wanted to import that file when compiling RotateLinkedList.java. Argh! Sorry about that. Appreciate the views / responses, though!
I'm learning java from the very beginning and I'm trying to accept a problem in a programming site, Its very basic, all i need to do is to print a+b till the end of file, I searched everywhere for EOF and all of them implemented an end of file,supposing a real file, but in the problem I'm writing the code of, I shouldn't use actual file.
I use this code in C++:
#include<iostream>;
using namespace std;
int main()
{
int a,b;
while(cin>>a)
{
cin>>b;
cout<<a+b<<endl;
}
}
now I kinda converted it in this way to java:
package a.b;
import java.util.*;
public class AB {
static Scanner in=new Scanner(System.in);
public static void main(String[] args) {
int a,b;
a=in.nextInt();
while(in.nextInt()!=null)
{
b=in.nextInt();
System.out.println(a+b);
a=in.nextInt();
}
}
}
but I don't know how to implement an EOF for it. any help would be appreciated.
system default input stream has no eof ... rather you can implement:
it should not be
in.nextInt()!=null
but rather
in.hasNextInt()
or you may get a line
in.nextLine();
and then extract each number separately by your own method.
I am trying to run this program but I cannot, the compiler is sending me a ".class" error.
Can somebody help me with my problem and if it is possible a general tip about ".class" error?
Here is the program:
import java.io.*;
class Bus
{
private int kostos;
private int plithos;
private int typepiv;
Bus(int x,int y,int z)
{
kostos=x;
plithos=y;
typepiv=z;
}
public void KB(int[] x)
{
try{
for(int i=1;i<5;i++)
{
if(typepiv==2)
{
plithos=plithos+plithos/2;
kostos=kostos-kostos/2;
}
if(typepiv==3)
{
plithos=plithos-plithos/5;
kostos=kostos-kostos*25/100;
}
if(typepiv==1)
{
plithos=plithos;
kostos=kostos;
}
x[i]=plithos*kostos;
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
class testBus
{
public static void main(String args[])
{
String leof[]=new String[4];
int leof1[][]=new int[4][3];
for(int i=1;i<5;i++)
{
System.out.println("dwste onoma leoforiou");
leof[i]=UserInput.getString();
System.out.println("dwste kostos thesis enilika");
leof1[i][1]=UserInput.getInteger();
System.out.println("dwste plithos thesewn");
leof1[i][2]=UserInput.getInteger();
System.out.println("dwste tupos epibath gia enilikes=1,gia
paidia=2,gia suntaksiouxous=3");
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
----->leof2.KB(KostEnoik);
System.out.print("onoleo");
System.out.print(" ");
System.out.print("plithos");
System.out.print(" ");
System.out.print("kost(EURO)");
System.out.print("typepiv");
System.out.print(" ");
System.out.print("apotelesma kostEnoik");
for(int g=1;g<5;g++)
{
System.out.print(leof[g]);
System.out.print(leof1[g][2]);
System.out.print(leof1[g][1]);
System.out.print(leof1[g][3]);
System.out.print(KostEnoik[g]);
}
}
}
the compiler message says :
testBus.java:56:error:cannot find symbol
leof2.KB(KostEnoik);
symbol:bariable leof2
location:class testBus
1 error
Remove the array brackets [] when invoking KB
leof2.KB(KostEnoik);
and remove the preceding enclosing brace }.
Aside: Java naming conventions indicate that variables start with a lowercase letter e.g. kostEnoik. Also consider giving the method KB a meaningful name, e.g. calculateCost
Read Java naming conventions
concern is with your access
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it is defined i.e. outside for loop and scope is upto for loop and that's why the compiler will not be able to find that varialble .
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it's defined (in this particular case, the for loop) and that's not allowed.
method KB takes an int array as argument, but you don't have to add the [] when passing the argument. The correct line is
leof2.KB(KostEnoik);
However, there's something pretty odd with you logic: you're repeatedly (for loop) setting leof2, but only the last iteration of the loop will have any effect. I'm almost certain that that's not what you actually want, but the correct answer to where Bus leof2 should actually be defined depends on the correction of that issue.
leof2.KB(KostEnoik); this is the main culprit. whether you have imported UserInput.
Also try to go through the Java Basics
any method can be invoked using object when it is non static or class name when it is static. Please consider this link
Get leof2 object out side the For Loop.
Don't type [] when you pass the array as argument "leof2.KB(KostEnoik[]);".