Search Results

Search found 874 results on 35 pages for 'scanner'.

Page 16/35 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • How to create a String Array and link it to a Grade array

    - by user1861544
    I have a project that I need to create 2 Arrays, one to hold Student Names and one to hold Student Scores. The user inputs the size of the array, and the array needs to be sorted using BubbleSort (putting the high scores at the top). I have started the project, created the first array for scores, I have successfully done bubble sort and sorted the grades. Now I can't figure out how to make an array for Names, and once I do how do I make the names array correspond to the Grades array BubbleSort? Here is the code I have so far. import java.util.Scanner; public class Grades { public static void main(String[]args){ { Scanner UserIn = new Scanner(System.in); System.out.print( "How many students are there? " ); int[]GradeArray = new int[UserIn.nextInt()]; for( int i=0 ; i<GradeArray.length ; i++ ) { System.out.print( "Enter Grade for Student " + (i+1) + ": " ); GradeArray[i] = UserIn.nextInt(); } bubbleSort(GradeArray); for( int i : GradeArray ) System.out.println( i ); System.out.println(); } } private static void bubbleSort(int[]GradeArray){ int n = GradeArray.length; int temp = 0; String temp2; for(int i=0; i<n; i++){ for(int j=1; j<(n-i);j++){ if(GradeArray[j-1]<GradeArray[j]){ //swap temp=GradeArray[j-1]; GradeArray[j-1]=GradeArray[j]; GradeArray[j]=temp; } } } } } Also how do I change the grades to Double? I started with Int and when I try to change everything to double I get an error saying "Found Double, expected Int".

    Read the article

  • need help with some basic java.

    - by Racket
    Hi, I'm doing the first chapter exercises on my Java book and I have been stuck for a problem for a while now. I'll print the question, prompt/read a double value representing a monetary amount. Then determine the fewest number of each bill and coin needed to represent that amount, starting with the highest (assume that a ten dollar bill is the maximum size needed). For example, if the value entered is 47,63 (forty-seven dollars and sixty-three cents), and the program should print the equivalent amount as: 4 ten dollar bills 1 five dollar bills 2 one dollar bills 2 quarters 1 dimes 0 nickels 3 pennies" etc. I'm doing an example exactly as they said in order to get an idea, as you will see in the code. Nevertheless, I managed to print 4 dollars, and I can't figure out how to get "1 five dollar", only 7 dollars (see code). Please, don't do the whole code for me. I just need some advice in regards to what I said. Thank you. import java.util.Scanner; public class PP29 { public static void main (String[] args) { Scanner sc = new Scanner (System.in); int amount; double value; double test1; double quarter; System.out.println("Enter \"double\" value: "); value = sc.nextDouble(); amount = (int) value / 10; // 47,63 / 10 = 4. int amount2 = (int) value % 10; // 47 - 40 = 7 quarter = value * 100; // 47,63 * 100 = 4736 int sum = (int) quarter % 100; // 4763 / 100 => 4763-4700 = 63. System.out.println(amount); System.out.println(amount2); } }

    Read the article

  • Is my code a correct implementation of insertion sort?

    - by user1657171
    This code sorts correctly. Is this an insertion sort? import java.util.Scanner; public class InsertionSort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements: "); int count; count = sc.nextInt(); int[] a = new int[count]; System.out.println("Enter elements: "); for(int i = 0 ; i<count;i++){ a[i] = sc.nextInt(); } int j,temp; System.out.println("aftr insertion sort :"); for(int i = 1 ; i<count;i++){ j=i; while(j>0 && a[j-1] > a[j] ){ temp = a[j]; a[j] = a[j-1]; a[j-1] = temp; j--; } } for(int i = 0 ; i<count;i++){ System.out.print(a[i]+" "); } } }

    Read the article

  • ArrayIndexOutOfBoundsException double array size

    - by Andy
    I'm going to preface this question with this statement: I know that I can easily handle this problem by reading the amount of lines in a file and making an array that size. I am not allowed to do this. Anyway, here is my question. I need to double my array's size whenever my program encounters an ArrayIndexOutOfBoundsException and then copy all the previous read in information into the larger array. Here is my code public static void main(String[] args) throws IOException { Scanner inScan, fScan = null; int [] A = new int[5]; inScan = new Scanner(System.in); System.out.print("Please enter the file to read from: "); while(true) { try{ String fName = inScan.nextLine(); fScan = new Scanner(new File(fName)); break; } catch (FileNotFoundException ex) { System.out.println("Your file is invalid -- please re-enter"); } } String nextItem; int nextInt = 0; int i = 0; while (fScan.hasNextLine()) { try { nextItem = fScan.nextLine(); nextInt = Integer.parseInt(nextItem); A[i] = nextInt; i++; } catch (NumberFormatException e) { System.out.println("Found an invalid int -- ignored"); } catch (ArrayIndexOutOfBoundsException e) { //double the size of array A until //copy all previous read in information to the larger array } } System.out.println("Here are your " + i + " items:"); for (int j = 0; j < i; j++) { System.out.println(A[j] + " "); } } }

    Read the article

  • Identify words with ascending characters from text file

    - by user2914000
    I am having a fair amount of trouble trying to write a program that counts the amount of ascending words (words in which each character is larger than the previous character) in a text file. I have tried a few different methods to solve this but cannot seem to get it working. If anyone could help me revise the code to work properly it would be appreciated. The code will print about 5 of the words from the list of nearly 20000, but none considered are ascending (the file does have many ascending words) and it sometimes prints the same word twice. I am printing theWord to the console simply to see if the code works. import java.util.Scanner; import java.io.*; public class { public static void main (String [] args) throws FileNotFoundException{ String theWord; Scanner inputFile = new Scanner(new File("file.txt")); boolean ascending = true; int i = 1; while(inputFile.hasNextLine()){ theWord = inputFile.nextLine(); if(theWord.length() >= 2){ while(i < theWord.length() - 1){ if(theWord.charAt(i) <= theWord.charAt(i + 1)){ ascending = true; System.out.println("+ " + theWord); totalNum = totalNum + 1; } else{ ascending = false; System.out.println("= " + theWord); } i++; } } }

    Read the article

  • How to scale page size down in Adobe Acrobat X Pro?

    - by WilliamKF
    I scanned a document on a scanner at a friend's house and the pdf ended up being 35 inches by 45 inches in size. I think this the cause of the trouble had for the person I sent it to, they get the error "insufficient image". How can I scale this down in Adobe Acrobat X Pro to a normal 8.5x11 inch sheet so that I can see if that resolves their issue and I can share the document with them. I cannot rescan the document, as I no longer have it. Acrobat is running on Windows 7 OS. The scanner was an HP OfficeJet Pro L7650 All-in-one.

    Read the article

  • Does not recognize usb sticks and drives

    - by Peter
    When connecting any usb stick to my thinkpad ubuntu 10.10 does not recognize them. I don't see anything on the desktop. the output of "dmesg | tail -n10" gives me: [ 1965.696388] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1965.884537] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.072503] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.260349] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.506227] usb 1-1: new high speed USB device using ehci_hcd and address 9 [ 1966.572375] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.760379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.948358] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.136335] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.325423] hub 1-0:1.0: unable to enumerate USB device on port 1 When connecting my usb scanner to the same port: [ 2008.480135] usb 1-1: new high speed USB device using ehci_hcd and address 65 [ 2008.548389] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.736786] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.924379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.112348] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.300443] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.488536] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.732180] usb 1-1: new high speed USB device using ehci_hcd and address 71 [ 2014.796299] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2018.000128] usb 2-1: new full speed USB device using uhci_hcd and address 3 And ubuntu 10.10 recognizes that scanner. So: What can i do to see my usb stick? BTW: on my other Thinkpad running fedora 14 it works perfectly... Cheers -Peter

    Read the article

  • ubuntu 10.10 does not recognize usb sticks and drives

    - by Peter
    When connecting any usb stick to my thinkpad ubuntu 10.10 does not recognize them. I don't see anything on the desktop. the output of "dmesg | tail -n10" gives me: [ 1965.696388] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1965.884537] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.072503] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.260349] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.506227] usb 1-1: new high speed USB device using ehci_hcd and address 9 [ 1966.572375] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.760379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.948358] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.136335] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.325423] hub 1-0:1.0: unable to enumerate USB device on port 1 When connecting my usb scanner to the same port: [ 2008.480135] usb 1-1: new high speed USB device using ehci_hcd and address 65 [ 2008.548389] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.736786] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.924379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.112348] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.300443] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.488536] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.732180] usb 1-1: new high speed USB device using ehci_hcd and address 71 [ 2014.796299] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2018.000128] usb 2-1: new full speed USB device using uhci_hcd and address 3 And ubuntu 10.10 recognizes that scanner. So: What can i do to see my usb stick? BTW: on my other Thinkpad running fedora 14 it works perfectly... Cheers -Peter

    Read the article

  • Help to organize game cycle in Java

    - by ASIO22
    I'm pretty new here (as though to a game development). So here's my question. I'm trying to organize a really simple game cycle in my public static main() as follows: Scanner sc = new Scanner(System.in); //Running the game cycle boolean flag=true; while (flag) { int action; System.out.println("Type your action please:"); System.out.println("0: Exit app"); try { action = sc.nextInt(); switch (action) { case 0: flag=false; break; case 1: break; } } catch (InputMismatchException ex) { System.out.println(ex.getClass() + "\n" + "Please type a correct input\n"); //action = sc.nextInt(); continue; } What's wrong with this cycle: I want to catch an exception when user types text instead of number, show a message, warning user, and the continue game cycle, read user input etc. But instead of that, when users types wrong data, it goes into a eternal cycle without even prompting user. What I did wrong?

    Read the article

  • Windows system drive letter changed after repair install

    - by taffer
    yesterday I did a repair install, because Windows froze on welcome screen after resizing its partition on a dual boot system. corresponding question Everything worked fine so far, but now I am facing another challenge: The Windows drive letter changed from G: to C:, so that most programs, including drivers, firewall and virus scanner do not work anymore. I tried to reinstall the virus scanner, but the uninstaller said, that drive G: is not available. What to do now, to get all programs running again? Is it possible, to rename C: to G: or will that mess up my system?

    Read the article

  • program logic of printing the prime numbers

    - by Vignesh Vicky
    can any body help to understand this java program it just print prime n.o ,as you enter how many you want and it works good class PrimeNumbers { public static void main(String args[]) { int n, status = 1, num = 3; Scanner in = new Scanner(System.in); System.out.println("Enter the number of prime numbers you want"); n = in.nextInt(); if (n >= 1) { System.out.println("First "+n+" prime numbers are :-"); System.out.println(2); } for ( int count = 2 ; count <=n ; ) { for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) { if ( num%j == 0 ) { status = 0; break; } } if ( status != 0 ) { System.out.println(num); count++; } status = 1; num++; } } } i dont understand this for loop condition for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) why we are taking sqrt of num...which is 3....why we assumed it as 3?

    Read the article

  • HP Cue-Scanning Flow component freezes

    - by Nathan Fellman
    I am trying to scan with an HP network scanner (actually E6500 all-in-one). Whenever I try to scan, it starts up a flash screen with HP Scanning written all over it, which proceeds to do nothing. Digging in, I found that the process that gets stuck is hpqkygrp.exe, aka "HP CUE-Scanning Flow Component". This happened when I tried scanning from onenote or from the HP Solution Center. However, it seems that scanning from Windows' Fax and Scan utility works fine. As a (probably related) side-note, scanning directly from the scanner (using the buttons on its panel) doesn't work either. How can I keep this process from getting stuck?

    Read the article

  • What is the best way to run ClamAV on Windows Server 2008 R2

    - by gabbsmo
    I'm hosting a Wordpress-site on Windows Server 2008 RS and want to scan all files that are uploaded by users for viruses using this plugin http://wordpress.org/extend/plugins/upload-scanner/. I'm on a really tight budget (no profit) so ClamAV seem like a good choice. What is the best way to run ClamAV under these circumstances? I'm concidering the following options: Just running the raw windows build from http://sourceforge.net/projects/clamav/ an setup definition updates with task scheduler. Any way to automate updates of the scanner (binaries)? Using a "distro" like ClamWin or Immunet (advertised on clamav.net). Any suggestions are welcome.

    Read the article

  • Prevent machine in a LAN from receiving a remote shutdown

    - by WebDevHobo
    I'm probably just overreacting, but I recently came across a LAN-scanner that showed me the option "remote shutdown", for all found computers on the scanned network. Now, how exactly does this work? If I send such a message, will the shutdown happen no matter what, or is it required to have the password/user-name of the user of that other computer. Mostly I'm wondering: can this be done to me and how do I prevent it? EDIT: what's more, I had the scanner check for shares. The result being this: Double clicking the links opens them in explorer, basically meaning my entire C and F drive(only 2 HD's I have) are completely exposed to anyone in my LAN. Or can I open these because it's my own machine?

    Read the article

  • keyPressed is not working after adding ActionListener to JButton

    - by Yehonatan
    I have a serious problem while trying to build a menu for my game. I've added two JButton to a main JPanel and added an ActionListener for each of them. The main JPanel also contains the game JPanel which have the keyPressed method inside keyController. That's how it looks - Main -       JPanel -         JButton, JButton,         JPanel which contains the game and keyPressed function inside KeyController class which worked fine before I added the ActionListener for JButton. For some reason after I added an ActionListener for each of the button, the game JPanel is not getting any keyPreseed events nor KeyRealesed. Does anyone know the solution for my situation? Thank you very much! Main window - Scanner in = new Scanner(System.in); JFrame f = new JFrame("Square V.S Circles"); f.setUndecorated(true); f.setResizable(false); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.add(new JPanelHandler()); f.pack(); f.setVisible(true); f.setLocationRelativeTo(null); JPanelHandler(main JPanel) - super.setFocusable(true); JButton mybutton = new JButton("Quit"); JButton sayhi = new JButton("Say hi"); sayhi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Hi"); } }); mybutton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); add(mybutton); add(sayhi); add(new Board(2)); Board KeyController(The code inside is working so it's unnecessary to put it here) - private class KeyController extends KeyAdapter { public KeyController() { ..Code } @Override public void keyPressed(KeyEvent e) { ...Code } @Override public void keyReleased(KeyEvent e){ ...Code } }

    Read the article

  • Index Check and Correct Character Display in a Console Hangman Game for Java

    - by Jen
    I have this problem wherein, I can not display the correct characters given by the character. Here's what I meant: String words, in; String replaced_words; Scanner s = new Scanner (System.in); System.out.println("Enter a line of words basing on an event, verse, place or a name of a person."); words = s.nextLine(); System.out.println("The words you just placed are now accepted."); //using char array method, we tried to place the words into a characters array. char [] c = words.toCharArray(); // we need to replace the replaced_words = words.replace(' ', '_').replaceAll("[^\\-]", "-"); for (int i = 0; i < replaced_words.length(); i++) { System.out.print(replaced_words.charAt(i) + " "); } System.out.println("Now, please input a character, guessing the words you just placed."); in = s.nextLine(); in that code, want that the user, when types a word (or should it be character?), any of the correct character the user inputs will be displayed, and changes the hyphen to it...(more like the hangman series of games). How can I achieve this?

    Read the article

  • Add & Show data in Java ArrayList [closed]

    - by Kaidul Islam Sazal
    I have a class inside a main class : static class Graph{ static int u, v, cost; } I have instantiated an arraylist of the class: static List<Graph> g = new ArrayList<Graph>(); And I insert several values into the arraylist like this: Scanner input = new Scanner(System.in); for (int i = 0; i < edge_no; i++) { Graph e = new Graph(); e.u = input.nextInt(); e.v = input.nextInt(); e.cost = input.nextInt(); g.add(e); } And I print it like this: for (int i = 0; i < edge_no; i++) { System.out.println(g.get(i).u + " " + g.get(i).v + " " + g.get(i).cost); } But the problem is that, when I print it, only the last value is shown all the time.It seems that, all the previous values are over-written with it. Input : 1 2 5 1 3 8 2 3 9 Output: 2 3 9 2 3 9 2 3 9 Expected output is just like the input.But I can't fix the problem as I am novice in java.

    Read the article

  • Ninject 3.0 MVC kernel.bind error Auto Registration

    - by user295734
    Getting and error on kernel.Bind(scanner = ... "scanner" has the little error line under it in VS 2010. Cannot convert lambda expression to type 'System.Type[]' because it is not a delegate type Tyring to Auto Register like the old kernel.scan in 2.0. I can not figure out what i am doing wrong. Added and removed so many Ninject packages. completely lost, getting to be a big waste of time. using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; //using Ninject.Extensions.Conventions; using Ninject.Web.WebApi; using Ninject.Web.Mvc; using CommonServiceLocator.NinjectAdapter; using System.Reflection; using System.IO; using LR.Repository; using LR.Repository.Interfaces; using LR.Service.Interfaces; using System.Web.Http; public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind(scanner => scanner.FromAssembliesInPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)) .Select(IsServiceType) .BindToDefaultInterface() .Configure(binding => binding.InSingletonScope()) ); } private static bool IsServiceType(Type type) { // temp return true; // .Any() is not recognized either. return true; // type.IsClass && type.GetInterfaces().Any(intface => intface.Name == "I" + type.Name); }

    Read the article

  • non-static variable cannot be referenced from a static context (java)

    - by Greg
    I ask that you ignore all logic.. i was taught poorly at first and so i still dont understand everything about static crap and its killing me. My error is with every single variable that i declare then try to use later inside my methods... i get the non-static variable cannot~~ error I can simply put all the rough coding of my methods inside my cases, and it works but then i cannot use recursion... What i really need is someone to help on the syntax and point me on the right direction of how to have my methods recognize my variables at the top... like compareCount etc thanks public class MyProgram7 { public static void main (String[]args) throws IOException{ Scanner scan = new Scanner(System.in); int compareCount = 0; int low = 0; int high = 0; int mid = 0; int key = 0; Scanner temp; int[]list; String menu, outputString; int option = 1; boolean found = false; // Prompt the user to select an option menu = "\n\t1 Reads file" + "\n\t2 Finds a specific number in the list" + "\n\t3 Prints how many comparisons were needed" + "\n\t0 Quit\n\n\n"; System.out.println(menu); System.out.print("\tEnter your selection: "); option = scan.nextInt(); // Keep reading data until the user enters 0 while (option != 0) { switch (option) { case 1: readFile(); break; case 2: findKey(list,low,high,key); break; case 3: printCount(); break; default: outputString = "\nInvalid Selection\n"; System.out.println(outputString); break; }//end of switch System.out.println(menu); System.out.print("\tEnter your selection: "); option = scan.nextInt(); }//end of while }//end of main public static void readFile() { int i = 0; temp = new Scanner(new File("CS1302_Data7_2010.txt")); while(temp.hasNext()) { list[i]= temp.nextInt(); i++; }//end of while temp.close(); System.out.println("File Found..."); }//end of readFile() public static void findKey() { while(found!=true) { while(key < 100 || key > 999) { System.out.println("Please enter the number you would like to search for? ie 350: "); key = scan.nextInt(); }//end of inside while //base if (low <= high) { mid = ((low+high)/2); if (key == list[mid]) { found = true; compareCount++; }//end of inside if }//end of outside if else if (key < list[mid]) { compareCount++; high = mid-1; findKey(list,low,high,key); }//end of else if else { compareCount++; low = mid+1; findKey(list,low,high,key); }//end of else }//end of outside while }//end of findKey() public static void printCount() { System.out.println("Total number of comparisons is: " + compareCount); }//end of printCount }//end of class

    Read the article

  • how to read data from file into array? java

    - by lox
    I need some help reading data from a txt file into my ArrayList. I know the code is pretty messy, but just try to take a look at it. The first part with the creating and putting the ArrayList into the txt file works perfectly. I just need some help at the end in the "marked" area. Sorry if I still have some words in my native language, but I didn't really had the time to translate everything. public class ContAngajat { String username; String password; } public class CreazaCont { // creating the arraylist and putting it into a file public static void ang(String args[]) { ArrayList<ContAngajat> angajati=new ArrayList<ContAngajat>(50); Scanner diskScanner = new Scanner(in); Scanner forn = new Scanner(in); int n; out.print("Introduceti numarul de conturi noi care doriti sa le introduceti: "); n=forn.nextInt(); out.println(); try{ FileWriter fw = new FileWriter("ConturiAngajati.txt", true); for(int i=0; i<n; i++){ ContAngajat cont = new ContAngajat(); out.print("Username: "); cont.username=diskScanner.nextLine(); out.print("Password: "); cont.password=diskScanner.nextLine(); angajati.add(cont); fw.write(cont.username + " "); fw.write(cont.password +"|"); } fw.close(); } catch(IOException ex){ System.out.println("Could not write to file"); System.exit(0); } for (int i=0; i<n; i++) { out.println("username: " + angajati.get(i).username + " password: " +angajati.get(i).password ); } } // HERE I'M TRING TO GET THE ARRAYLIST OUT OF THE FILE public static void RdAng(String args[]) { ArrayList<ContAngajat> angajati=new ArrayList<ContAngajat>(50); ContAngajat cont = new ContAngajat(); int count,i2,i; try{ FileReader fr = new FileReader("ConturiAngajati.txt"); BufferedReader br = new BufferedReader(fr); String line = ""; while((line=br.readLine())!=null) { String[] theline=line.split("|"); count=theline.length; for(i=0;i<theline.length;i++) { String[] theword = theline[i].split(" "); } } for(i2=0;i2<count;i2++) { ContAngajat contrd = new ContAngajat(); // "ERROR" OVER HERE for (int ird=0; ird <theword.length; ird++) { cont.username=theword[0]; cont.password=theword[1]; // they keep telling me "theword cannot be resolved" whenever i try to run this } angajati.add(contrd); } } catch(IOException ex){ System.out.println("Could not read to file"); System.exit(0); } } }

    Read the article

  • (This is for a project, so yes it is homework) How would I finish this java code?

    - by user2924318
    The task is to create arrays using user input (which I was able to do), then for the second part, use a separate method to sort the array in ascending order then output it. I have gotten it to do everything I need except I don't know how I would get it to sort. The directions say to use a while loop from 0 to the length to find the minimum value then swap that with the 1st, but I don't know how to do this. This is what I have so far: public static void main(String[] args) { Scanner in = new Scanner(System.in); int storage = getNumDigits(in); if(storage == 0){ System.out.print("No digits to store? OK, goodbye!"); System.exit(0); } int []a = new int [storage]; a = getDigits(a, in); displayDigits(a); selectionSort(a); } private static int getNumDigits(Scanner inScanner) { System.out.print("Please enter the number of digits to be stored: "); int stored = inScanner.nextInt(); while(stored < 0){ System.out.println("ERROR! You must enter a non-negative number of digits!"); System.out.println(); System.out.print("Please enter the number of digits to be stored: "); stored = inScanner.nextInt(); } return stored; } private static int[] getDigits(int[] digits, Scanner inScanner) { int length = digits.length; int count = 0; int toBeStored = 0; while(count < length){ System.out.print("Enter integer " +count +": "); toBeStored = inScanner.nextInt(); digits[count] = toBeStored; count++; } return digits; } private static void displayDigits(int[] digits) { int len = digits.length; System.out.println(); System.out.println("Array before sorting:"); System.out.println("Number of digits in array: " +len); System.out.print("Digits in array: "); for(int cnt = 0; cnt < len-1; cnt++){ System.out.print(digits[cnt] + ", "); } System.out.println(digits[len-1]); } private static void selectionSort(int[] digits) { int l = digits.length; System.out.println(); System.out.println("Array after sorting:"); System.out.println("Number of digits in array: " +l); System.out.print("Digits in array: "); int index = 0; int value = digits[0]; int indVal = digits[index]; while(index < l){ indVal = digits[index]; if(indVal <= value){ indVal = value; digits[index] = value; index++; } else if(value < indVal){ index++; } System.out.print(value); //This is where I don't know what to do. } }

    Read the article

  • Adding Polynomials (Linked Lists)......Bug Help

    - by Brian
    I have written a program that creates nodes that in this class are parts of polynomials and then the two polynomials get added together to become one polynomial (list of nodes). All my code compiles so the only problem I am having is that the nodes are not inserting into the polynomial via the insert method I have in polynomial.java and when running the program it does create nodes and displays them in the 2x^2 format but when it comes to add the polynomials together it displays o as the polynomials, so if anyone can figure out whats wrong and what I can do to fix it it would be much appreciated. Here is the code: import java.util.Scanner; class Polynomial{ public termNode head; public Polynomial() { head = null; } public boolean isEmpty() { return (head == null); } public void display() { if (head == null) System.out.print("0"); else for(termNode cur = head; cur != null; cur = cur.getNext()) { System.out.println(cur); } } public void insert(termNode newNode) { termNode prev = null; termNode cur = head; while (cur!=null && (newNode.compareTo(cur)<0)) { prev = null; cur = cur.getNext(); } if (prev == null) { newNode.setNext(head); head = newNode; } else { newNode.setNext(cur); prev.setNext(newNode); } } public void readPolynomial(Scanner kb) { boolean done = false; double coefficient; int exponent; termNode term; head = null; //UNLINK ANY PREVIOUS POLYNOMIAL System.out.println("Enter 0 and 0 to end."); System.out.print("coefficient: "); coefficient = kb.nextDouble(); System.out.println(coefficient); System.out.print("exponent: "); exponent = kb.nextInt(); System.out.println(exponent); done = (coefficient == 0 && exponent == 0); while(!done) { Polynomial poly = new Polynomial(); term = new termNode(coefficient,exponent); System.out.println(term); poly.insert(term); System.out.println("Enter 0 and 0 to end."); System.out.print("coefficient: "); coefficient = kb.nextDouble(); System.out.println(coefficient); System.out.print("exponent: "); exponent = kb.nextInt(); System.out.println(exponent); done = (coefficient==0 && exponent==0); } } public static Polynomial add(Polynomial p, Polynomial q) { Polynomial r = new Polynomial(); double coefficient; int exponent; termNode first = p.head; termNode second = q.head; termNode sum = r.head; termNode term; while (first != null && second != null) { if (first.getExp() == second.getExp()) { if (first.getCoeff() != 0 && second.getCoeff() != 0); { double addCoeff = first.getCoeff() + second.getCoeff(); term = new termNode(addCoeff,first.getExp()); sum.setNext(term); first.getNext(); second.getNext(); } } else if (first.getExp() < second.getExp()) { sum.setNext(second); term = new termNode(second.getCoeff(),second.getExp()); sum.setNext(term); second.getNext(); } else { sum.setNext(first); term = new termNode(first.getNext()); sum.setNext(term); first.getNext(); } } while (first != null) { sum.setNext(first); } while (second != null) { sum.setNext(second); } return r; } } Here is my Node class: class termNode implements Comparable { private int exp; private double coeff; private termNode next; public termNode(double coefficient, int exponent) { coeff = coefficient; exp = exponent; next = null; } public termNode(termNode inTermNode) { coeff = inTermNode.coeff; exp = inTermNode.exp; } public void setData(double coefficient, int exponent) { coefficient = coeff; exponent = exp; } public double getCoeff() { return coeff; } public int getExp() { return exp; } public void setNext(termNode link) { next = link; } public termNode getNext() { return next; } public String toString() { if (exp == 0) { return(coeff + " "); } else if (exp == 1) { return(coeff + "x"); } else { return(coeff + "x^" + exp); } } public int compareTo(Object other) { if(exp ==((termNode) other).exp) return 0; else if(exp < ((termNode) other).exp) return -1; else return 1; } } And here is my Test class to run the program. import java.util.Scanner; class PolyTest{ public static void main(String [] args) { Scanner kb = new Scanner(System.in); Polynomial r; Polynomial p = new Polynomial(); System.out.println("Enter first polynomial."); p.readPolynomial(kb); Polynomial q = new Polynomial(); System.out.println(); System.out.println("Enter second polynomial."); q.readPolynomial(kb); r = Polynomial.add(p,q); System.out.println(); System.out.print("The sum of "); p.display(); System.out.print(" and "); q.display(); System.out.print(" is "); r.display(); } }

    Read the article

  • NullPointerException, Collections not storing data?

    - by Elliott
    Hi there, I posted this question earlier but not with the code in its entirety. The coe below also calls to other classes Background and Hydro which I have included at the bottom. I have a Nullpointerexception at the line indicate by asterisks. Which would suggest to me that the Collections are not storing data properly. Although when I check their size they seem correct. Thanks in advance. PS: If anyone would like to give me advice on how best to format my code to make it readable, it would be appreciated. Elliott package exam0607; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Collection; import java.util.Scanner; import java.util.Vector; import exam0607.Hydro; import exam0607.Background;// this may not be necessary???? FIND OUT public class HydroAnalysis { public static void main(String[] args) { Collection hydroList = null; Collection backList = null; try{hydroList = readHydro("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_data.dat");} catch (IOException e){ e.getMessage();} try{backList = readBackground("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_bgd.dat"); //System.out.println(backList.size()); } catch (IOException e){ e.getMessage();} for(int i =0; i <=14; i++ ){ String nameroot = "HJK"; String middle = Integer.toString(i); String hydroName = nameroot + middle + "X"; System.out.println(hydroName); ALGO_1(hydroName, backList, hydroList); } } public static Collection readHydro(String url) throws IOException { URL u = new URL(url); InputStream is = u.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader b = new BufferedReader(isr); String line =""; Collection data = new Vector(); while((line = b.readLine())!= null){ Scanner s = new Scanner(line); String name = s.next(); System.out.println(name); double starttime = Double.parseDouble(s.next()); System.out.println(+starttime); double increment = Double.parseDouble(s.next()); System.out.println(+increment); double p = 0; double nterms = 0; while(s.hasNextDouble()){ p = Double.parseDouble(s.next()); System.out.println(+p); nterms++; System.out.println(+nterms); } Hydro SAMP = new Hydro(name, starttime, increment, p); data.add(SAMP); } return data; } public static Collection readBackground(String url) throws IOException { URL u = new URL(url); InputStream is = u.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader b = new BufferedReader(isr); String line =""; Vector data = new Vector(); while((line = b.readLine())!= null){ Scanner s = new Scanner(line); String name = s.next(); //System.out.println(name); double starttime = Double.parseDouble(s.next()); //System.out.println(starttime); double increment = Double.parseDouble(s.next()); //System.out.println(increment); double sum = 0; double p = 0; double nterms = 0; while((s.hasNextDouble())){ p = Double.parseDouble(s.next()); //System.out.println(p); nterms++; sum += p; } double pbmean = sum/nterms; Background SAMP = new Background(name, starttime, increment, pbmean); //System.out.println(SAMP); data.add(SAMP); } return data; } public static void ALGO_1(String hydroName, Collection backgs, Collection hydros){ //double aMin = Double.POSITIVE_INFINITY; //double sum = 0; double intensity = 0; double numberPN_SIG = 0; double POSITIVE_PN_SIG =0; //int numberOfRays = 0; for(Hydro hd: hydros){ System.out.println(hd.H_NAME); for(Background back : backgs){ System.out.println(back.H_NAME); if(back.H_NAME.equals(hydroName)){//ERROR HERE double PN_SIG = Math.max(0.0, hd.PN - back.PBMEAN); numberPN_SIG ++; if(PN_SIG 0){ intensity += PN_SIG; POSITIVE_PN_SIG ++; } } } double positive_fraction = POSITIVE_PN_SIG/numberPN_SIG; if(positive_fraction < 0.5){ System.out.println( hydroName + "is faulty" ); } else{System.out.println(hydroName + "is not faulty");} System.out.println(hydroName + "has instensity" + intensity); } } } THE BACKGROUND CLASS package exam0607; public class Background { String H_NAME; double T_START; double DT; double PBMEAN; public Background(String name, double starttime, double increment, double pbmean) { name = H_NAME; starttime = T_START; increment = DT; pbmean = PBMEAN; }} AND THE HYDRO CLASS public class Hydro { String H_NAME; double T_START; double DT; double PN; public double n; public Hydro(String name, double starttime, double increment, double p) { name = H_NAME; starttime = T_START; increment = DT; p = PN; } }

    Read the article

  • http server implentation, the page does not show properly

    - by none
    well, as i am doing a small project of coding an http server. the code is at http://code.google.com/p/reactor/ the current puzzle is when asked to parse a page with java script and css. As an http server it just sends a page (copied from another website) and it parsed inproperly. when a simple html page is been parse , by my firefox, it shows ok, however when parsing a more complex page(css+javascript) the page is all wired like this : ???? ????? if(getCookie('pais999')==null){varisToplayerDouble="True";isToplayerDouble=(isToplayerDouble=="True")?true:falsevarToplayerCookieName='pais999';varTopLayerCookieExpiredDays=1;varToplayerLink='http://xads.zedo.com/ads2/c?a=239671;g=0;c=455000000;i=0;x=7168;n=455;s=0;k=http://www.pais.co.il/Pais/Games/Lotto/';varToplayerImpression='http://l4.zedo.com/log/p.gif?a=239671;c=455000000;x=7168;n=455;e=i;i=0;s=0;z='+Math.random();varToplayerBigPath='pais/January2007/98one_toplayer.swf';varToplayerSmallPath='pais/January2007/98one_reminder.swf';varToplayerBigWidth=1005;varToplayerBigHeight=500;varToplayerSmallWidth=100;varToplayerSmallHeight=100;varToplayerBigLeft=(0==0)?resWidth/2-ToplayerBigWidth/2:resWidth/2-ToplayerBigWidth/2+0varToplayerBigTop=0;varToplayerSmallLeft=resWidth-ToplayerSmallWidth-0;varToplayerSmallTop=0;varSecondsToChangeBigToSmall=15;}elseif(getCookie('NF999')==null){varisToplayerDouble="True";isToplayerDouble=(isToplayerDouble=="True")?true:falsevarToplayerCookieName='NF999';varTopLayerCookieExpiredDays=1;varToplayerLink='http://xads.zedo.com/ads2/c?a=238663;g=0;c=455000000;i=0;x=7168;n=455;s=0;k=http://www.new-pharm.co.il/SkiGame/?ToolID=OLJD8O';varToplayerImpression='http://l4.zedo.com/log/p.gif?a=238663;c=455000000;x=7168;n=455;e=i;i=0;s=0;z='+Math.random();varToplayerBigPath='NewFarm/Ski/995ONE_TopLayer_550x360.swf';varToplayerSmallPath='NewFarm/Ski/995ONE_Reminder_100x100.swf';varToplayerBigWidth=550;varToplayerBigHeight=360;varToplayerSmallWidth=100;varToplayerSmallHeight=100;varToplayerBigLeft=(0==0)?resWidth/2-ToplayerBigWidth/2:resWidth/2-ToplayerBigWidth/2+0varToplayerBigTop=0;varToplayerSmallLeft=resWidth-ToplayerSmallWidth-0;varToplayerSmallTop=0;varSecondsToChangeBigToSmall=15;}elseif(1==0){}$("divToplayerBig").style.width=ToplayerBigWidth;$("divToplayerBig").style.height=ToplayerBigHeight;$("divToplayerBig").style.left=resWidth/2-ToplayerBigWidth/2;$("divToplayerSmall").style.width=ToplayerSmallWidth;$("divToplayerSmall").style.height=ToplayerSmallHeight;$("divToplayerSmall").style.right=ToplayerSmallWidthvartopOff=0;if(ToplayerBigTop0)topOff=resHeight-ToplayerBigHeight+ToplayerBigTop;varisMain=false;#divToplayerBig{position:absolute;right:20px;bottom:1px;}bodydiv#divToplayerBig{position:fixed;}#divToplayerSmall{position:absolute;right:20px;bottom:10px;}bodydiv#divToplayerSmall{position:fixed;}????|??????LIVE|???????????|ONE???????|ONETV |????'??|BigONE|?????????| CrazyONE | where the source code of the html is : ONE:???:??????????????????????????? ????  ????? if(getCookie('pais999')==null){varisToplayerDouble="True";isToplayerDouble=(isToplayerDouble=="True")?true:falsevarToplayerCookieName='pais999';varTopLayerCookieExpiredDays=1;varToplayerLink='http://xads.zedo.com/ads2/c?a=239671;g=0;c=455000000;i=0;x=7168;n=455;s=0;k=http://www.pais.co.il/Pais/Games/Lotto/';varToplayerImpression='http://l4.zedo.com/log/p.gif?a=239671;c=455000000;x=7168;n=455;e=i;i=0;s=0;z='+Math.random();varToplayerBigPath='pais/January2007/98one_toplayer.swf';varToplayerSmallPath='pais/January2007/98one_reminder.swf';varToplayerBigWidth=1005;varToplayerBigHeight=500;varToplayerSmallWidth=100;varToplayerSmallHeight=100;varToplayerBigLeft=(0==0)?resWidth/2-ToplayerBigWidth/2:resWidth/2-ToplayerBigWidth/2+0varToplayerBigTop=0;varToplayerSmallLeft=resWidth-ToplayerSmallWidth-0;varToplayerSmallTop=0;varSecondsToChangeBigToSmall=15;}elseif(getCookie('NF999')==null){varisToplayerDouble="True";isToplayerDouble=(isToplayerDouble=="True")?true:falsevarToplayerCookieName='NF999';varTopLayerCookieExpiredDays=1;varToplayerLink='http://xads.zedo.com/ads2/c?a=238663;g=0;c=455000000;i=0;x=7168;n=455;s=0;k=http://www.new-pharm.co.il/SkiGame/?ToolID=OLJD8O';varToplayerImpression='http://l4.zedo.com/log/p.gif?a=238663;c=455000000;x=7168;n=455;e=i;i=0;s=0;z='+Math.random();varToplayerBigPath='NewFarm/Ski/995ONE_TopLayer_550x360.swf';varToplayerSmallPath='NewFarm/Ski/995ONE_Reminder_100x100.swf';varToplayerBigWidth=550;varToplayerBigHeight=360;varToplayerSmallWidth=100;varToplayerSmallHeight=100;varToplayerBigLeft=(0==0)?resWidth/2-ToplayerBigWidth/2:resWidth/2-ToplayerBigWidth/2+0varToplayerBigTop=0;varToplayerSmallLeft=resWidth-ToplayerSmallWidth-0;varToplayerSmallTop=0;varSecondsToChangeBigToSmall=15;}elseif(1==0){}$("divToplayerBig").style.width=ToplayerBigWidth;$("divToplayerBig").style.height=ToplayerBigHeight;$("divToplayerBig").style.left=resWidth/2-ToplayerBigWidth/2;$("divToplayerSmall").style.width=ToplayerSmallWidth;$("divToplayerSmall").style.height=ToplayerSmallHeight;$("divToplayerSmall").style.right=ToplayerSmallWidthvartopOff=0;if(ToplayerBigTop0)topOff=resHeight-ToplayerBigHeight+ToplayerBigTop;varisMain=false;#divToplayerBig{position:absolute;right:20px;bottom:1px;}bodydiv#divToplayerBig{position:fixed;}div#divToplayerBig{right:auto;bottom:auto;left:expression((-20-divToplayerBig.offsetWidth+(document.documentElement.clientWidth?document.documentElement.clientWidth:document.body.clientWidth)+(ignoreMe2=document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft))+'px');top:expression((0-divToplayerBig.offsetHeight-topOff+(document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight)+(ignoreMe=document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop))+'px');}#divToplayerSmall{position:absolute;right:20px;bottom:10px;}bodydiv#divToplayerSmall{position:fixed;}div#divToplayerSmall{right:auto;bottom:auto;left:expression((-20-divToplayerSmall.offsetWidth+(document.documentElement.clientWidth?document.documentElement.clientWidth:document.body.clientWidth)+(ignoreMe2=document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft))+'px');top:expression((0-divToplayerSmall.offsetHeight+(document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight)+(ignoreMe=document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop))+'px');}varisTopTrans=(ToplayerBigPath.indexOf("transparent")-1)?false:true;varisRemTrans=(ToplayerSmallPath.indexOf("transparent")-1)?false:true;vartop1session=3;vartop2session=5;InitToplayer(isTopTrans,isRemTrans);window.onload=StartToplayer;????|??????LIVE|???????????|ONE???????|ONETV |????'??|BigONE|?????????|  CrazyONE |????????????????????????????????????????????????????????19/01/07  19:30?????????????????????-?????:?????????????????????????19/01/07  18:43??????????????:??????????????????????19/01/07  17:41???:??????????????????????????????????19/01/07  16:49?????:??????"?????????????/?????1:2,??????"??????19/01/07  16:45????????????????????????????,?????2.5???????????????19/01/07  16:37???????:???"?????????????????-19:30?????????????19/01/07  14:32?????"?????????-18:30?????????"????????,????'??????19/01/07  14:45????????????????????????????????"?:??????????????19/01/07  14:37??????????:??????????????????????????????0:019/01/07  13:46varswfPeleSmall=newSWFObject("http://images.one.co.il/images/PeleEmulator/emulator_pelephone_01a.swf","peleSmall",160,470,"6","#FFFFFF");swfPeleSmall.addParam("quality","high");swfPeleSmall.addParam("wmode","transparent");swfPeleSmall.write("divPeleSmall");varswfPeleBig=newSWFObject("http://images.one.co.il/images/PeleEmulator/emulator_pelephone_02d.swf","peleBig",400,470,"6","#FFFFFF");swfPeleBig.addParam("quality","high");swfPeleBig.addParam("wmode","transparent");swfPeleBig.write("divWithBig");???:???????????????????????????????????????-ONE????????????????????????????????????????????.????????,???????????1:2,?????????????:"???????????"DisplayFlash("W_S_round_border_pic.swf","156","201","1","style=position:absolute");?????????????????????????(??????)?????????                          19/01/20077:26???????????????(????)????????????????????????????6:3,5:7?-5:7???????????????????????,???????23?????.?????,????????????????????????????????,???????????????????????????????????????????,????????????????????.??????????????????????????,??????????????????????????.????????????????????????????-1:1?????????.?????????????????????????????'?????????????????????????????.?????????????.???????????????????????????????(16???????),???????????????????????????????????????3???????,???????????????????????.????????- (only part of of the page presentation in firefox and page source html) why is it happening? what is midding in the http response? StringBuffer tResponse = new StringBuffer(); tResponse.append("HTTP/1.1 200 OK\n"); tResponse.append("Date: "+new Date().toString() +'\n'); tResponse.append("server: http-reactor/0.1-dev\n"); tResponse.append("last-Modified:"+ d.toString() +'\n'); tResponse.append("Content-Type: text/html; charset=windows-1255\n"); tResponse.append("Accept-Language: he; q=1.0, en; q=0.5:); tResponse.append("Content-Length: "+tFileContent.length()+'\n'); tResponse.append('\n'); tResponse.append(tFileContent); public StringBuffer FetchData(String FileName) throws FileNotFoundException{ StringBuffer tFileContent = new StringBuffer(); if (FileName.contains("../")) throw new SecurityException(); if (FileName.equals("/")) FileName = "\\index.html"; FileName.replace('/', '\\'); File f = new File(_root + FileName); Scanner scanner = new Scanner(f); while(scanner.hasNext()) tFileContent.append(scanner.next()); return generateResponse(tFileContent,f.lastModified()); } private StringBuffer generateResponse(StringBuffer tFileContent, long l) { StringBuffer tResponse = new StringBuffer(); Date d = new Date(l); tResponse.append("HTTP/1.1 200 OK\n"); tResponse.append("Date: "+new Date().toString() +'\n'); tResponse.append("server: http-reactor/0.1-dev\n"); tResponse.append("last-Modified:"+ d.toString() +'\n'); tResponse.append("Content-Type: text/html; charset=windows-1255\n"); tResponse.append("Accept-Language: he; q=1.0, en; q=0.5:); tResponse.append("Content-Length: "+tFileContent.length()+'\n'); tResponse.append('\n'); tResponse.append(tFileContent); return tResponse; }

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >